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 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
205   if (checkArgCount(S, TheCall, 3))
206     return true;
207 
208   // First two arguments should be integers.
209   for (unsigned I = 0; I < 2; ++I) {
210     ExprResult Arg = TheCall->getArg(I);
211     QualType Ty = Arg.get()->getType();
212     if (!Ty->isIntegerType()) {
213       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
214           << Ty << Arg.get()->getSourceRange();
215       return true;
216     }
217     InitializedEntity Entity = InitializedEntity::InitializeParameter(
218         S.getASTContext(), Ty, /*consume*/ false);
219     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
220     if (Arg.isInvalid())
221       return true;
222     TheCall->setArg(I, Arg.get());
223   }
224 
225   // Third argument should be a pointer to a non-const integer.
226   // IRGen correctly handles volatile, restrict, and address spaces, and
227   // the other qualifiers aren't possible.
228   {
229     ExprResult Arg = TheCall->getArg(2);
230     QualType Ty = Arg.get()->getType();
231     const auto *PtrTy = Ty->getAs<PointerType>();
232     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
233           !PtrTy->getPointeeType().isConstQualified())) {
234       S.Diag(Arg.get()->getBeginLoc(),
235              diag::err_overflow_builtin_must_be_ptr_int)
236           << Ty << Arg.get()->getSourceRange();
237       return true;
238     }
239     InitializedEntity Entity = InitializedEntity::InitializeParameter(
240         S.getASTContext(), Ty, /*consume*/ false);
241     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
242     if (Arg.isInvalid())
243       return true;
244     TheCall->setArg(2, Arg.get());
245   }
246   return false;
247 }
248 
249 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
250   if (checkArgCount(S, BuiltinCall, 2))
251     return true;
252 
253   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
254   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
255   Expr *Call = BuiltinCall->getArg(0);
256   Expr *Chain = BuiltinCall->getArg(1);
257 
258   if (Call->getStmtClass() != Stmt::CallExprClass) {
259     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
260         << Call->getSourceRange();
261     return true;
262   }
263 
264   auto CE = cast<CallExpr>(Call);
265   if (CE->getCallee()->getType()->isBlockPointerType()) {
266     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
267         << Call->getSourceRange();
268     return true;
269   }
270 
271   const Decl *TargetDecl = CE->getCalleeDecl();
272   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
273     if (FD->getBuiltinID()) {
274       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
275           << Call->getSourceRange();
276       return true;
277     }
278 
279   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
280     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
281         << Call->getSourceRange();
282     return true;
283   }
284 
285   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
286   if (ChainResult.isInvalid())
287     return true;
288   if (!ChainResult.get()->getType()->isPointerType()) {
289     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
290         << Chain->getSourceRange();
291     return true;
292   }
293 
294   QualType ReturnTy = CE->getCallReturnType(S.Context);
295   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
296   QualType BuiltinTy = S.Context.getFunctionType(
297       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
298   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
299 
300   Builtin =
301       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
302 
303   BuiltinCall->setType(CE->getType());
304   BuiltinCall->setValueKind(CE->getValueKind());
305   BuiltinCall->setObjectKind(CE->getObjectKind());
306   BuiltinCall->setCallee(Builtin);
307   BuiltinCall->setArg(1, ChainResult.get());
308 
309   return false;
310 }
311 
312 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
313 /// __builtin_*_chk function, then use the object size argument specified in the
314 /// source. Otherwise, infer the object size using __builtin_object_size.
315 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
316                                                CallExpr *TheCall) {
317   // FIXME: There are some more useful checks we could be doing here:
318   //  - Analyze the format string of sprintf to see how much of buffer is used.
319   //  - Evaluate strlen of strcpy arguments, use as object size.
320 
321   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
322       isConstantEvaluated())
323     return;
324 
325   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
326   if (!BuiltinID)
327     return;
328 
329   unsigned DiagID = 0;
330   bool IsChkVariant = false;
331   unsigned SizeIndex, ObjectIndex;
332   switch (BuiltinID) {
333   default:
334     return;
335   case Builtin::BI__builtin___memcpy_chk:
336   case Builtin::BI__builtin___memmove_chk:
337   case Builtin::BI__builtin___memset_chk:
338   case Builtin::BI__builtin___strlcat_chk:
339   case Builtin::BI__builtin___strlcpy_chk:
340   case Builtin::BI__builtin___strncat_chk:
341   case Builtin::BI__builtin___strncpy_chk:
342   case Builtin::BI__builtin___stpncpy_chk:
343   case Builtin::BI__builtin___memccpy_chk: {
344     DiagID = diag::warn_builtin_chk_overflow;
345     IsChkVariant = true;
346     SizeIndex = TheCall->getNumArgs() - 2;
347     ObjectIndex = TheCall->getNumArgs() - 1;
348     break;
349   }
350 
351   case Builtin::BI__builtin___snprintf_chk:
352   case Builtin::BI__builtin___vsnprintf_chk: {
353     DiagID = diag::warn_builtin_chk_overflow;
354     IsChkVariant = true;
355     SizeIndex = 1;
356     ObjectIndex = 3;
357     break;
358   }
359 
360   case Builtin::BIstrncat:
361   case Builtin::BI__builtin_strncat:
362   case Builtin::BIstrncpy:
363   case Builtin::BI__builtin_strncpy:
364   case Builtin::BIstpncpy:
365   case Builtin::BI__builtin_stpncpy: {
366     // Whether these functions overflow depends on the runtime strlen of the
367     // string, not just the buffer size, so emitting the "always overflow"
368     // diagnostic isn't quite right. We should still diagnose passing a buffer
369     // size larger than the destination buffer though; this is a runtime abort
370     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
371     DiagID = diag::warn_fortify_source_size_mismatch;
372     SizeIndex = TheCall->getNumArgs() - 1;
373     ObjectIndex = 0;
374     break;
375   }
376 
377   case Builtin::BImemcpy:
378   case Builtin::BI__builtin_memcpy:
379   case Builtin::BImemmove:
380   case Builtin::BI__builtin_memmove:
381   case Builtin::BImemset:
382   case Builtin::BI__builtin_memset: {
383     DiagID = diag::warn_fortify_source_overflow;
384     SizeIndex = TheCall->getNumArgs() - 1;
385     ObjectIndex = 0;
386     break;
387   }
388   case Builtin::BIsnprintf:
389   case Builtin::BI__builtin_snprintf:
390   case Builtin::BIvsnprintf:
391   case Builtin::BI__builtin_vsnprintf: {
392     DiagID = diag::warn_fortify_source_size_mismatch;
393     SizeIndex = 1;
394     ObjectIndex = 0;
395     break;
396   }
397   }
398 
399   llvm::APSInt ObjectSize;
400   // For __builtin___*_chk, the object size is explicitly provided by the caller
401   // (usually using __builtin_object_size). Use that value to check this call.
402   if (IsChkVariant) {
403     Expr::EvalResult Result;
404     Expr *SizeArg = TheCall->getArg(ObjectIndex);
405     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
406       return;
407     ObjectSize = Result.Val.getInt();
408 
409   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
410   } else {
411     // If the parameter has a pass_object_size attribute, then we should use its
412     // (potentially) more strict checking mode. Otherwise, conservatively assume
413     // type 0.
414     int BOSType = 0;
415     if (const auto *POS =
416             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
417       BOSType = POS->getType();
418 
419     Expr *ObjArg = TheCall->getArg(ObjectIndex);
420     uint64_t Result;
421     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
422       return;
423     // Get the object size in the target's size_t width.
424     const TargetInfo &TI = getASTContext().getTargetInfo();
425     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
426     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
427   }
428 
429   // Evaluate the number of bytes of the object that this call will use.
430   Expr::EvalResult Result;
431   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
432   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
433     return;
434   llvm::APSInt UsedSize = Result.Val.getInt();
435 
436   if (UsedSize.ule(ObjectSize))
437     return;
438 
439   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
440   // Skim off the details of whichever builtin was called to produce a better
441   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
442   if (IsChkVariant) {
443     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
444     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
445   } else if (FunctionName.startswith("__builtin_")) {
446     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
447   }
448 
449   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
450                       PDiag(DiagID)
451                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
452                           << UsedSize.toString(/*Radix=*/10));
453 }
454 
455 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
456                                      Scope::ScopeFlags NeededScopeFlags,
457                                      unsigned DiagID) {
458   // Scopes aren't available during instantiation. Fortunately, builtin
459   // functions cannot be template args so they cannot be formed through template
460   // instantiation. Therefore checking once during the parse is sufficient.
461   if (SemaRef.inTemplateInstantiation())
462     return false;
463 
464   Scope *S = SemaRef.getCurScope();
465   while (S && !S->isSEHExceptScope())
466     S = S->getParent();
467   if (!S || !(S->getFlags() & NeededScopeFlags)) {
468     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
469     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
470         << DRE->getDecl()->getIdentifier();
471     return true;
472   }
473 
474   return false;
475 }
476 
477 static inline bool isBlockPointer(Expr *Arg) {
478   return Arg->getType()->isBlockPointerType();
479 }
480 
481 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
482 /// void*, which is a requirement of device side enqueue.
483 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
484   const BlockPointerType *BPT =
485       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
486   ArrayRef<QualType> Params =
487       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
488   unsigned ArgCounter = 0;
489   bool IllegalParams = false;
490   // Iterate through the block parameters until either one is found that is not
491   // a local void*, or the block is valid.
492   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
493        I != E; ++I, ++ArgCounter) {
494     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
495         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
496             LangAS::opencl_local) {
497       // Get the location of the error. If a block literal has been passed
498       // (BlockExpr) then we can point straight to the offending argument,
499       // else we just point to the variable reference.
500       SourceLocation ErrorLoc;
501       if (isa<BlockExpr>(BlockArg)) {
502         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
503         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
504       } else if (isa<DeclRefExpr>(BlockArg)) {
505         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
506       }
507       S.Diag(ErrorLoc,
508              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
509       IllegalParams = true;
510     }
511   }
512 
513   return IllegalParams;
514 }
515 
516 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
517   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
518     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
519         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
520     return true;
521   }
522   return false;
523 }
524 
525 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
526   if (checkArgCount(S, TheCall, 2))
527     return true;
528 
529   if (checkOpenCLSubgroupExt(S, TheCall))
530     return true;
531 
532   // First argument is an ndrange_t type.
533   Expr *NDRangeArg = TheCall->getArg(0);
534   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
535     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
536         << TheCall->getDirectCallee() << "'ndrange_t'";
537     return true;
538   }
539 
540   Expr *BlockArg = TheCall->getArg(1);
541   if (!isBlockPointer(BlockArg)) {
542     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
543         << TheCall->getDirectCallee() << "block";
544     return true;
545   }
546   return checkOpenCLBlockArgs(S, BlockArg);
547 }
548 
549 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
550 /// get_kernel_work_group_size
551 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
552 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
553   if (checkArgCount(S, TheCall, 1))
554     return true;
555 
556   Expr *BlockArg = TheCall->getArg(0);
557   if (!isBlockPointer(BlockArg)) {
558     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
559         << TheCall->getDirectCallee() << "block";
560     return true;
561   }
562   return checkOpenCLBlockArgs(S, BlockArg);
563 }
564 
565 /// Diagnose integer type and any valid implicit conversion to it.
566 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
567                                       const QualType &IntType);
568 
569 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
570                                             unsigned Start, unsigned End) {
571   bool IllegalParams = false;
572   for (unsigned I = Start; I <= End; ++I)
573     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
574                                               S.Context.getSizeType());
575   return IllegalParams;
576 }
577 
578 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
579 /// 'local void*' parameter of passed block.
580 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
581                                            Expr *BlockArg,
582                                            unsigned NumNonVarArgs) {
583   const BlockPointerType *BPT =
584       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
585   unsigned NumBlockParams =
586       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
587   unsigned TotalNumArgs = TheCall->getNumArgs();
588 
589   // For each argument passed to the block, a corresponding uint needs to
590   // be passed to describe the size of the local memory.
591   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
592     S.Diag(TheCall->getBeginLoc(),
593            diag::err_opencl_enqueue_kernel_local_size_args);
594     return true;
595   }
596 
597   // Check that the sizes of the local memory are specified by integers.
598   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
599                                          TotalNumArgs - 1);
600 }
601 
602 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
603 /// overload formats specified in Table 6.13.17.1.
604 /// int enqueue_kernel(queue_t queue,
605 ///                    kernel_enqueue_flags_t flags,
606 ///                    const ndrange_t ndrange,
607 ///                    void (^block)(void))
608 /// int enqueue_kernel(queue_t queue,
609 ///                    kernel_enqueue_flags_t flags,
610 ///                    const ndrange_t ndrange,
611 ///                    uint num_events_in_wait_list,
612 ///                    clk_event_t *event_wait_list,
613 ///                    clk_event_t *event_ret,
614 ///                    void (^block)(void))
615 /// int enqueue_kernel(queue_t queue,
616 ///                    kernel_enqueue_flags_t flags,
617 ///                    const ndrange_t ndrange,
618 ///                    void (^block)(local void*, ...),
619 ///                    uint size0, ...)
620 /// int enqueue_kernel(queue_t queue,
621 ///                    kernel_enqueue_flags_t flags,
622 ///                    const ndrange_t ndrange,
623 ///                    uint num_events_in_wait_list,
624 ///                    clk_event_t *event_wait_list,
625 ///                    clk_event_t *event_ret,
626 ///                    void (^block)(local void*, ...),
627 ///                    uint size0, ...)
628 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
629   unsigned NumArgs = TheCall->getNumArgs();
630 
631   if (NumArgs < 4) {
632     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
633     return true;
634   }
635 
636   Expr *Arg0 = TheCall->getArg(0);
637   Expr *Arg1 = TheCall->getArg(1);
638   Expr *Arg2 = TheCall->getArg(2);
639   Expr *Arg3 = TheCall->getArg(3);
640 
641   // First argument always needs to be a queue_t type.
642   if (!Arg0->getType()->isQueueT()) {
643     S.Diag(TheCall->getArg(0)->getBeginLoc(),
644            diag::err_opencl_builtin_expected_type)
645         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
646     return true;
647   }
648 
649   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
650   if (!Arg1->getType()->isIntegerType()) {
651     S.Diag(TheCall->getArg(1)->getBeginLoc(),
652            diag::err_opencl_builtin_expected_type)
653         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
654     return true;
655   }
656 
657   // Third argument is always an ndrange_t type.
658   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
659     S.Diag(TheCall->getArg(2)->getBeginLoc(),
660            diag::err_opencl_builtin_expected_type)
661         << TheCall->getDirectCallee() << "'ndrange_t'";
662     return true;
663   }
664 
665   // With four arguments, there is only one form that the function could be
666   // called in: no events and no variable arguments.
667   if (NumArgs == 4) {
668     // check that the last argument is the right block type.
669     if (!isBlockPointer(Arg3)) {
670       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
671           << TheCall->getDirectCallee() << "block";
672       return true;
673     }
674     // we have a block type, check the prototype
675     const BlockPointerType *BPT =
676         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
677     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
678       S.Diag(Arg3->getBeginLoc(),
679              diag::err_opencl_enqueue_kernel_blocks_no_args);
680       return true;
681     }
682     return false;
683   }
684   // we can have block + varargs.
685   if (isBlockPointer(Arg3))
686     return (checkOpenCLBlockArgs(S, Arg3) ||
687             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
688   // last two cases with either exactly 7 args or 7 args and varargs.
689   if (NumArgs >= 7) {
690     // check common block argument.
691     Expr *Arg6 = TheCall->getArg(6);
692     if (!isBlockPointer(Arg6)) {
693       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
694           << TheCall->getDirectCallee() << "block";
695       return true;
696     }
697     if (checkOpenCLBlockArgs(S, Arg6))
698       return true;
699 
700     // Forth argument has to be any integer type.
701     if (!Arg3->getType()->isIntegerType()) {
702       S.Diag(TheCall->getArg(3)->getBeginLoc(),
703              diag::err_opencl_builtin_expected_type)
704           << TheCall->getDirectCallee() << "integer";
705       return true;
706     }
707     // check remaining common arguments.
708     Expr *Arg4 = TheCall->getArg(4);
709     Expr *Arg5 = TheCall->getArg(5);
710 
711     // Fifth argument is always passed as a pointer to clk_event_t.
712     if (!Arg4->isNullPointerConstant(S.Context,
713                                      Expr::NPC_ValueDependentIsNotNull) &&
714         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
715       S.Diag(TheCall->getArg(4)->getBeginLoc(),
716              diag::err_opencl_builtin_expected_type)
717           << TheCall->getDirectCallee()
718           << S.Context.getPointerType(S.Context.OCLClkEventTy);
719       return true;
720     }
721 
722     // Sixth argument is always passed as a pointer to clk_event_t.
723     if (!Arg5->isNullPointerConstant(S.Context,
724                                      Expr::NPC_ValueDependentIsNotNull) &&
725         !(Arg5->getType()->isPointerType() &&
726           Arg5->getType()->getPointeeType()->isClkEventT())) {
727       S.Diag(TheCall->getArg(5)->getBeginLoc(),
728              diag::err_opencl_builtin_expected_type)
729           << TheCall->getDirectCallee()
730           << S.Context.getPointerType(S.Context.OCLClkEventTy);
731       return true;
732     }
733 
734     if (NumArgs == 7)
735       return false;
736 
737     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
738   }
739 
740   // None of the specific case has been detected, give generic error
741   S.Diag(TheCall->getBeginLoc(),
742          diag::err_opencl_enqueue_kernel_incorrect_args);
743   return true;
744 }
745 
746 /// Returns OpenCL access qual.
747 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
748     return D->getAttr<OpenCLAccessAttr>();
749 }
750 
751 /// Returns true if pipe element type is different from the pointer.
752 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
753   const Expr *Arg0 = Call->getArg(0);
754   // First argument type should always be pipe.
755   if (!Arg0->getType()->isPipeType()) {
756     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
757         << Call->getDirectCallee() << Arg0->getSourceRange();
758     return true;
759   }
760   OpenCLAccessAttr *AccessQual =
761       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
762   // Validates the access qualifier is compatible with the call.
763   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
764   // read_only and write_only, and assumed to be read_only if no qualifier is
765   // specified.
766   switch (Call->getDirectCallee()->getBuiltinID()) {
767   case Builtin::BIread_pipe:
768   case Builtin::BIreserve_read_pipe:
769   case Builtin::BIcommit_read_pipe:
770   case Builtin::BIwork_group_reserve_read_pipe:
771   case Builtin::BIsub_group_reserve_read_pipe:
772   case Builtin::BIwork_group_commit_read_pipe:
773   case Builtin::BIsub_group_commit_read_pipe:
774     if (!(!AccessQual || AccessQual->isReadOnly())) {
775       S.Diag(Arg0->getBeginLoc(),
776              diag::err_opencl_builtin_pipe_invalid_access_modifier)
777           << "read_only" << Arg0->getSourceRange();
778       return true;
779     }
780     break;
781   case Builtin::BIwrite_pipe:
782   case Builtin::BIreserve_write_pipe:
783   case Builtin::BIcommit_write_pipe:
784   case Builtin::BIwork_group_reserve_write_pipe:
785   case Builtin::BIsub_group_reserve_write_pipe:
786   case Builtin::BIwork_group_commit_write_pipe:
787   case Builtin::BIsub_group_commit_write_pipe:
788     if (!(AccessQual && AccessQual->isWriteOnly())) {
789       S.Diag(Arg0->getBeginLoc(),
790              diag::err_opencl_builtin_pipe_invalid_access_modifier)
791           << "write_only" << Arg0->getSourceRange();
792       return true;
793     }
794     break;
795   default:
796     break;
797   }
798   return false;
799 }
800 
801 /// Returns true if pipe element type is different from the pointer.
802 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
803   const Expr *Arg0 = Call->getArg(0);
804   const Expr *ArgIdx = Call->getArg(Idx);
805   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
806   const QualType EltTy = PipeTy->getElementType();
807   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
808   // The Idx argument should be a pointer and the type of the pointer and
809   // the type of pipe element should also be the same.
810   if (!ArgTy ||
811       !S.Context.hasSameType(
812           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
813     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
814         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
815         << ArgIdx->getType() << ArgIdx->getSourceRange();
816     return true;
817   }
818   return false;
819 }
820 
821 // Performs semantic analysis for the read/write_pipe call.
822 // \param S Reference to the semantic analyzer.
823 // \param Call A pointer to the builtin call.
824 // \return True if a semantic error has been found, false otherwise.
825 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
826   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
827   // functions have two forms.
828   switch (Call->getNumArgs()) {
829   case 2:
830     if (checkOpenCLPipeArg(S, Call))
831       return true;
832     // The call with 2 arguments should be
833     // read/write_pipe(pipe T, T*).
834     // Check packet type T.
835     if (checkOpenCLPipePacketType(S, Call, 1))
836       return true;
837     break;
838 
839   case 4: {
840     if (checkOpenCLPipeArg(S, Call))
841       return true;
842     // The call with 4 arguments should be
843     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
844     // Check reserve_id_t.
845     if (!Call->getArg(1)->getType()->isReserveIDT()) {
846       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
847           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
848           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
849       return true;
850     }
851 
852     // Check the index.
853     const Expr *Arg2 = Call->getArg(2);
854     if (!Arg2->getType()->isIntegerType() &&
855         !Arg2->getType()->isUnsignedIntegerType()) {
856       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
857           << Call->getDirectCallee() << S.Context.UnsignedIntTy
858           << Arg2->getType() << Arg2->getSourceRange();
859       return true;
860     }
861 
862     // Check packet type T.
863     if (checkOpenCLPipePacketType(S, Call, 3))
864       return true;
865   } break;
866   default:
867     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
868         << Call->getDirectCallee() << Call->getSourceRange();
869     return true;
870   }
871 
872   return false;
873 }
874 
875 // Performs a semantic analysis on the {work_group_/sub_group_
876 //        /_}reserve_{read/write}_pipe
877 // \param S Reference to the semantic analyzer.
878 // \param Call The call to the builtin function to be analyzed.
879 // \return True if a semantic error was found, false otherwise.
880 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
881   if (checkArgCount(S, Call, 2))
882     return true;
883 
884   if (checkOpenCLPipeArg(S, Call))
885     return true;
886 
887   // Check the reserve size.
888   if (!Call->getArg(1)->getType()->isIntegerType() &&
889       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
890     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
891         << Call->getDirectCallee() << S.Context.UnsignedIntTy
892         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
893     return true;
894   }
895 
896   // Since return type of reserve_read/write_pipe built-in function is
897   // reserve_id_t, which is not defined in the builtin def file , we used int
898   // as return type and need to override the return type of these functions.
899   Call->setType(S.Context.OCLReserveIDTy);
900 
901   return false;
902 }
903 
904 // Performs a semantic analysis on {work_group_/sub_group_
905 //        /_}commit_{read/write}_pipe
906 // \param S Reference to the semantic analyzer.
907 // \param Call The call to the builtin function to be analyzed.
908 // \return True if a semantic error was found, false otherwise.
909 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
910   if (checkArgCount(S, Call, 2))
911     return true;
912 
913   if (checkOpenCLPipeArg(S, Call))
914     return true;
915 
916   // Check reserve_id_t.
917   if (!Call->getArg(1)->getType()->isReserveIDT()) {
918     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
919         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
920         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
921     return true;
922   }
923 
924   return false;
925 }
926 
927 // Performs a semantic analysis on the call to built-in Pipe
928 //        Query Functions.
929 // \param S Reference to the semantic analyzer.
930 // \param Call The call to the builtin function to be analyzed.
931 // \return True if a semantic error was found, false otherwise.
932 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
933   if (checkArgCount(S, Call, 1))
934     return true;
935 
936   if (!Call->getArg(0)->getType()->isPipeType()) {
937     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
938         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
939     return true;
940   }
941 
942   return false;
943 }
944 
945 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
946 // Performs semantic analysis for the to_global/local/private call.
947 // \param S Reference to the semantic analyzer.
948 // \param BuiltinID ID of the builtin function.
949 // \param Call A pointer to the builtin call.
950 // \return True if a semantic error has been found, false otherwise.
951 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
952                                     CallExpr *Call) {
953   if (Call->getNumArgs() != 1) {
954     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
955         << Call->getDirectCallee() << Call->getSourceRange();
956     return true;
957   }
958 
959   auto RT = Call->getArg(0)->getType();
960   if (!RT->isPointerType() || RT->getPointeeType()
961       .getAddressSpace() == LangAS::opencl_constant) {
962     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
963         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
964     return true;
965   }
966 
967   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
968     S.Diag(Call->getArg(0)->getBeginLoc(),
969            diag::warn_opencl_generic_address_space_arg)
970         << Call->getDirectCallee()->getNameInfo().getAsString()
971         << Call->getArg(0)->getSourceRange();
972   }
973 
974   RT = RT->getPointeeType();
975   auto Qual = RT.getQualifiers();
976   switch (BuiltinID) {
977   case Builtin::BIto_global:
978     Qual.setAddressSpace(LangAS::opencl_global);
979     break;
980   case Builtin::BIto_local:
981     Qual.setAddressSpace(LangAS::opencl_local);
982     break;
983   case Builtin::BIto_private:
984     Qual.setAddressSpace(LangAS::opencl_private);
985     break;
986   default:
987     llvm_unreachable("Invalid builtin function");
988   }
989   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
990       RT.getUnqualifiedType(), Qual)));
991 
992   return false;
993 }
994 
995 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
996   if (checkArgCount(S, TheCall, 1))
997     return ExprError();
998 
999   // Compute __builtin_launder's parameter type from the argument.
1000   // The parameter type is:
1001   //  * The type of the argument if it's not an array or function type,
1002   //  Otherwise,
1003   //  * The decayed argument type.
1004   QualType ParamTy = [&]() {
1005     QualType ArgTy = TheCall->getArg(0)->getType();
1006     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1007       return S.Context.getPointerType(Ty->getElementType());
1008     if (ArgTy->isFunctionType()) {
1009       return S.Context.getPointerType(ArgTy);
1010     }
1011     return ArgTy;
1012   }();
1013 
1014   TheCall->setType(ParamTy);
1015 
1016   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1017     if (!ParamTy->isPointerType())
1018       return 0;
1019     if (ParamTy->isFunctionPointerType())
1020       return 1;
1021     if (ParamTy->isVoidPointerType())
1022       return 2;
1023     return llvm::Optional<unsigned>{};
1024   }();
1025   if (DiagSelect.hasValue()) {
1026     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1027         << DiagSelect.getValue() << TheCall->getSourceRange();
1028     return ExprError();
1029   }
1030 
1031   // We either have an incomplete class type, or we have a class template
1032   // whose instantiation has not been forced. Example:
1033   //
1034   //   template <class T> struct Foo { T value; };
1035   //   Foo<int> *p = nullptr;
1036   //   auto *d = __builtin_launder(p);
1037   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1038                             diag::err_incomplete_type))
1039     return ExprError();
1040 
1041   assert(ParamTy->getPointeeType()->isObjectType() &&
1042          "Unhandled non-object pointer case");
1043 
1044   InitializedEntity Entity =
1045       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1046   ExprResult Arg =
1047       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1048   if (Arg.isInvalid())
1049     return ExprError();
1050   TheCall->setArg(0, Arg.get());
1051 
1052   return TheCall;
1053 }
1054 
1055 // Emit an error and return true if the current architecture is not in the list
1056 // of supported architectures.
1057 static bool
1058 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1059                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1060   llvm::Triple::ArchType CurArch =
1061       S.getASTContext().getTargetInfo().getTriple().getArch();
1062   if (llvm::is_contained(SupportedArchs, CurArch))
1063     return false;
1064   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1065       << TheCall->getSourceRange();
1066   return true;
1067 }
1068 
1069 ExprResult
1070 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1071                                CallExpr *TheCall) {
1072   ExprResult TheCallResult(TheCall);
1073 
1074   // Find out if any arguments are required to be integer constant expressions.
1075   unsigned ICEArguments = 0;
1076   ASTContext::GetBuiltinTypeError Error;
1077   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1078   if (Error != ASTContext::GE_None)
1079     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1080 
1081   // If any arguments are required to be ICE's, check and diagnose.
1082   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1083     // Skip arguments not required to be ICE's.
1084     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1085 
1086     llvm::APSInt Result;
1087     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1088       return true;
1089     ICEArguments &= ~(1 << ArgNo);
1090   }
1091 
1092   switch (BuiltinID) {
1093   case Builtin::BI__builtin___CFStringMakeConstantString:
1094     assert(TheCall->getNumArgs() == 1 &&
1095            "Wrong # arguments to builtin CFStringMakeConstantString");
1096     if (CheckObjCString(TheCall->getArg(0)))
1097       return ExprError();
1098     break;
1099   case Builtin::BI__builtin_ms_va_start:
1100   case Builtin::BI__builtin_stdarg_start:
1101   case Builtin::BI__builtin_va_start:
1102     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1103       return ExprError();
1104     break;
1105   case Builtin::BI__va_start: {
1106     switch (Context.getTargetInfo().getTriple().getArch()) {
1107     case llvm::Triple::aarch64:
1108     case llvm::Triple::arm:
1109     case llvm::Triple::thumb:
1110       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1111         return ExprError();
1112       break;
1113     default:
1114       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1115         return ExprError();
1116       break;
1117     }
1118     break;
1119   }
1120 
1121   // The acquire, release, and no fence variants are ARM and AArch64 only.
1122   case Builtin::BI_interlockedbittestandset_acq:
1123   case Builtin::BI_interlockedbittestandset_rel:
1124   case Builtin::BI_interlockedbittestandset_nf:
1125   case Builtin::BI_interlockedbittestandreset_acq:
1126   case Builtin::BI_interlockedbittestandreset_rel:
1127   case Builtin::BI_interlockedbittestandreset_nf:
1128     if (CheckBuiltinTargetSupport(
1129             *this, BuiltinID, TheCall,
1130             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1131       return ExprError();
1132     break;
1133 
1134   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1135   case Builtin::BI_bittest64:
1136   case Builtin::BI_bittestandcomplement64:
1137   case Builtin::BI_bittestandreset64:
1138   case Builtin::BI_bittestandset64:
1139   case Builtin::BI_interlockedbittestandreset64:
1140   case Builtin::BI_interlockedbittestandset64:
1141     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1142                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1143                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1144       return ExprError();
1145     break;
1146 
1147   case Builtin::BI__builtin_isgreater:
1148   case Builtin::BI__builtin_isgreaterequal:
1149   case Builtin::BI__builtin_isless:
1150   case Builtin::BI__builtin_islessequal:
1151   case Builtin::BI__builtin_islessgreater:
1152   case Builtin::BI__builtin_isunordered:
1153     if (SemaBuiltinUnorderedCompare(TheCall))
1154       return ExprError();
1155     break;
1156   case Builtin::BI__builtin_fpclassify:
1157     if (SemaBuiltinFPClassification(TheCall, 6))
1158       return ExprError();
1159     break;
1160   case Builtin::BI__builtin_isfinite:
1161   case Builtin::BI__builtin_isinf:
1162   case Builtin::BI__builtin_isinf_sign:
1163   case Builtin::BI__builtin_isnan:
1164   case Builtin::BI__builtin_isnormal:
1165   case Builtin::BI__builtin_signbit:
1166   case Builtin::BI__builtin_signbitf:
1167   case Builtin::BI__builtin_signbitl:
1168     if (SemaBuiltinFPClassification(TheCall, 1))
1169       return ExprError();
1170     break;
1171   case Builtin::BI__builtin_shufflevector:
1172     return SemaBuiltinShuffleVector(TheCall);
1173     // TheCall will be freed by the smart pointer here, but that's fine, since
1174     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1175   case Builtin::BI__builtin_prefetch:
1176     if (SemaBuiltinPrefetch(TheCall))
1177       return ExprError();
1178     break;
1179   case Builtin::BI__builtin_alloca_with_align:
1180     if (SemaBuiltinAllocaWithAlign(TheCall))
1181       return ExprError();
1182     LLVM_FALLTHROUGH;
1183   case Builtin::BI__builtin_alloca:
1184     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1185         << TheCall->getDirectCallee();
1186     break;
1187   case Builtin::BI__assume:
1188   case Builtin::BI__builtin_assume:
1189     if (SemaBuiltinAssume(TheCall))
1190       return ExprError();
1191     break;
1192   case Builtin::BI__builtin_assume_aligned:
1193     if (SemaBuiltinAssumeAligned(TheCall))
1194       return ExprError();
1195     break;
1196   case Builtin::BI__builtin_dynamic_object_size:
1197   case Builtin::BI__builtin_object_size:
1198     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1199       return ExprError();
1200     break;
1201   case Builtin::BI__builtin_longjmp:
1202     if (SemaBuiltinLongjmp(TheCall))
1203       return ExprError();
1204     break;
1205   case Builtin::BI__builtin_setjmp:
1206     if (SemaBuiltinSetjmp(TheCall))
1207       return ExprError();
1208     break;
1209   case Builtin::BI_setjmp:
1210   case Builtin::BI_setjmpex:
1211     if (checkArgCount(*this, TheCall, 1))
1212       return true;
1213     break;
1214   case Builtin::BI__builtin_classify_type:
1215     if (checkArgCount(*this, TheCall, 1)) return true;
1216     TheCall->setType(Context.IntTy);
1217     break;
1218   case Builtin::BI__builtin_constant_p: {
1219     if (checkArgCount(*this, TheCall, 1)) return true;
1220     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1221     if (Arg.isInvalid()) return true;
1222     TheCall->setArg(0, Arg.get());
1223     TheCall->setType(Context.IntTy);
1224     break;
1225   }
1226   case Builtin::BI__builtin_launder:
1227     return SemaBuiltinLaunder(*this, TheCall);
1228   case Builtin::BI__sync_fetch_and_add:
1229   case Builtin::BI__sync_fetch_and_add_1:
1230   case Builtin::BI__sync_fetch_and_add_2:
1231   case Builtin::BI__sync_fetch_and_add_4:
1232   case Builtin::BI__sync_fetch_and_add_8:
1233   case Builtin::BI__sync_fetch_and_add_16:
1234   case Builtin::BI__sync_fetch_and_sub:
1235   case Builtin::BI__sync_fetch_and_sub_1:
1236   case Builtin::BI__sync_fetch_and_sub_2:
1237   case Builtin::BI__sync_fetch_and_sub_4:
1238   case Builtin::BI__sync_fetch_and_sub_8:
1239   case Builtin::BI__sync_fetch_and_sub_16:
1240   case Builtin::BI__sync_fetch_and_or:
1241   case Builtin::BI__sync_fetch_and_or_1:
1242   case Builtin::BI__sync_fetch_and_or_2:
1243   case Builtin::BI__sync_fetch_and_or_4:
1244   case Builtin::BI__sync_fetch_and_or_8:
1245   case Builtin::BI__sync_fetch_and_or_16:
1246   case Builtin::BI__sync_fetch_and_and:
1247   case Builtin::BI__sync_fetch_and_and_1:
1248   case Builtin::BI__sync_fetch_and_and_2:
1249   case Builtin::BI__sync_fetch_and_and_4:
1250   case Builtin::BI__sync_fetch_and_and_8:
1251   case Builtin::BI__sync_fetch_and_and_16:
1252   case Builtin::BI__sync_fetch_and_xor:
1253   case Builtin::BI__sync_fetch_and_xor_1:
1254   case Builtin::BI__sync_fetch_and_xor_2:
1255   case Builtin::BI__sync_fetch_and_xor_4:
1256   case Builtin::BI__sync_fetch_and_xor_8:
1257   case Builtin::BI__sync_fetch_and_xor_16:
1258   case Builtin::BI__sync_fetch_and_nand:
1259   case Builtin::BI__sync_fetch_and_nand_1:
1260   case Builtin::BI__sync_fetch_and_nand_2:
1261   case Builtin::BI__sync_fetch_and_nand_4:
1262   case Builtin::BI__sync_fetch_and_nand_8:
1263   case Builtin::BI__sync_fetch_and_nand_16:
1264   case Builtin::BI__sync_add_and_fetch:
1265   case Builtin::BI__sync_add_and_fetch_1:
1266   case Builtin::BI__sync_add_and_fetch_2:
1267   case Builtin::BI__sync_add_and_fetch_4:
1268   case Builtin::BI__sync_add_and_fetch_8:
1269   case Builtin::BI__sync_add_and_fetch_16:
1270   case Builtin::BI__sync_sub_and_fetch:
1271   case Builtin::BI__sync_sub_and_fetch_1:
1272   case Builtin::BI__sync_sub_and_fetch_2:
1273   case Builtin::BI__sync_sub_and_fetch_4:
1274   case Builtin::BI__sync_sub_and_fetch_8:
1275   case Builtin::BI__sync_sub_and_fetch_16:
1276   case Builtin::BI__sync_and_and_fetch:
1277   case Builtin::BI__sync_and_and_fetch_1:
1278   case Builtin::BI__sync_and_and_fetch_2:
1279   case Builtin::BI__sync_and_and_fetch_4:
1280   case Builtin::BI__sync_and_and_fetch_8:
1281   case Builtin::BI__sync_and_and_fetch_16:
1282   case Builtin::BI__sync_or_and_fetch:
1283   case Builtin::BI__sync_or_and_fetch_1:
1284   case Builtin::BI__sync_or_and_fetch_2:
1285   case Builtin::BI__sync_or_and_fetch_4:
1286   case Builtin::BI__sync_or_and_fetch_8:
1287   case Builtin::BI__sync_or_and_fetch_16:
1288   case Builtin::BI__sync_xor_and_fetch:
1289   case Builtin::BI__sync_xor_and_fetch_1:
1290   case Builtin::BI__sync_xor_and_fetch_2:
1291   case Builtin::BI__sync_xor_and_fetch_4:
1292   case Builtin::BI__sync_xor_and_fetch_8:
1293   case Builtin::BI__sync_xor_and_fetch_16:
1294   case Builtin::BI__sync_nand_and_fetch:
1295   case Builtin::BI__sync_nand_and_fetch_1:
1296   case Builtin::BI__sync_nand_and_fetch_2:
1297   case Builtin::BI__sync_nand_and_fetch_4:
1298   case Builtin::BI__sync_nand_and_fetch_8:
1299   case Builtin::BI__sync_nand_and_fetch_16:
1300   case Builtin::BI__sync_val_compare_and_swap:
1301   case Builtin::BI__sync_val_compare_and_swap_1:
1302   case Builtin::BI__sync_val_compare_and_swap_2:
1303   case Builtin::BI__sync_val_compare_and_swap_4:
1304   case Builtin::BI__sync_val_compare_and_swap_8:
1305   case Builtin::BI__sync_val_compare_and_swap_16:
1306   case Builtin::BI__sync_bool_compare_and_swap:
1307   case Builtin::BI__sync_bool_compare_and_swap_1:
1308   case Builtin::BI__sync_bool_compare_and_swap_2:
1309   case Builtin::BI__sync_bool_compare_and_swap_4:
1310   case Builtin::BI__sync_bool_compare_and_swap_8:
1311   case Builtin::BI__sync_bool_compare_and_swap_16:
1312   case Builtin::BI__sync_lock_test_and_set:
1313   case Builtin::BI__sync_lock_test_and_set_1:
1314   case Builtin::BI__sync_lock_test_and_set_2:
1315   case Builtin::BI__sync_lock_test_and_set_4:
1316   case Builtin::BI__sync_lock_test_and_set_8:
1317   case Builtin::BI__sync_lock_test_and_set_16:
1318   case Builtin::BI__sync_lock_release:
1319   case Builtin::BI__sync_lock_release_1:
1320   case Builtin::BI__sync_lock_release_2:
1321   case Builtin::BI__sync_lock_release_4:
1322   case Builtin::BI__sync_lock_release_8:
1323   case Builtin::BI__sync_lock_release_16:
1324   case Builtin::BI__sync_swap:
1325   case Builtin::BI__sync_swap_1:
1326   case Builtin::BI__sync_swap_2:
1327   case Builtin::BI__sync_swap_4:
1328   case Builtin::BI__sync_swap_8:
1329   case Builtin::BI__sync_swap_16:
1330     return SemaBuiltinAtomicOverloaded(TheCallResult);
1331   case Builtin::BI__sync_synchronize:
1332     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1333         << TheCall->getCallee()->getSourceRange();
1334     break;
1335   case Builtin::BI__builtin_nontemporal_load:
1336   case Builtin::BI__builtin_nontemporal_store:
1337     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1338 #define BUILTIN(ID, TYPE, ATTRS)
1339 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1340   case Builtin::BI##ID: \
1341     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1342 #include "clang/Basic/Builtins.def"
1343   case Builtin::BI__annotation:
1344     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1345       return ExprError();
1346     break;
1347   case Builtin::BI__builtin_annotation:
1348     if (SemaBuiltinAnnotation(*this, TheCall))
1349       return ExprError();
1350     break;
1351   case Builtin::BI__builtin_addressof:
1352     if (SemaBuiltinAddressof(*this, TheCall))
1353       return ExprError();
1354     break;
1355   case Builtin::BI__builtin_add_overflow:
1356   case Builtin::BI__builtin_sub_overflow:
1357   case Builtin::BI__builtin_mul_overflow:
1358     if (SemaBuiltinOverflow(*this, TheCall))
1359       return ExprError();
1360     break;
1361   case Builtin::BI__builtin_operator_new:
1362   case Builtin::BI__builtin_operator_delete: {
1363     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1364     ExprResult Res =
1365         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1366     if (Res.isInvalid())
1367       CorrectDelayedTyposInExpr(TheCallResult.get());
1368     return Res;
1369   }
1370   case Builtin::BI__builtin_dump_struct: {
1371     // We first want to ensure we are called with 2 arguments
1372     if (checkArgCount(*this, TheCall, 2))
1373       return ExprError();
1374     // Ensure that the first argument is of type 'struct XX *'
1375     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1376     const QualType PtrArgType = PtrArg->getType();
1377     if (!PtrArgType->isPointerType() ||
1378         !PtrArgType->getPointeeType()->isRecordType()) {
1379       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1380           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1381           << "structure pointer";
1382       return ExprError();
1383     }
1384 
1385     // Ensure that the second argument is of type 'FunctionType'
1386     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1387     const QualType FnPtrArgType = FnPtrArg->getType();
1388     if (!FnPtrArgType->isPointerType()) {
1389       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1390           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1391           << FnPtrArgType << "'int (*)(const char *, ...)'";
1392       return ExprError();
1393     }
1394 
1395     const auto *FuncType =
1396         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1397 
1398     if (!FuncType) {
1399       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1400           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1401           << FnPtrArgType << "'int (*)(const char *, ...)'";
1402       return ExprError();
1403     }
1404 
1405     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1406       if (!FT->getNumParams()) {
1407         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1408             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1409             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1410         return ExprError();
1411       }
1412       QualType PT = FT->getParamType(0);
1413       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1414           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1415           !PT->getPointeeType().isConstQualified()) {
1416         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1417             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1418             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1419         return ExprError();
1420       }
1421     }
1422 
1423     TheCall->setType(Context.IntTy);
1424     break;
1425   }
1426   case Builtin::BI__builtin_preserve_access_index:
1427     if (SemaBuiltinPreserveAI(*this, TheCall))
1428       return ExprError();
1429     break;
1430   case Builtin::BI__builtin_call_with_static_chain:
1431     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1432       return ExprError();
1433     break;
1434   case Builtin::BI__exception_code:
1435   case Builtin::BI_exception_code:
1436     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1437                                  diag::err_seh___except_block))
1438       return ExprError();
1439     break;
1440   case Builtin::BI__exception_info:
1441   case Builtin::BI_exception_info:
1442     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1443                                  diag::err_seh___except_filter))
1444       return ExprError();
1445     break;
1446   case Builtin::BI__GetExceptionInfo:
1447     if (checkArgCount(*this, TheCall, 1))
1448       return ExprError();
1449 
1450     if (CheckCXXThrowOperand(
1451             TheCall->getBeginLoc(),
1452             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1453             TheCall))
1454       return ExprError();
1455 
1456     TheCall->setType(Context.VoidPtrTy);
1457     break;
1458   // OpenCL v2.0, s6.13.16 - Pipe functions
1459   case Builtin::BIread_pipe:
1460   case Builtin::BIwrite_pipe:
1461     // Since those two functions are declared with var args, we need a semantic
1462     // check for the argument.
1463     if (SemaBuiltinRWPipe(*this, TheCall))
1464       return ExprError();
1465     break;
1466   case Builtin::BIreserve_read_pipe:
1467   case Builtin::BIreserve_write_pipe:
1468   case Builtin::BIwork_group_reserve_read_pipe:
1469   case Builtin::BIwork_group_reserve_write_pipe:
1470     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1471       return ExprError();
1472     break;
1473   case Builtin::BIsub_group_reserve_read_pipe:
1474   case Builtin::BIsub_group_reserve_write_pipe:
1475     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1476         SemaBuiltinReserveRWPipe(*this, TheCall))
1477       return ExprError();
1478     break;
1479   case Builtin::BIcommit_read_pipe:
1480   case Builtin::BIcommit_write_pipe:
1481   case Builtin::BIwork_group_commit_read_pipe:
1482   case Builtin::BIwork_group_commit_write_pipe:
1483     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1484       return ExprError();
1485     break;
1486   case Builtin::BIsub_group_commit_read_pipe:
1487   case Builtin::BIsub_group_commit_write_pipe:
1488     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1489         SemaBuiltinCommitRWPipe(*this, TheCall))
1490       return ExprError();
1491     break;
1492   case Builtin::BIget_pipe_num_packets:
1493   case Builtin::BIget_pipe_max_packets:
1494     if (SemaBuiltinPipePackets(*this, TheCall))
1495       return ExprError();
1496     break;
1497   case Builtin::BIto_global:
1498   case Builtin::BIto_local:
1499   case Builtin::BIto_private:
1500     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1501       return ExprError();
1502     break;
1503   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1504   case Builtin::BIenqueue_kernel:
1505     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1506       return ExprError();
1507     break;
1508   case Builtin::BIget_kernel_work_group_size:
1509   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1510     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1511       return ExprError();
1512     break;
1513   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1514   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1515     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1516       return ExprError();
1517     break;
1518   case Builtin::BI__builtin_os_log_format:
1519   case Builtin::BI__builtin_os_log_format_buffer_size:
1520     if (SemaBuiltinOSLogFormat(TheCall))
1521       return ExprError();
1522     break;
1523   }
1524 
1525   // Since the target specific builtins for each arch overlap, only check those
1526   // of the arch we are compiling for.
1527   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1528     switch (Context.getTargetInfo().getTriple().getArch()) {
1529       case llvm::Triple::arm:
1530       case llvm::Triple::armeb:
1531       case llvm::Triple::thumb:
1532       case llvm::Triple::thumbeb:
1533         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1534           return ExprError();
1535         break;
1536       case llvm::Triple::aarch64:
1537       case llvm::Triple::aarch64_be:
1538         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1539           return ExprError();
1540         break;
1541       case llvm::Triple::hexagon:
1542         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1543           return ExprError();
1544         break;
1545       case llvm::Triple::mips:
1546       case llvm::Triple::mipsel:
1547       case llvm::Triple::mips64:
1548       case llvm::Triple::mips64el:
1549         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1550           return ExprError();
1551         break;
1552       case llvm::Triple::systemz:
1553         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1554           return ExprError();
1555         break;
1556       case llvm::Triple::x86:
1557       case llvm::Triple::x86_64:
1558         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1559           return ExprError();
1560         break;
1561       case llvm::Triple::ppc:
1562       case llvm::Triple::ppc64:
1563       case llvm::Triple::ppc64le:
1564         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1565           return ExprError();
1566         break;
1567       default:
1568         break;
1569     }
1570   }
1571 
1572   return TheCallResult;
1573 }
1574 
1575 // Get the valid immediate range for the specified NEON type code.
1576 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1577   NeonTypeFlags Type(t);
1578   int IsQuad = ForceQuad ? true : Type.isQuad();
1579   switch (Type.getEltType()) {
1580   case NeonTypeFlags::Int8:
1581   case NeonTypeFlags::Poly8:
1582     return shift ? 7 : (8 << IsQuad) - 1;
1583   case NeonTypeFlags::Int16:
1584   case NeonTypeFlags::Poly16:
1585     return shift ? 15 : (4 << IsQuad) - 1;
1586   case NeonTypeFlags::Int32:
1587     return shift ? 31 : (2 << IsQuad) - 1;
1588   case NeonTypeFlags::Int64:
1589   case NeonTypeFlags::Poly64:
1590     return shift ? 63 : (1 << IsQuad) - 1;
1591   case NeonTypeFlags::Poly128:
1592     return shift ? 127 : (1 << IsQuad) - 1;
1593   case NeonTypeFlags::Float16:
1594     assert(!shift && "cannot shift float types!");
1595     return (4 << IsQuad) - 1;
1596   case NeonTypeFlags::Float32:
1597     assert(!shift && "cannot shift float types!");
1598     return (2 << IsQuad) - 1;
1599   case NeonTypeFlags::Float64:
1600     assert(!shift && "cannot shift float types!");
1601     return (1 << IsQuad) - 1;
1602   }
1603   llvm_unreachable("Invalid NeonTypeFlag!");
1604 }
1605 
1606 /// getNeonEltType - Return the QualType corresponding to the elements of
1607 /// the vector type specified by the NeonTypeFlags.  This is used to check
1608 /// the pointer arguments for Neon load/store intrinsics.
1609 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1610                                bool IsPolyUnsigned, bool IsInt64Long) {
1611   switch (Flags.getEltType()) {
1612   case NeonTypeFlags::Int8:
1613     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1614   case NeonTypeFlags::Int16:
1615     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1616   case NeonTypeFlags::Int32:
1617     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1618   case NeonTypeFlags::Int64:
1619     if (IsInt64Long)
1620       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1621     else
1622       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1623                                 : Context.LongLongTy;
1624   case NeonTypeFlags::Poly8:
1625     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1626   case NeonTypeFlags::Poly16:
1627     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1628   case NeonTypeFlags::Poly64:
1629     if (IsInt64Long)
1630       return Context.UnsignedLongTy;
1631     else
1632       return Context.UnsignedLongLongTy;
1633   case NeonTypeFlags::Poly128:
1634     break;
1635   case NeonTypeFlags::Float16:
1636     return Context.HalfTy;
1637   case NeonTypeFlags::Float32:
1638     return Context.FloatTy;
1639   case NeonTypeFlags::Float64:
1640     return Context.DoubleTy;
1641   }
1642   llvm_unreachable("Invalid NeonTypeFlag!");
1643 }
1644 
1645 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1646   llvm::APSInt Result;
1647   uint64_t mask = 0;
1648   unsigned TV = 0;
1649   int PtrArgNum = -1;
1650   bool HasConstPtr = false;
1651   switch (BuiltinID) {
1652 #define GET_NEON_OVERLOAD_CHECK
1653 #include "clang/Basic/arm_neon.inc"
1654 #include "clang/Basic/arm_fp16.inc"
1655 #undef GET_NEON_OVERLOAD_CHECK
1656   }
1657 
1658   // For NEON intrinsics which are overloaded on vector element type, validate
1659   // the immediate which specifies which variant to emit.
1660   unsigned ImmArg = TheCall->getNumArgs()-1;
1661   if (mask) {
1662     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1663       return true;
1664 
1665     TV = Result.getLimitedValue(64);
1666     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1667       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1668              << TheCall->getArg(ImmArg)->getSourceRange();
1669   }
1670 
1671   if (PtrArgNum >= 0) {
1672     // Check that pointer arguments have the specified type.
1673     Expr *Arg = TheCall->getArg(PtrArgNum);
1674     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1675       Arg = ICE->getSubExpr();
1676     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1677     QualType RHSTy = RHS.get()->getType();
1678 
1679     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1680     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1681                           Arch == llvm::Triple::aarch64_be;
1682     bool IsInt64Long =
1683         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1684     QualType EltTy =
1685         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1686     if (HasConstPtr)
1687       EltTy = EltTy.withConst();
1688     QualType LHSTy = Context.getPointerType(EltTy);
1689     AssignConvertType ConvTy;
1690     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1691     if (RHS.isInvalid())
1692       return true;
1693     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1694                                  RHS.get(), AA_Assigning))
1695       return true;
1696   }
1697 
1698   // For NEON intrinsics which take an immediate value as part of the
1699   // instruction, range check them here.
1700   unsigned i = 0, l = 0, u = 0;
1701   switch (BuiltinID) {
1702   default:
1703     return false;
1704   #define GET_NEON_IMMEDIATE_CHECK
1705   #include "clang/Basic/arm_neon.inc"
1706   #include "clang/Basic/arm_fp16.inc"
1707   #undef GET_NEON_IMMEDIATE_CHECK
1708   }
1709 
1710   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1711 }
1712 
1713 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1714                                         unsigned MaxWidth) {
1715   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1716           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1717           BuiltinID == ARM::BI__builtin_arm_strex ||
1718           BuiltinID == ARM::BI__builtin_arm_stlex ||
1719           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1720           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1721           BuiltinID == AArch64::BI__builtin_arm_strex ||
1722           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1723          "unexpected ARM builtin");
1724   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1725                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1726                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1727                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1728 
1729   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1730 
1731   // Ensure that we have the proper number of arguments.
1732   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1733     return true;
1734 
1735   // Inspect the pointer argument of the atomic builtin.  This should always be
1736   // a pointer type, whose element is an integral scalar or pointer type.
1737   // Because it is a pointer type, we don't have to worry about any implicit
1738   // casts here.
1739   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1740   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1741   if (PointerArgRes.isInvalid())
1742     return true;
1743   PointerArg = PointerArgRes.get();
1744 
1745   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1746   if (!pointerType) {
1747     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1748         << PointerArg->getType() << PointerArg->getSourceRange();
1749     return true;
1750   }
1751 
1752   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1753   // task is to insert the appropriate casts into the AST. First work out just
1754   // what the appropriate type is.
1755   QualType ValType = pointerType->getPointeeType();
1756   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1757   if (IsLdrex)
1758     AddrType.addConst();
1759 
1760   // Issue a warning if the cast is dodgy.
1761   CastKind CastNeeded = CK_NoOp;
1762   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1763     CastNeeded = CK_BitCast;
1764     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1765         << PointerArg->getType() << Context.getPointerType(AddrType)
1766         << AA_Passing << PointerArg->getSourceRange();
1767   }
1768 
1769   // Finally, do the cast and replace the argument with the corrected version.
1770   AddrType = Context.getPointerType(AddrType);
1771   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1772   if (PointerArgRes.isInvalid())
1773     return true;
1774   PointerArg = PointerArgRes.get();
1775 
1776   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1777 
1778   // In general, we allow ints, floats and pointers to be loaded and stored.
1779   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1780       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1781     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1782         << PointerArg->getType() << PointerArg->getSourceRange();
1783     return true;
1784   }
1785 
1786   // But ARM doesn't have instructions to deal with 128-bit versions.
1787   if (Context.getTypeSize(ValType) > MaxWidth) {
1788     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1789     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1790         << PointerArg->getType() << PointerArg->getSourceRange();
1791     return true;
1792   }
1793 
1794   switch (ValType.getObjCLifetime()) {
1795   case Qualifiers::OCL_None:
1796   case Qualifiers::OCL_ExplicitNone:
1797     // okay
1798     break;
1799 
1800   case Qualifiers::OCL_Weak:
1801   case Qualifiers::OCL_Strong:
1802   case Qualifiers::OCL_Autoreleasing:
1803     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1804         << ValType << PointerArg->getSourceRange();
1805     return true;
1806   }
1807 
1808   if (IsLdrex) {
1809     TheCall->setType(ValType);
1810     return false;
1811   }
1812 
1813   // Initialize the argument to be stored.
1814   ExprResult ValArg = TheCall->getArg(0);
1815   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1816       Context, ValType, /*consume*/ false);
1817   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1818   if (ValArg.isInvalid())
1819     return true;
1820   TheCall->setArg(0, ValArg.get());
1821 
1822   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1823   // but the custom checker bypasses all default analysis.
1824   TheCall->setType(Context.IntTy);
1825   return false;
1826 }
1827 
1828 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1829   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1830       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1831       BuiltinID == ARM::BI__builtin_arm_strex ||
1832       BuiltinID == ARM::BI__builtin_arm_stlex) {
1833     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1834   }
1835 
1836   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1837     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1838       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1839   }
1840 
1841   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1842       BuiltinID == ARM::BI__builtin_arm_wsr64)
1843     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1844 
1845   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1846       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1847       BuiltinID == ARM::BI__builtin_arm_wsr ||
1848       BuiltinID == ARM::BI__builtin_arm_wsrp)
1849     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1850 
1851   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1852     return true;
1853 
1854   // For intrinsics which take an immediate value as part of the instruction,
1855   // range check them here.
1856   // FIXME: VFP Intrinsics should error if VFP not present.
1857   switch (BuiltinID) {
1858   default: return false;
1859   case ARM::BI__builtin_arm_ssat:
1860     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1861   case ARM::BI__builtin_arm_usat:
1862     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1863   case ARM::BI__builtin_arm_ssat16:
1864     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1865   case ARM::BI__builtin_arm_usat16:
1866     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1867   case ARM::BI__builtin_arm_vcvtr_f:
1868   case ARM::BI__builtin_arm_vcvtr_d:
1869     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1870   case ARM::BI__builtin_arm_dmb:
1871   case ARM::BI__builtin_arm_dsb:
1872   case ARM::BI__builtin_arm_isb:
1873   case ARM::BI__builtin_arm_dbg:
1874     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1875   }
1876 }
1877 
1878 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1879                                          CallExpr *TheCall) {
1880   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1881       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1882       BuiltinID == AArch64::BI__builtin_arm_strex ||
1883       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1884     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1885   }
1886 
1887   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1888     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1889       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1890       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1891       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1892   }
1893 
1894   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1895       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1896     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1897 
1898   // Memory Tagging Extensions (MTE) Intrinsics
1899   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1900       BuiltinID == AArch64::BI__builtin_arm_addg ||
1901       BuiltinID == AArch64::BI__builtin_arm_gmi ||
1902       BuiltinID == AArch64::BI__builtin_arm_ldg ||
1903       BuiltinID == AArch64::BI__builtin_arm_stg ||
1904       BuiltinID == AArch64::BI__builtin_arm_subp) {
1905     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1906   }
1907 
1908   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1909       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1910       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1911       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1912     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1913 
1914   // Only check the valid encoding range. Any constant in this range would be
1915   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1916   // an exception for incorrect registers. This matches MSVC behavior.
1917   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1918       BuiltinID == AArch64::BI_WriteStatusReg)
1919     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1920 
1921   if (BuiltinID == AArch64::BI__getReg)
1922     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1923 
1924   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1925     return true;
1926 
1927   // For intrinsics which take an immediate value as part of the instruction,
1928   // range check them here.
1929   unsigned i = 0, l = 0, u = 0;
1930   switch (BuiltinID) {
1931   default: return false;
1932   case AArch64::BI__builtin_arm_dmb:
1933   case AArch64::BI__builtin_arm_dsb:
1934   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1935   }
1936 
1937   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1938 }
1939 
1940 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1941   struct BuiltinAndString {
1942     unsigned BuiltinID;
1943     const char *Str;
1944   };
1945 
1946   static BuiltinAndString ValidCPU[] = {
1947     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1948     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1949     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1950     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1951     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1952     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1953     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1954     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1955     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1958     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1970   };
1971 
1972   static BuiltinAndString ValidHVX[] = {
1973     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2671     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2672     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2673     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2674     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2675     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2676     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2677     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2678     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2679     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2680     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2681     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2682     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2683     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2684     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2685     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2686     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2687     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2688     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2689     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2690     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2691     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2692     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2693     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2694     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2695     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2696     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2697     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2705   };
2706 
2707   // Sort the tables on first execution so we can binary search them.
2708   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2709     return LHS.BuiltinID < RHS.BuiltinID;
2710   };
2711   static const bool SortOnce =
2712       (llvm::sort(ValidCPU, SortCmp),
2713        llvm::sort(ValidHVX, SortCmp), true);
2714   (void)SortOnce;
2715   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2716     return BI.BuiltinID < BuiltinID;
2717   };
2718 
2719   const TargetInfo &TI = Context.getTargetInfo();
2720 
2721   const BuiltinAndString *FC =
2722       llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2723   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2724     const TargetOptions &Opts = TI.getTargetOpts();
2725     StringRef CPU = Opts.CPU;
2726     if (!CPU.empty()) {
2727       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2728       CPU.consume_front("hexagon");
2729       SmallVector<StringRef, 3> CPUs;
2730       StringRef(FC->Str).split(CPUs, ',');
2731       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2732         return Diag(TheCall->getBeginLoc(),
2733                     diag::err_hexagon_builtin_unsupported_cpu);
2734     }
2735   }
2736 
2737   const BuiltinAndString *FH =
2738       llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2739   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2740     if (!TI.hasFeature("hvx"))
2741       return Diag(TheCall->getBeginLoc(),
2742                   diag::err_hexagon_builtin_requires_hvx);
2743 
2744     SmallVector<StringRef, 3> HVXs;
2745     StringRef(FH->Str).split(HVXs, ',');
2746     bool IsValid = llvm::any_of(HVXs,
2747                                 [&TI] (StringRef V) {
2748                                   std::string F = "hvx" + V.str();
2749                                   return TI.hasFeature(F);
2750                                 });
2751     if (!IsValid)
2752       return Diag(TheCall->getBeginLoc(),
2753                   diag::err_hexagon_builtin_unsupported_hvx);
2754   }
2755 
2756   return false;
2757 }
2758 
2759 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2760   struct ArgInfo {
2761     uint8_t OpNum;
2762     bool IsSigned;
2763     uint8_t BitWidth;
2764     uint8_t Align;
2765   };
2766   struct BuiltinInfo {
2767     unsigned BuiltinID;
2768     ArgInfo Infos[2];
2769   };
2770 
2771   static BuiltinInfo Infos[] = {
2772     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2773     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2774     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2775     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2776     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2777     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2778     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2779     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2780     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2781     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2782     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2783 
2784     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2787     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2789     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2790     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2795 
2796     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2848                                                       {{ 1, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2856                                                       {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2863                                                        { 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2865                                                        { 2, false, 6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2867                                                        { 3, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2869                                                        { 3, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2886                                                       {{ 2, false, 4,  0 },
2887                                                        { 3, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2889                                                       {{ 2, false, 4,  0 },
2890                                                        { 3, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2892                                                       {{ 2, false, 4,  0 },
2893                                                        { 3, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2895                                                       {{ 2, false, 4,  0 },
2896                                                        { 3, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2908                                                        { 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2910                                                        { 2, false, 6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2920                                                       {{ 1, false, 4,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2923                                                       {{ 1, false, 4,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2944                                                       {{ 3, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2949                                                       {{ 3, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2954                                                       {{ 3, false, 1,  0 }} },
2955   };
2956 
2957   // Use a dynamically initialized static to sort the table exactly once on
2958   // first run.
2959   static const bool SortOnce =
2960       (llvm::sort(Infos,
2961                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2962                    return LHS.BuiltinID < RHS.BuiltinID;
2963                  }),
2964        true);
2965   (void)SortOnce;
2966 
2967   const BuiltinInfo *F = llvm::partition_point(
2968       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2969   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2970     return false;
2971 
2972   bool Error = false;
2973 
2974   for (const ArgInfo &A : F->Infos) {
2975     // Ignore empty ArgInfo elements.
2976     if (A.BitWidth == 0)
2977       continue;
2978 
2979     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2980     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2981     if (!A.Align) {
2982       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2983     } else {
2984       unsigned M = 1 << A.Align;
2985       Min *= M;
2986       Max *= M;
2987       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2988                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2989     }
2990   }
2991   return Error;
2992 }
2993 
2994 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2995                                            CallExpr *TheCall) {
2996   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2997          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2998 }
2999 
3000 
3001 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3002 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3003 // ordering for DSP is unspecified. MSA is ordered by the data format used
3004 // by the underlying instruction i.e., df/m, df/n and then by size.
3005 //
3006 // FIXME: The size tests here should instead be tablegen'd along with the
3007 //        definitions from include/clang/Basic/BuiltinsMips.def.
3008 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3009 //        be too.
3010 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3011   unsigned i = 0, l = 0, u = 0, m = 0;
3012   switch (BuiltinID) {
3013   default: return false;
3014   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3015   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3016   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3017   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3018   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3019   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3020   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3021   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3022   // df/m field.
3023   // These intrinsics take an unsigned 3 bit immediate.
3024   case Mips::BI__builtin_msa_bclri_b:
3025   case Mips::BI__builtin_msa_bnegi_b:
3026   case Mips::BI__builtin_msa_bseti_b:
3027   case Mips::BI__builtin_msa_sat_s_b:
3028   case Mips::BI__builtin_msa_sat_u_b:
3029   case Mips::BI__builtin_msa_slli_b:
3030   case Mips::BI__builtin_msa_srai_b:
3031   case Mips::BI__builtin_msa_srari_b:
3032   case Mips::BI__builtin_msa_srli_b:
3033   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3034   case Mips::BI__builtin_msa_binsli_b:
3035   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3036   // These intrinsics take an unsigned 4 bit immediate.
3037   case Mips::BI__builtin_msa_bclri_h:
3038   case Mips::BI__builtin_msa_bnegi_h:
3039   case Mips::BI__builtin_msa_bseti_h:
3040   case Mips::BI__builtin_msa_sat_s_h:
3041   case Mips::BI__builtin_msa_sat_u_h:
3042   case Mips::BI__builtin_msa_slli_h:
3043   case Mips::BI__builtin_msa_srai_h:
3044   case Mips::BI__builtin_msa_srari_h:
3045   case Mips::BI__builtin_msa_srli_h:
3046   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3047   case Mips::BI__builtin_msa_binsli_h:
3048   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3049   // These intrinsics take an unsigned 5 bit immediate.
3050   // The first block of intrinsics actually have an unsigned 5 bit field,
3051   // not a df/n field.
3052   case Mips::BI__builtin_msa_cfcmsa:
3053   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3054   case Mips::BI__builtin_msa_clei_u_b:
3055   case Mips::BI__builtin_msa_clei_u_h:
3056   case Mips::BI__builtin_msa_clei_u_w:
3057   case Mips::BI__builtin_msa_clei_u_d:
3058   case Mips::BI__builtin_msa_clti_u_b:
3059   case Mips::BI__builtin_msa_clti_u_h:
3060   case Mips::BI__builtin_msa_clti_u_w:
3061   case Mips::BI__builtin_msa_clti_u_d:
3062   case Mips::BI__builtin_msa_maxi_u_b:
3063   case Mips::BI__builtin_msa_maxi_u_h:
3064   case Mips::BI__builtin_msa_maxi_u_w:
3065   case Mips::BI__builtin_msa_maxi_u_d:
3066   case Mips::BI__builtin_msa_mini_u_b:
3067   case Mips::BI__builtin_msa_mini_u_h:
3068   case Mips::BI__builtin_msa_mini_u_w:
3069   case Mips::BI__builtin_msa_mini_u_d:
3070   case Mips::BI__builtin_msa_addvi_b:
3071   case Mips::BI__builtin_msa_addvi_h:
3072   case Mips::BI__builtin_msa_addvi_w:
3073   case Mips::BI__builtin_msa_addvi_d:
3074   case Mips::BI__builtin_msa_bclri_w:
3075   case Mips::BI__builtin_msa_bnegi_w:
3076   case Mips::BI__builtin_msa_bseti_w:
3077   case Mips::BI__builtin_msa_sat_s_w:
3078   case Mips::BI__builtin_msa_sat_u_w:
3079   case Mips::BI__builtin_msa_slli_w:
3080   case Mips::BI__builtin_msa_srai_w:
3081   case Mips::BI__builtin_msa_srari_w:
3082   case Mips::BI__builtin_msa_srli_w:
3083   case Mips::BI__builtin_msa_srlri_w:
3084   case Mips::BI__builtin_msa_subvi_b:
3085   case Mips::BI__builtin_msa_subvi_h:
3086   case Mips::BI__builtin_msa_subvi_w:
3087   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3088   case Mips::BI__builtin_msa_binsli_w:
3089   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3090   // These intrinsics take an unsigned 6 bit immediate.
3091   case Mips::BI__builtin_msa_bclri_d:
3092   case Mips::BI__builtin_msa_bnegi_d:
3093   case Mips::BI__builtin_msa_bseti_d:
3094   case Mips::BI__builtin_msa_sat_s_d:
3095   case Mips::BI__builtin_msa_sat_u_d:
3096   case Mips::BI__builtin_msa_slli_d:
3097   case Mips::BI__builtin_msa_srai_d:
3098   case Mips::BI__builtin_msa_srari_d:
3099   case Mips::BI__builtin_msa_srli_d:
3100   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3101   case Mips::BI__builtin_msa_binsli_d:
3102   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3103   // These intrinsics take a signed 5 bit immediate.
3104   case Mips::BI__builtin_msa_ceqi_b:
3105   case Mips::BI__builtin_msa_ceqi_h:
3106   case Mips::BI__builtin_msa_ceqi_w:
3107   case Mips::BI__builtin_msa_ceqi_d:
3108   case Mips::BI__builtin_msa_clti_s_b:
3109   case Mips::BI__builtin_msa_clti_s_h:
3110   case Mips::BI__builtin_msa_clti_s_w:
3111   case Mips::BI__builtin_msa_clti_s_d:
3112   case Mips::BI__builtin_msa_clei_s_b:
3113   case Mips::BI__builtin_msa_clei_s_h:
3114   case Mips::BI__builtin_msa_clei_s_w:
3115   case Mips::BI__builtin_msa_clei_s_d:
3116   case Mips::BI__builtin_msa_maxi_s_b:
3117   case Mips::BI__builtin_msa_maxi_s_h:
3118   case Mips::BI__builtin_msa_maxi_s_w:
3119   case Mips::BI__builtin_msa_maxi_s_d:
3120   case Mips::BI__builtin_msa_mini_s_b:
3121   case Mips::BI__builtin_msa_mini_s_h:
3122   case Mips::BI__builtin_msa_mini_s_w:
3123   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3124   // These intrinsics take an unsigned 8 bit immediate.
3125   case Mips::BI__builtin_msa_andi_b:
3126   case Mips::BI__builtin_msa_nori_b:
3127   case Mips::BI__builtin_msa_ori_b:
3128   case Mips::BI__builtin_msa_shf_b:
3129   case Mips::BI__builtin_msa_shf_h:
3130   case Mips::BI__builtin_msa_shf_w:
3131   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3132   case Mips::BI__builtin_msa_bseli_b:
3133   case Mips::BI__builtin_msa_bmnzi_b:
3134   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3135   // df/n format
3136   // These intrinsics take an unsigned 4 bit immediate.
3137   case Mips::BI__builtin_msa_copy_s_b:
3138   case Mips::BI__builtin_msa_copy_u_b:
3139   case Mips::BI__builtin_msa_insve_b:
3140   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3141   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3142   // These intrinsics take an unsigned 3 bit immediate.
3143   case Mips::BI__builtin_msa_copy_s_h:
3144   case Mips::BI__builtin_msa_copy_u_h:
3145   case Mips::BI__builtin_msa_insve_h:
3146   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3147   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3148   // These intrinsics take an unsigned 2 bit immediate.
3149   case Mips::BI__builtin_msa_copy_s_w:
3150   case Mips::BI__builtin_msa_copy_u_w:
3151   case Mips::BI__builtin_msa_insve_w:
3152   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3153   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3154   // These intrinsics take an unsigned 1 bit immediate.
3155   case Mips::BI__builtin_msa_copy_s_d:
3156   case Mips::BI__builtin_msa_copy_u_d:
3157   case Mips::BI__builtin_msa_insve_d:
3158   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3159   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3160   // Memory offsets and immediate loads.
3161   // These intrinsics take a signed 10 bit immediate.
3162   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3163   case Mips::BI__builtin_msa_ldi_h:
3164   case Mips::BI__builtin_msa_ldi_w:
3165   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3166   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3167   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3168   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3169   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3170   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3171   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3172   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3173   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3174   }
3175 
3176   if (!m)
3177     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3178 
3179   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3180          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3181 }
3182 
3183 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3184   unsigned i = 0, l = 0, u = 0;
3185   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3186                       BuiltinID == PPC::BI__builtin_divdeu ||
3187                       BuiltinID == PPC::BI__builtin_bpermd;
3188   bool IsTarget64Bit = Context.getTargetInfo()
3189                               .getTypeWidth(Context
3190                                             .getTargetInfo()
3191                                             .getIntPtrType()) == 64;
3192   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3193                        BuiltinID == PPC::BI__builtin_divweu ||
3194                        BuiltinID == PPC::BI__builtin_divde ||
3195                        BuiltinID == PPC::BI__builtin_divdeu;
3196 
3197   if (Is64BitBltin && !IsTarget64Bit)
3198     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3199            << TheCall->getSourceRange();
3200 
3201   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3202       (BuiltinID == PPC::BI__builtin_bpermd &&
3203        !Context.getTargetInfo().hasFeature("bpermd")))
3204     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3205            << TheCall->getSourceRange();
3206 
3207   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3208     if (!Context.getTargetInfo().hasFeature("vsx"))
3209       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3210              << TheCall->getSourceRange();
3211     return false;
3212   };
3213 
3214   switch (BuiltinID) {
3215   default: return false;
3216   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3217   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3218     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3219            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3220   case PPC::BI__builtin_tbegin:
3221   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3222   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3223   case PPC::BI__builtin_tabortwc:
3224   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3225   case PPC::BI__builtin_tabortwci:
3226   case PPC::BI__builtin_tabortdci:
3227     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3228            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3229   case PPC::BI__builtin_vsx_xxpermdi:
3230   case PPC::BI__builtin_vsx_xxsldwi:
3231     return SemaBuiltinVSX(TheCall);
3232   case PPC::BI__builtin_unpack_vector_int128:
3233     return SemaVSXCheck(TheCall) ||
3234            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3235   case PPC::BI__builtin_pack_vector_int128:
3236     return SemaVSXCheck(TheCall);
3237   }
3238   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3239 }
3240 
3241 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3242                                            CallExpr *TheCall) {
3243   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3244     Expr *Arg = TheCall->getArg(0);
3245     llvm::APSInt AbortCode(32);
3246     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3247         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3248       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3249              << Arg->getSourceRange();
3250   }
3251 
3252   // For intrinsics which take an immediate value as part of the instruction,
3253   // range check them here.
3254   unsigned i = 0, l = 0, u = 0;
3255   switch (BuiltinID) {
3256   default: return false;
3257   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3258   case SystemZ::BI__builtin_s390_verimb:
3259   case SystemZ::BI__builtin_s390_verimh:
3260   case SystemZ::BI__builtin_s390_verimf:
3261   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3262   case SystemZ::BI__builtin_s390_vfaeb:
3263   case SystemZ::BI__builtin_s390_vfaeh:
3264   case SystemZ::BI__builtin_s390_vfaef:
3265   case SystemZ::BI__builtin_s390_vfaebs:
3266   case SystemZ::BI__builtin_s390_vfaehs:
3267   case SystemZ::BI__builtin_s390_vfaefs:
3268   case SystemZ::BI__builtin_s390_vfaezb:
3269   case SystemZ::BI__builtin_s390_vfaezh:
3270   case SystemZ::BI__builtin_s390_vfaezf:
3271   case SystemZ::BI__builtin_s390_vfaezbs:
3272   case SystemZ::BI__builtin_s390_vfaezhs:
3273   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3274   case SystemZ::BI__builtin_s390_vfisb:
3275   case SystemZ::BI__builtin_s390_vfidb:
3276     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3277            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3278   case SystemZ::BI__builtin_s390_vftcisb:
3279   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3280   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3281   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3282   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3283   case SystemZ::BI__builtin_s390_vstrcb:
3284   case SystemZ::BI__builtin_s390_vstrch:
3285   case SystemZ::BI__builtin_s390_vstrcf:
3286   case SystemZ::BI__builtin_s390_vstrczb:
3287   case SystemZ::BI__builtin_s390_vstrczh:
3288   case SystemZ::BI__builtin_s390_vstrczf:
3289   case SystemZ::BI__builtin_s390_vstrcbs:
3290   case SystemZ::BI__builtin_s390_vstrchs:
3291   case SystemZ::BI__builtin_s390_vstrcfs:
3292   case SystemZ::BI__builtin_s390_vstrczbs:
3293   case SystemZ::BI__builtin_s390_vstrczhs:
3294   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3295   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3296   case SystemZ::BI__builtin_s390_vfminsb:
3297   case SystemZ::BI__builtin_s390_vfmaxsb:
3298   case SystemZ::BI__builtin_s390_vfmindb:
3299   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3300   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3301   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3302   }
3303   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3304 }
3305 
3306 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3307 /// This checks that the target supports __builtin_cpu_supports and
3308 /// that the string argument is constant and valid.
3309 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3310   Expr *Arg = TheCall->getArg(0);
3311 
3312   // Check if the argument is a string literal.
3313   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3314     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3315            << Arg->getSourceRange();
3316 
3317   // Check the contents of the string.
3318   StringRef Feature =
3319       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3320   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3321     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3322            << Arg->getSourceRange();
3323   return false;
3324 }
3325 
3326 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3327 /// This checks that the target supports __builtin_cpu_is and
3328 /// that the string argument is constant and valid.
3329 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3330   Expr *Arg = TheCall->getArg(0);
3331 
3332   // Check if the argument is a string literal.
3333   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3334     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3335            << Arg->getSourceRange();
3336 
3337   // Check the contents of the string.
3338   StringRef Feature =
3339       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3340   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3341     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3342            << Arg->getSourceRange();
3343   return false;
3344 }
3345 
3346 // Check if the rounding mode is legal.
3347 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3348   // Indicates if this instruction has rounding control or just SAE.
3349   bool HasRC = false;
3350 
3351   unsigned ArgNum = 0;
3352   switch (BuiltinID) {
3353   default:
3354     return false;
3355   case X86::BI__builtin_ia32_vcvttsd2si32:
3356   case X86::BI__builtin_ia32_vcvttsd2si64:
3357   case X86::BI__builtin_ia32_vcvttsd2usi32:
3358   case X86::BI__builtin_ia32_vcvttsd2usi64:
3359   case X86::BI__builtin_ia32_vcvttss2si32:
3360   case X86::BI__builtin_ia32_vcvttss2si64:
3361   case X86::BI__builtin_ia32_vcvttss2usi32:
3362   case X86::BI__builtin_ia32_vcvttss2usi64:
3363     ArgNum = 1;
3364     break;
3365   case X86::BI__builtin_ia32_maxpd512:
3366   case X86::BI__builtin_ia32_maxps512:
3367   case X86::BI__builtin_ia32_minpd512:
3368   case X86::BI__builtin_ia32_minps512:
3369     ArgNum = 2;
3370     break;
3371   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3372   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3373   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3374   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3375   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3376   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3377   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3378   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3379   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3380   case X86::BI__builtin_ia32_exp2pd_mask:
3381   case X86::BI__builtin_ia32_exp2ps_mask:
3382   case X86::BI__builtin_ia32_getexppd512_mask:
3383   case X86::BI__builtin_ia32_getexpps512_mask:
3384   case X86::BI__builtin_ia32_rcp28pd_mask:
3385   case X86::BI__builtin_ia32_rcp28ps_mask:
3386   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3387   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3388   case X86::BI__builtin_ia32_vcomisd:
3389   case X86::BI__builtin_ia32_vcomiss:
3390   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3391     ArgNum = 3;
3392     break;
3393   case X86::BI__builtin_ia32_cmppd512_mask:
3394   case X86::BI__builtin_ia32_cmpps512_mask:
3395   case X86::BI__builtin_ia32_cmpsd_mask:
3396   case X86::BI__builtin_ia32_cmpss_mask:
3397   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3398   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3399   case X86::BI__builtin_ia32_getexpss128_round_mask:
3400   case X86::BI__builtin_ia32_getmantpd512_mask:
3401   case X86::BI__builtin_ia32_getmantps512_mask:
3402   case X86::BI__builtin_ia32_maxsd_round_mask:
3403   case X86::BI__builtin_ia32_maxss_round_mask:
3404   case X86::BI__builtin_ia32_minsd_round_mask:
3405   case X86::BI__builtin_ia32_minss_round_mask:
3406   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3407   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3408   case X86::BI__builtin_ia32_reducepd512_mask:
3409   case X86::BI__builtin_ia32_reduceps512_mask:
3410   case X86::BI__builtin_ia32_rndscalepd_mask:
3411   case X86::BI__builtin_ia32_rndscaleps_mask:
3412   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3413   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3414     ArgNum = 4;
3415     break;
3416   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3417   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3418   case X86::BI__builtin_ia32_fixupimmps512_mask:
3419   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3420   case X86::BI__builtin_ia32_fixupimmsd_mask:
3421   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3422   case X86::BI__builtin_ia32_fixupimmss_mask:
3423   case X86::BI__builtin_ia32_fixupimmss_maskz:
3424   case X86::BI__builtin_ia32_getmantsd_round_mask:
3425   case X86::BI__builtin_ia32_getmantss_round_mask:
3426   case X86::BI__builtin_ia32_rangepd512_mask:
3427   case X86::BI__builtin_ia32_rangeps512_mask:
3428   case X86::BI__builtin_ia32_rangesd128_round_mask:
3429   case X86::BI__builtin_ia32_rangess128_round_mask:
3430   case X86::BI__builtin_ia32_reducesd_mask:
3431   case X86::BI__builtin_ia32_reducess_mask:
3432   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3433   case X86::BI__builtin_ia32_rndscaless_round_mask:
3434     ArgNum = 5;
3435     break;
3436   case X86::BI__builtin_ia32_vcvtsd2si64:
3437   case X86::BI__builtin_ia32_vcvtsd2si32:
3438   case X86::BI__builtin_ia32_vcvtsd2usi32:
3439   case X86::BI__builtin_ia32_vcvtsd2usi64:
3440   case X86::BI__builtin_ia32_vcvtss2si32:
3441   case X86::BI__builtin_ia32_vcvtss2si64:
3442   case X86::BI__builtin_ia32_vcvtss2usi32:
3443   case X86::BI__builtin_ia32_vcvtss2usi64:
3444   case X86::BI__builtin_ia32_sqrtpd512:
3445   case X86::BI__builtin_ia32_sqrtps512:
3446     ArgNum = 1;
3447     HasRC = true;
3448     break;
3449   case X86::BI__builtin_ia32_addpd512:
3450   case X86::BI__builtin_ia32_addps512:
3451   case X86::BI__builtin_ia32_divpd512:
3452   case X86::BI__builtin_ia32_divps512:
3453   case X86::BI__builtin_ia32_mulpd512:
3454   case X86::BI__builtin_ia32_mulps512:
3455   case X86::BI__builtin_ia32_subpd512:
3456   case X86::BI__builtin_ia32_subps512:
3457   case X86::BI__builtin_ia32_cvtsi2sd64:
3458   case X86::BI__builtin_ia32_cvtsi2ss32:
3459   case X86::BI__builtin_ia32_cvtsi2ss64:
3460   case X86::BI__builtin_ia32_cvtusi2sd64:
3461   case X86::BI__builtin_ia32_cvtusi2ss32:
3462   case X86::BI__builtin_ia32_cvtusi2ss64:
3463     ArgNum = 2;
3464     HasRC = true;
3465     break;
3466   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3467   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3468   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3469   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3470   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3471   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3472   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3473   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3474   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3475   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3476   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3477   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3478   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3479   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3480   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3481     ArgNum = 3;
3482     HasRC = true;
3483     break;
3484   case X86::BI__builtin_ia32_addss_round_mask:
3485   case X86::BI__builtin_ia32_addsd_round_mask:
3486   case X86::BI__builtin_ia32_divss_round_mask:
3487   case X86::BI__builtin_ia32_divsd_round_mask:
3488   case X86::BI__builtin_ia32_mulss_round_mask:
3489   case X86::BI__builtin_ia32_mulsd_round_mask:
3490   case X86::BI__builtin_ia32_subss_round_mask:
3491   case X86::BI__builtin_ia32_subsd_round_mask:
3492   case X86::BI__builtin_ia32_scalefpd512_mask:
3493   case X86::BI__builtin_ia32_scalefps512_mask:
3494   case X86::BI__builtin_ia32_scalefsd_round_mask:
3495   case X86::BI__builtin_ia32_scalefss_round_mask:
3496   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3497   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3498   case X86::BI__builtin_ia32_sqrtss_round_mask:
3499   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3500   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3501   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3502   case X86::BI__builtin_ia32_vfmaddss3_mask:
3503   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3504   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3505   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3506   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3507   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3508   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3509   case X86::BI__builtin_ia32_vfmaddps512_mask:
3510   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3511   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3512   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3513   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3514   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3515   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3516   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3517   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3518   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3519   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3520   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3521     ArgNum = 4;
3522     HasRC = true;
3523     break;
3524   }
3525 
3526   llvm::APSInt Result;
3527 
3528   // We can't check the value of a dependent argument.
3529   Expr *Arg = TheCall->getArg(ArgNum);
3530   if (Arg->isTypeDependent() || Arg->isValueDependent())
3531     return false;
3532 
3533   // Check constant-ness first.
3534   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3535     return true;
3536 
3537   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3538   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3539   // combined with ROUND_NO_EXC.
3540   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3541       Result == 8/*ROUND_NO_EXC*/ ||
3542       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3543     return false;
3544 
3545   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3546          << Arg->getSourceRange();
3547 }
3548 
3549 // Check if the gather/scatter scale is legal.
3550 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3551                                              CallExpr *TheCall) {
3552   unsigned ArgNum = 0;
3553   switch (BuiltinID) {
3554   default:
3555     return false;
3556   case X86::BI__builtin_ia32_gatherpfdpd:
3557   case X86::BI__builtin_ia32_gatherpfdps:
3558   case X86::BI__builtin_ia32_gatherpfqpd:
3559   case X86::BI__builtin_ia32_gatherpfqps:
3560   case X86::BI__builtin_ia32_scatterpfdpd:
3561   case X86::BI__builtin_ia32_scatterpfdps:
3562   case X86::BI__builtin_ia32_scatterpfqpd:
3563   case X86::BI__builtin_ia32_scatterpfqps:
3564     ArgNum = 3;
3565     break;
3566   case X86::BI__builtin_ia32_gatherd_pd:
3567   case X86::BI__builtin_ia32_gatherd_pd256:
3568   case X86::BI__builtin_ia32_gatherq_pd:
3569   case X86::BI__builtin_ia32_gatherq_pd256:
3570   case X86::BI__builtin_ia32_gatherd_ps:
3571   case X86::BI__builtin_ia32_gatherd_ps256:
3572   case X86::BI__builtin_ia32_gatherq_ps:
3573   case X86::BI__builtin_ia32_gatherq_ps256:
3574   case X86::BI__builtin_ia32_gatherd_q:
3575   case X86::BI__builtin_ia32_gatherd_q256:
3576   case X86::BI__builtin_ia32_gatherq_q:
3577   case X86::BI__builtin_ia32_gatherq_q256:
3578   case X86::BI__builtin_ia32_gatherd_d:
3579   case X86::BI__builtin_ia32_gatherd_d256:
3580   case X86::BI__builtin_ia32_gatherq_d:
3581   case X86::BI__builtin_ia32_gatherq_d256:
3582   case X86::BI__builtin_ia32_gather3div2df:
3583   case X86::BI__builtin_ia32_gather3div2di:
3584   case X86::BI__builtin_ia32_gather3div4df:
3585   case X86::BI__builtin_ia32_gather3div4di:
3586   case X86::BI__builtin_ia32_gather3div4sf:
3587   case X86::BI__builtin_ia32_gather3div4si:
3588   case X86::BI__builtin_ia32_gather3div8sf:
3589   case X86::BI__builtin_ia32_gather3div8si:
3590   case X86::BI__builtin_ia32_gather3siv2df:
3591   case X86::BI__builtin_ia32_gather3siv2di:
3592   case X86::BI__builtin_ia32_gather3siv4df:
3593   case X86::BI__builtin_ia32_gather3siv4di:
3594   case X86::BI__builtin_ia32_gather3siv4sf:
3595   case X86::BI__builtin_ia32_gather3siv4si:
3596   case X86::BI__builtin_ia32_gather3siv8sf:
3597   case X86::BI__builtin_ia32_gather3siv8si:
3598   case X86::BI__builtin_ia32_gathersiv8df:
3599   case X86::BI__builtin_ia32_gathersiv16sf:
3600   case X86::BI__builtin_ia32_gatherdiv8df:
3601   case X86::BI__builtin_ia32_gatherdiv16sf:
3602   case X86::BI__builtin_ia32_gathersiv8di:
3603   case X86::BI__builtin_ia32_gathersiv16si:
3604   case X86::BI__builtin_ia32_gatherdiv8di:
3605   case X86::BI__builtin_ia32_gatherdiv16si:
3606   case X86::BI__builtin_ia32_scatterdiv2df:
3607   case X86::BI__builtin_ia32_scatterdiv2di:
3608   case X86::BI__builtin_ia32_scatterdiv4df:
3609   case X86::BI__builtin_ia32_scatterdiv4di:
3610   case X86::BI__builtin_ia32_scatterdiv4sf:
3611   case X86::BI__builtin_ia32_scatterdiv4si:
3612   case X86::BI__builtin_ia32_scatterdiv8sf:
3613   case X86::BI__builtin_ia32_scatterdiv8si:
3614   case X86::BI__builtin_ia32_scattersiv2df:
3615   case X86::BI__builtin_ia32_scattersiv2di:
3616   case X86::BI__builtin_ia32_scattersiv4df:
3617   case X86::BI__builtin_ia32_scattersiv4di:
3618   case X86::BI__builtin_ia32_scattersiv4sf:
3619   case X86::BI__builtin_ia32_scattersiv4si:
3620   case X86::BI__builtin_ia32_scattersiv8sf:
3621   case X86::BI__builtin_ia32_scattersiv8si:
3622   case X86::BI__builtin_ia32_scattersiv8df:
3623   case X86::BI__builtin_ia32_scattersiv16sf:
3624   case X86::BI__builtin_ia32_scatterdiv8df:
3625   case X86::BI__builtin_ia32_scatterdiv16sf:
3626   case X86::BI__builtin_ia32_scattersiv8di:
3627   case X86::BI__builtin_ia32_scattersiv16si:
3628   case X86::BI__builtin_ia32_scatterdiv8di:
3629   case X86::BI__builtin_ia32_scatterdiv16si:
3630     ArgNum = 4;
3631     break;
3632   }
3633 
3634   llvm::APSInt Result;
3635 
3636   // We can't check the value of a dependent argument.
3637   Expr *Arg = TheCall->getArg(ArgNum);
3638   if (Arg->isTypeDependent() || Arg->isValueDependent())
3639     return false;
3640 
3641   // Check constant-ness first.
3642   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3643     return true;
3644 
3645   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3646     return false;
3647 
3648   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3649          << Arg->getSourceRange();
3650 }
3651 
3652 static bool isX86_32Builtin(unsigned BuiltinID) {
3653   // These builtins only work on x86-32 targets.
3654   switch (BuiltinID) {
3655   case X86::BI__builtin_ia32_readeflags_u32:
3656   case X86::BI__builtin_ia32_writeeflags_u32:
3657     return true;
3658   }
3659 
3660   return false;
3661 }
3662 
3663 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3664   if (BuiltinID == X86::BI__builtin_cpu_supports)
3665     return SemaBuiltinCpuSupports(*this, TheCall);
3666 
3667   if (BuiltinID == X86::BI__builtin_cpu_is)
3668     return SemaBuiltinCpuIs(*this, TheCall);
3669 
3670   // Check for 32-bit only builtins on a 64-bit target.
3671   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3672   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3673     return Diag(TheCall->getCallee()->getBeginLoc(),
3674                 diag::err_32_bit_builtin_64_bit_tgt);
3675 
3676   // If the intrinsic has rounding or SAE make sure its valid.
3677   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3678     return true;
3679 
3680   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3681   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3682     return true;
3683 
3684   // For intrinsics which take an immediate value as part of the instruction,
3685   // range check them here.
3686   int i = 0, l = 0, u = 0;
3687   switch (BuiltinID) {
3688   default:
3689     return false;
3690   case X86::BI__builtin_ia32_vec_ext_v2si:
3691   case X86::BI__builtin_ia32_vec_ext_v2di:
3692   case X86::BI__builtin_ia32_vextractf128_pd256:
3693   case X86::BI__builtin_ia32_vextractf128_ps256:
3694   case X86::BI__builtin_ia32_vextractf128_si256:
3695   case X86::BI__builtin_ia32_extract128i256:
3696   case X86::BI__builtin_ia32_extractf64x4_mask:
3697   case X86::BI__builtin_ia32_extracti64x4_mask:
3698   case X86::BI__builtin_ia32_extractf32x8_mask:
3699   case X86::BI__builtin_ia32_extracti32x8_mask:
3700   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3701   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3702   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3703   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3704     i = 1; l = 0; u = 1;
3705     break;
3706   case X86::BI__builtin_ia32_vec_set_v2di:
3707   case X86::BI__builtin_ia32_vinsertf128_pd256:
3708   case X86::BI__builtin_ia32_vinsertf128_ps256:
3709   case X86::BI__builtin_ia32_vinsertf128_si256:
3710   case X86::BI__builtin_ia32_insert128i256:
3711   case X86::BI__builtin_ia32_insertf32x8:
3712   case X86::BI__builtin_ia32_inserti32x8:
3713   case X86::BI__builtin_ia32_insertf64x4:
3714   case X86::BI__builtin_ia32_inserti64x4:
3715   case X86::BI__builtin_ia32_insertf64x2_256:
3716   case X86::BI__builtin_ia32_inserti64x2_256:
3717   case X86::BI__builtin_ia32_insertf32x4_256:
3718   case X86::BI__builtin_ia32_inserti32x4_256:
3719     i = 2; l = 0; u = 1;
3720     break;
3721   case X86::BI__builtin_ia32_vpermilpd:
3722   case X86::BI__builtin_ia32_vec_ext_v4hi:
3723   case X86::BI__builtin_ia32_vec_ext_v4si:
3724   case X86::BI__builtin_ia32_vec_ext_v4sf:
3725   case X86::BI__builtin_ia32_vec_ext_v4di:
3726   case X86::BI__builtin_ia32_extractf32x4_mask:
3727   case X86::BI__builtin_ia32_extracti32x4_mask:
3728   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3729   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3730     i = 1; l = 0; u = 3;
3731     break;
3732   case X86::BI_mm_prefetch:
3733   case X86::BI__builtin_ia32_vec_ext_v8hi:
3734   case X86::BI__builtin_ia32_vec_ext_v8si:
3735     i = 1; l = 0; u = 7;
3736     break;
3737   case X86::BI__builtin_ia32_sha1rnds4:
3738   case X86::BI__builtin_ia32_blendpd:
3739   case X86::BI__builtin_ia32_shufpd:
3740   case X86::BI__builtin_ia32_vec_set_v4hi:
3741   case X86::BI__builtin_ia32_vec_set_v4si:
3742   case X86::BI__builtin_ia32_vec_set_v4di:
3743   case X86::BI__builtin_ia32_shuf_f32x4_256:
3744   case X86::BI__builtin_ia32_shuf_f64x2_256:
3745   case X86::BI__builtin_ia32_shuf_i32x4_256:
3746   case X86::BI__builtin_ia32_shuf_i64x2_256:
3747   case X86::BI__builtin_ia32_insertf64x2_512:
3748   case X86::BI__builtin_ia32_inserti64x2_512:
3749   case X86::BI__builtin_ia32_insertf32x4:
3750   case X86::BI__builtin_ia32_inserti32x4:
3751     i = 2; l = 0; u = 3;
3752     break;
3753   case X86::BI__builtin_ia32_vpermil2pd:
3754   case X86::BI__builtin_ia32_vpermil2pd256:
3755   case X86::BI__builtin_ia32_vpermil2ps:
3756   case X86::BI__builtin_ia32_vpermil2ps256:
3757     i = 3; l = 0; u = 3;
3758     break;
3759   case X86::BI__builtin_ia32_cmpb128_mask:
3760   case X86::BI__builtin_ia32_cmpw128_mask:
3761   case X86::BI__builtin_ia32_cmpd128_mask:
3762   case X86::BI__builtin_ia32_cmpq128_mask:
3763   case X86::BI__builtin_ia32_cmpb256_mask:
3764   case X86::BI__builtin_ia32_cmpw256_mask:
3765   case X86::BI__builtin_ia32_cmpd256_mask:
3766   case X86::BI__builtin_ia32_cmpq256_mask:
3767   case X86::BI__builtin_ia32_cmpb512_mask:
3768   case X86::BI__builtin_ia32_cmpw512_mask:
3769   case X86::BI__builtin_ia32_cmpd512_mask:
3770   case X86::BI__builtin_ia32_cmpq512_mask:
3771   case X86::BI__builtin_ia32_ucmpb128_mask:
3772   case X86::BI__builtin_ia32_ucmpw128_mask:
3773   case X86::BI__builtin_ia32_ucmpd128_mask:
3774   case X86::BI__builtin_ia32_ucmpq128_mask:
3775   case X86::BI__builtin_ia32_ucmpb256_mask:
3776   case X86::BI__builtin_ia32_ucmpw256_mask:
3777   case X86::BI__builtin_ia32_ucmpd256_mask:
3778   case X86::BI__builtin_ia32_ucmpq256_mask:
3779   case X86::BI__builtin_ia32_ucmpb512_mask:
3780   case X86::BI__builtin_ia32_ucmpw512_mask:
3781   case X86::BI__builtin_ia32_ucmpd512_mask:
3782   case X86::BI__builtin_ia32_ucmpq512_mask:
3783   case X86::BI__builtin_ia32_vpcomub:
3784   case X86::BI__builtin_ia32_vpcomuw:
3785   case X86::BI__builtin_ia32_vpcomud:
3786   case X86::BI__builtin_ia32_vpcomuq:
3787   case X86::BI__builtin_ia32_vpcomb:
3788   case X86::BI__builtin_ia32_vpcomw:
3789   case X86::BI__builtin_ia32_vpcomd:
3790   case X86::BI__builtin_ia32_vpcomq:
3791   case X86::BI__builtin_ia32_vec_set_v8hi:
3792   case X86::BI__builtin_ia32_vec_set_v8si:
3793     i = 2; l = 0; u = 7;
3794     break;
3795   case X86::BI__builtin_ia32_vpermilpd256:
3796   case X86::BI__builtin_ia32_roundps:
3797   case X86::BI__builtin_ia32_roundpd:
3798   case X86::BI__builtin_ia32_roundps256:
3799   case X86::BI__builtin_ia32_roundpd256:
3800   case X86::BI__builtin_ia32_getmantpd128_mask:
3801   case X86::BI__builtin_ia32_getmantpd256_mask:
3802   case X86::BI__builtin_ia32_getmantps128_mask:
3803   case X86::BI__builtin_ia32_getmantps256_mask:
3804   case X86::BI__builtin_ia32_getmantpd512_mask:
3805   case X86::BI__builtin_ia32_getmantps512_mask:
3806   case X86::BI__builtin_ia32_vec_ext_v16qi:
3807   case X86::BI__builtin_ia32_vec_ext_v16hi:
3808     i = 1; l = 0; u = 15;
3809     break;
3810   case X86::BI__builtin_ia32_pblendd128:
3811   case X86::BI__builtin_ia32_blendps:
3812   case X86::BI__builtin_ia32_blendpd256:
3813   case X86::BI__builtin_ia32_shufpd256:
3814   case X86::BI__builtin_ia32_roundss:
3815   case X86::BI__builtin_ia32_roundsd:
3816   case X86::BI__builtin_ia32_rangepd128_mask:
3817   case X86::BI__builtin_ia32_rangepd256_mask:
3818   case X86::BI__builtin_ia32_rangepd512_mask:
3819   case X86::BI__builtin_ia32_rangeps128_mask:
3820   case X86::BI__builtin_ia32_rangeps256_mask:
3821   case X86::BI__builtin_ia32_rangeps512_mask:
3822   case X86::BI__builtin_ia32_getmantsd_round_mask:
3823   case X86::BI__builtin_ia32_getmantss_round_mask:
3824   case X86::BI__builtin_ia32_vec_set_v16qi:
3825   case X86::BI__builtin_ia32_vec_set_v16hi:
3826     i = 2; l = 0; u = 15;
3827     break;
3828   case X86::BI__builtin_ia32_vec_ext_v32qi:
3829     i = 1; l = 0; u = 31;
3830     break;
3831   case X86::BI__builtin_ia32_cmpps:
3832   case X86::BI__builtin_ia32_cmpss:
3833   case X86::BI__builtin_ia32_cmppd:
3834   case X86::BI__builtin_ia32_cmpsd:
3835   case X86::BI__builtin_ia32_cmpps256:
3836   case X86::BI__builtin_ia32_cmppd256:
3837   case X86::BI__builtin_ia32_cmpps128_mask:
3838   case X86::BI__builtin_ia32_cmppd128_mask:
3839   case X86::BI__builtin_ia32_cmpps256_mask:
3840   case X86::BI__builtin_ia32_cmppd256_mask:
3841   case X86::BI__builtin_ia32_cmpps512_mask:
3842   case X86::BI__builtin_ia32_cmppd512_mask:
3843   case X86::BI__builtin_ia32_cmpsd_mask:
3844   case X86::BI__builtin_ia32_cmpss_mask:
3845   case X86::BI__builtin_ia32_vec_set_v32qi:
3846     i = 2; l = 0; u = 31;
3847     break;
3848   case X86::BI__builtin_ia32_permdf256:
3849   case X86::BI__builtin_ia32_permdi256:
3850   case X86::BI__builtin_ia32_permdf512:
3851   case X86::BI__builtin_ia32_permdi512:
3852   case X86::BI__builtin_ia32_vpermilps:
3853   case X86::BI__builtin_ia32_vpermilps256:
3854   case X86::BI__builtin_ia32_vpermilpd512:
3855   case X86::BI__builtin_ia32_vpermilps512:
3856   case X86::BI__builtin_ia32_pshufd:
3857   case X86::BI__builtin_ia32_pshufd256:
3858   case X86::BI__builtin_ia32_pshufd512:
3859   case X86::BI__builtin_ia32_pshufhw:
3860   case X86::BI__builtin_ia32_pshufhw256:
3861   case X86::BI__builtin_ia32_pshufhw512:
3862   case X86::BI__builtin_ia32_pshuflw:
3863   case X86::BI__builtin_ia32_pshuflw256:
3864   case X86::BI__builtin_ia32_pshuflw512:
3865   case X86::BI__builtin_ia32_vcvtps2ph:
3866   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3867   case X86::BI__builtin_ia32_vcvtps2ph256:
3868   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3869   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3870   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3871   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3872   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3873   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3874   case X86::BI__builtin_ia32_rndscaleps_mask:
3875   case X86::BI__builtin_ia32_rndscalepd_mask:
3876   case X86::BI__builtin_ia32_reducepd128_mask:
3877   case X86::BI__builtin_ia32_reducepd256_mask:
3878   case X86::BI__builtin_ia32_reducepd512_mask:
3879   case X86::BI__builtin_ia32_reduceps128_mask:
3880   case X86::BI__builtin_ia32_reduceps256_mask:
3881   case X86::BI__builtin_ia32_reduceps512_mask:
3882   case X86::BI__builtin_ia32_prold512:
3883   case X86::BI__builtin_ia32_prolq512:
3884   case X86::BI__builtin_ia32_prold128:
3885   case X86::BI__builtin_ia32_prold256:
3886   case X86::BI__builtin_ia32_prolq128:
3887   case X86::BI__builtin_ia32_prolq256:
3888   case X86::BI__builtin_ia32_prord512:
3889   case X86::BI__builtin_ia32_prorq512:
3890   case X86::BI__builtin_ia32_prord128:
3891   case X86::BI__builtin_ia32_prord256:
3892   case X86::BI__builtin_ia32_prorq128:
3893   case X86::BI__builtin_ia32_prorq256:
3894   case X86::BI__builtin_ia32_fpclasspd128_mask:
3895   case X86::BI__builtin_ia32_fpclasspd256_mask:
3896   case X86::BI__builtin_ia32_fpclassps128_mask:
3897   case X86::BI__builtin_ia32_fpclassps256_mask:
3898   case X86::BI__builtin_ia32_fpclassps512_mask:
3899   case X86::BI__builtin_ia32_fpclasspd512_mask:
3900   case X86::BI__builtin_ia32_fpclasssd_mask:
3901   case X86::BI__builtin_ia32_fpclassss_mask:
3902   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3903   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3904   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3905   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3906   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3907   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3908   case X86::BI__builtin_ia32_kshiftliqi:
3909   case X86::BI__builtin_ia32_kshiftlihi:
3910   case X86::BI__builtin_ia32_kshiftlisi:
3911   case X86::BI__builtin_ia32_kshiftlidi:
3912   case X86::BI__builtin_ia32_kshiftriqi:
3913   case X86::BI__builtin_ia32_kshiftrihi:
3914   case X86::BI__builtin_ia32_kshiftrisi:
3915   case X86::BI__builtin_ia32_kshiftridi:
3916     i = 1; l = 0; u = 255;
3917     break;
3918   case X86::BI__builtin_ia32_vperm2f128_pd256:
3919   case X86::BI__builtin_ia32_vperm2f128_ps256:
3920   case X86::BI__builtin_ia32_vperm2f128_si256:
3921   case X86::BI__builtin_ia32_permti256:
3922   case X86::BI__builtin_ia32_pblendw128:
3923   case X86::BI__builtin_ia32_pblendw256:
3924   case X86::BI__builtin_ia32_blendps256:
3925   case X86::BI__builtin_ia32_pblendd256:
3926   case X86::BI__builtin_ia32_palignr128:
3927   case X86::BI__builtin_ia32_palignr256:
3928   case X86::BI__builtin_ia32_palignr512:
3929   case X86::BI__builtin_ia32_alignq512:
3930   case X86::BI__builtin_ia32_alignd512:
3931   case X86::BI__builtin_ia32_alignd128:
3932   case X86::BI__builtin_ia32_alignd256:
3933   case X86::BI__builtin_ia32_alignq128:
3934   case X86::BI__builtin_ia32_alignq256:
3935   case X86::BI__builtin_ia32_vcomisd:
3936   case X86::BI__builtin_ia32_vcomiss:
3937   case X86::BI__builtin_ia32_shuf_f32x4:
3938   case X86::BI__builtin_ia32_shuf_f64x2:
3939   case X86::BI__builtin_ia32_shuf_i32x4:
3940   case X86::BI__builtin_ia32_shuf_i64x2:
3941   case X86::BI__builtin_ia32_shufpd512:
3942   case X86::BI__builtin_ia32_shufps:
3943   case X86::BI__builtin_ia32_shufps256:
3944   case X86::BI__builtin_ia32_shufps512:
3945   case X86::BI__builtin_ia32_dbpsadbw128:
3946   case X86::BI__builtin_ia32_dbpsadbw256:
3947   case X86::BI__builtin_ia32_dbpsadbw512:
3948   case X86::BI__builtin_ia32_vpshldd128:
3949   case X86::BI__builtin_ia32_vpshldd256:
3950   case X86::BI__builtin_ia32_vpshldd512:
3951   case X86::BI__builtin_ia32_vpshldq128:
3952   case X86::BI__builtin_ia32_vpshldq256:
3953   case X86::BI__builtin_ia32_vpshldq512:
3954   case X86::BI__builtin_ia32_vpshldw128:
3955   case X86::BI__builtin_ia32_vpshldw256:
3956   case X86::BI__builtin_ia32_vpshldw512:
3957   case X86::BI__builtin_ia32_vpshrdd128:
3958   case X86::BI__builtin_ia32_vpshrdd256:
3959   case X86::BI__builtin_ia32_vpshrdd512:
3960   case X86::BI__builtin_ia32_vpshrdq128:
3961   case X86::BI__builtin_ia32_vpshrdq256:
3962   case X86::BI__builtin_ia32_vpshrdq512:
3963   case X86::BI__builtin_ia32_vpshrdw128:
3964   case X86::BI__builtin_ia32_vpshrdw256:
3965   case X86::BI__builtin_ia32_vpshrdw512:
3966     i = 2; l = 0; u = 255;
3967     break;
3968   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3969   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3970   case X86::BI__builtin_ia32_fixupimmps512_mask:
3971   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3972   case X86::BI__builtin_ia32_fixupimmsd_mask:
3973   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3974   case X86::BI__builtin_ia32_fixupimmss_mask:
3975   case X86::BI__builtin_ia32_fixupimmss_maskz:
3976   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3977   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3978   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3979   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3980   case X86::BI__builtin_ia32_fixupimmps128_mask:
3981   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3982   case X86::BI__builtin_ia32_fixupimmps256_mask:
3983   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3984   case X86::BI__builtin_ia32_pternlogd512_mask:
3985   case X86::BI__builtin_ia32_pternlogd512_maskz:
3986   case X86::BI__builtin_ia32_pternlogq512_mask:
3987   case X86::BI__builtin_ia32_pternlogq512_maskz:
3988   case X86::BI__builtin_ia32_pternlogd128_mask:
3989   case X86::BI__builtin_ia32_pternlogd128_maskz:
3990   case X86::BI__builtin_ia32_pternlogd256_mask:
3991   case X86::BI__builtin_ia32_pternlogd256_maskz:
3992   case X86::BI__builtin_ia32_pternlogq128_mask:
3993   case X86::BI__builtin_ia32_pternlogq128_maskz:
3994   case X86::BI__builtin_ia32_pternlogq256_mask:
3995   case X86::BI__builtin_ia32_pternlogq256_maskz:
3996     i = 3; l = 0; u = 255;
3997     break;
3998   case X86::BI__builtin_ia32_gatherpfdpd:
3999   case X86::BI__builtin_ia32_gatherpfdps:
4000   case X86::BI__builtin_ia32_gatherpfqpd:
4001   case X86::BI__builtin_ia32_gatherpfqps:
4002   case X86::BI__builtin_ia32_scatterpfdpd:
4003   case X86::BI__builtin_ia32_scatterpfdps:
4004   case X86::BI__builtin_ia32_scatterpfqpd:
4005   case X86::BI__builtin_ia32_scatterpfqps:
4006     i = 4; l = 2; u = 3;
4007     break;
4008   case X86::BI__builtin_ia32_reducesd_mask:
4009   case X86::BI__builtin_ia32_reducess_mask:
4010   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4011   case X86::BI__builtin_ia32_rndscaless_round_mask:
4012     i = 4; l = 0; u = 255;
4013     break;
4014   }
4015 
4016   // Note that we don't force a hard error on the range check here, allowing
4017   // template-generated or macro-generated dead code to potentially have out-of-
4018   // range values. These need to code generate, but don't need to necessarily
4019   // make any sense. We use a warning that defaults to an error.
4020   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4021 }
4022 
4023 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4024 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4025 /// Returns true when the format fits the function and the FormatStringInfo has
4026 /// been populated.
4027 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4028                                FormatStringInfo *FSI) {
4029   FSI->HasVAListArg = Format->getFirstArg() == 0;
4030   FSI->FormatIdx = Format->getFormatIdx() - 1;
4031   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4032 
4033   // The way the format attribute works in GCC, the implicit this argument
4034   // of member functions is counted. However, it doesn't appear in our own
4035   // lists, so decrement format_idx in that case.
4036   if (IsCXXMember) {
4037     if(FSI->FormatIdx == 0)
4038       return false;
4039     --FSI->FormatIdx;
4040     if (FSI->FirstDataArg != 0)
4041       --FSI->FirstDataArg;
4042   }
4043   return true;
4044 }
4045 
4046 /// Checks if a the given expression evaluates to null.
4047 ///
4048 /// Returns true if the value evaluates to null.
4049 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4050   // If the expression has non-null type, it doesn't evaluate to null.
4051   if (auto nullability
4052         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4053     if (*nullability == NullabilityKind::NonNull)
4054       return false;
4055   }
4056 
4057   // As a special case, transparent unions initialized with zero are
4058   // considered null for the purposes of the nonnull attribute.
4059   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4060     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4061       if (const CompoundLiteralExpr *CLE =
4062           dyn_cast<CompoundLiteralExpr>(Expr))
4063         if (const InitListExpr *ILE =
4064             dyn_cast<InitListExpr>(CLE->getInitializer()))
4065           Expr = ILE->getInit(0);
4066   }
4067 
4068   bool Result;
4069   return (!Expr->isValueDependent() &&
4070           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4071           !Result);
4072 }
4073 
4074 static void CheckNonNullArgument(Sema &S,
4075                                  const Expr *ArgExpr,
4076                                  SourceLocation CallSiteLoc) {
4077   if (CheckNonNullExpr(S, ArgExpr))
4078     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4079                           S.PDiag(diag::warn_null_arg)
4080                               << ArgExpr->getSourceRange());
4081 }
4082 
4083 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4084   FormatStringInfo FSI;
4085   if ((GetFormatStringType(Format) == FST_NSString) &&
4086       getFormatStringInfo(Format, false, &FSI)) {
4087     Idx = FSI.FormatIdx;
4088     return true;
4089   }
4090   return false;
4091 }
4092 
4093 /// Diagnose use of %s directive in an NSString which is being passed
4094 /// as formatting string to formatting method.
4095 static void
4096 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4097                                         const NamedDecl *FDecl,
4098                                         Expr **Args,
4099                                         unsigned NumArgs) {
4100   unsigned Idx = 0;
4101   bool Format = false;
4102   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4103   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4104     Idx = 2;
4105     Format = true;
4106   }
4107   else
4108     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4109       if (S.GetFormatNSStringIdx(I, Idx)) {
4110         Format = true;
4111         break;
4112       }
4113     }
4114   if (!Format || NumArgs <= Idx)
4115     return;
4116   const Expr *FormatExpr = Args[Idx];
4117   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4118     FormatExpr = CSCE->getSubExpr();
4119   const StringLiteral *FormatString;
4120   if (const ObjCStringLiteral *OSL =
4121       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4122     FormatString = OSL->getString();
4123   else
4124     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4125   if (!FormatString)
4126     return;
4127   if (S.FormatStringHasSArg(FormatString)) {
4128     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4129       << "%s" << 1 << 1;
4130     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4131       << FDecl->getDeclName();
4132   }
4133 }
4134 
4135 /// Determine whether the given type has a non-null nullability annotation.
4136 static bool isNonNullType(ASTContext &ctx, QualType type) {
4137   if (auto nullability = type->getNullability(ctx))
4138     return *nullability == NullabilityKind::NonNull;
4139 
4140   return false;
4141 }
4142 
4143 static void CheckNonNullArguments(Sema &S,
4144                                   const NamedDecl *FDecl,
4145                                   const FunctionProtoType *Proto,
4146                                   ArrayRef<const Expr *> Args,
4147                                   SourceLocation CallSiteLoc) {
4148   assert((FDecl || Proto) && "Need a function declaration or prototype");
4149 
4150   // Already checked by by constant evaluator.
4151   if (S.isConstantEvaluated())
4152     return;
4153   // Check the attributes attached to the method/function itself.
4154   llvm::SmallBitVector NonNullArgs;
4155   if (FDecl) {
4156     // Handle the nonnull attribute on the function/method declaration itself.
4157     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4158       if (!NonNull->args_size()) {
4159         // Easy case: all pointer arguments are nonnull.
4160         for (const auto *Arg : Args)
4161           if (S.isValidPointerAttrType(Arg->getType()))
4162             CheckNonNullArgument(S, Arg, CallSiteLoc);
4163         return;
4164       }
4165 
4166       for (const ParamIdx &Idx : NonNull->args()) {
4167         unsigned IdxAST = Idx.getASTIndex();
4168         if (IdxAST >= Args.size())
4169           continue;
4170         if (NonNullArgs.empty())
4171           NonNullArgs.resize(Args.size());
4172         NonNullArgs.set(IdxAST);
4173       }
4174     }
4175   }
4176 
4177   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4178     // Handle the nonnull attribute on the parameters of the
4179     // function/method.
4180     ArrayRef<ParmVarDecl*> parms;
4181     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4182       parms = FD->parameters();
4183     else
4184       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4185 
4186     unsigned ParamIndex = 0;
4187     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4188          I != E; ++I, ++ParamIndex) {
4189       const ParmVarDecl *PVD = *I;
4190       if (PVD->hasAttr<NonNullAttr>() ||
4191           isNonNullType(S.Context, PVD->getType())) {
4192         if (NonNullArgs.empty())
4193           NonNullArgs.resize(Args.size());
4194 
4195         NonNullArgs.set(ParamIndex);
4196       }
4197     }
4198   } else {
4199     // If we have a non-function, non-method declaration but no
4200     // function prototype, try to dig out the function prototype.
4201     if (!Proto) {
4202       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4203         QualType type = VD->getType().getNonReferenceType();
4204         if (auto pointerType = type->getAs<PointerType>())
4205           type = pointerType->getPointeeType();
4206         else if (auto blockType = type->getAs<BlockPointerType>())
4207           type = blockType->getPointeeType();
4208         // FIXME: data member pointers?
4209 
4210         // Dig out the function prototype, if there is one.
4211         Proto = type->getAs<FunctionProtoType>();
4212       }
4213     }
4214 
4215     // Fill in non-null argument information from the nullability
4216     // information on the parameter types (if we have them).
4217     if (Proto) {
4218       unsigned Index = 0;
4219       for (auto paramType : Proto->getParamTypes()) {
4220         if (isNonNullType(S.Context, paramType)) {
4221           if (NonNullArgs.empty())
4222             NonNullArgs.resize(Args.size());
4223 
4224           NonNullArgs.set(Index);
4225         }
4226 
4227         ++Index;
4228       }
4229     }
4230   }
4231 
4232   // Check for non-null arguments.
4233   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4234        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4235     if (NonNullArgs[ArgIndex])
4236       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4237   }
4238 }
4239 
4240 /// Handles the checks for format strings, non-POD arguments to vararg
4241 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4242 /// attributes.
4243 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4244                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4245                      bool IsMemberFunction, SourceLocation Loc,
4246                      SourceRange Range, VariadicCallType CallType) {
4247   // FIXME: We should check as much as we can in the template definition.
4248   if (CurContext->isDependentContext())
4249     return;
4250 
4251   // Printf and scanf checking.
4252   llvm::SmallBitVector CheckedVarArgs;
4253   if (FDecl) {
4254     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4255       // Only create vector if there are format attributes.
4256       CheckedVarArgs.resize(Args.size());
4257 
4258       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4259                            CheckedVarArgs);
4260     }
4261   }
4262 
4263   // Refuse POD arguments that weren't caught by the format string
4264   // checks above.
4265   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4266   if (CallType != VariadicDoesNotApply &&
4267       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4268     unsigned NumParams = Proto ? Proto->getNumParams()
4269                        : FDecl && isa<FunctionDecl>(FDecl)
4270                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4271                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4272                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4273                        : 0;
4274 
4275     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4276       // Args[ArgIdx] can be null in malformed code.
4277       if (const Expr *Arg = Args[ArgIdx]) {
4278         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4279           checkVariadicArgument(Arg, CallType);
4280       }
4281     }
4282   }
4283 
4284   if (FDecl || Proto) {
4285     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4286 
4287     // Type safety checking.
4288     if (FDecl) {
4289       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4290         CheckArgumentWithTypeTag(I, Args, Loc);
4291     }
4292   }
4293 
4294   if (FD)
4295     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4296 }
4297 
4298 /// CheckConstructorCall - Check a constructor call for correctness and safety
4299 /// properties not enforced by the C type system.
4300 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4301                                 ArrayRef<const Expr *> Args,
4302                                 const FunctionProtoType *Proto,
4303                                 SourceLocation Loc) {
4304   VariadicCallType CallType =
4305     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4306   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4307             Loc, SourceRange(), CallType);
4308 }
4309 
4310 /// CheckFunctionCall - Check a direct function call for various correctness
4311 /// and safety properties not strictly enforced by the C type system.
4312 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4313                              const FunctionProtoType *Proto) {
4314   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4315                               isa<CXXMethodDecl>(FDecl);
4316   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4317                           IsMemberOperatorCall;
4318   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4319                                                   TheCall->getCallee());
4320   Expr** Args = TheCall->getArgs();
4321   unsigned NumArgs = TheCall->getNumArgs();
4322 
4323   Expr *ImplicitThis = nullptr;
4324   if (IsMemberOperatorCall) {
4325     // If this is a call to a member operator, hide the first argument
4326     // from checkCall.
4327     // FIXME: Our choice of AST representation here is less than ideal.
4328     ImplicitThis = Args[0];
4329     ++Args;
4330     --NumArgs;
4331   } else if (IsMemberFunction)
4332     ImplicitThis =
4333         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4334 
4335   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4336             IsMemberFunction, TheCall->getRParenLoc(),
4337             TheCall->getCallee()->getSourceRange(), CallType);
4338 
4339   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4340   // None of the checks below are needed for functions that don't have
4341   // simple names (e.g., C++ conversion functions).
4342   if (!FnInfo)
4343     return false;
4344 
4345   CheckAbsoluteValueFunction(TheCall, FDecl);
4346   CheckMaxUnsignedZero(TheCall, FDecl);
4347 
4348   if (getLangOpts().ObjC)
4349     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4350 
4351   unsigned CMId = FDecl->getMemoryFunctionKind();
4352   if (CMId == 0)
4353     return false;
4354 
4355   // Handle memory setting and copying functions.
4356   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4357     CheckStrlcpycatArguments(TheCall, FnInfo);
4358   else if (CMId == Builtin::BIstrncat)
4359     CheckStrncatArguments(TheCall, FnInfo);
4360   else
4361     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4362 
4363   return false;
4364 }
4365 
4366 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4367                                ArrayRef<const Expr *> Args) {
4368   VariadicCallType CallType =
4369       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4370 
4371   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4372             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4373             CallType);
4374 
4375   return false;
4376 }
4377 
4378 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4379                             const FunctionProtoType *Proto) {
4380   QualType Ty;
4381   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4382     Ty = V->getType().getNonReferenceType();
4383   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4384     Ty = F->getType().getNonReferenceType();
4385   else
4386     return false;
4387 
4388   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4389       !Ty->isFunctionProtoType())
4390     return false;
4391 
4392   VariadicCallType CallType;
4393   if (!Proto || !Proto->isVariadic()) {
4394     CallType = VariadicDoesNotApply;
4395   } else if (Ty->isBlockPointerType()) {
4396     CallType = VariadicBlock;
4397   } else { // Ty->isFunctionPointerType()
4398     CallType = VariadicFunction;
4399   }
4400 
4401   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4402             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4403             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4404             TheCall->getCallee()->getSourceRange(), CallType);
4405 
4406   return false;
4407 }
4408 
4409 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4410 /// such as function pointers returned from functions.
4411 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4412   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4413                                                   TheCall->getCallee());
4414   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4415             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4416             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4417             TheCall->getCallee()->getSourceRange(), CallType);
4418 
4419   return false;
4420 }
4421 
4422 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4423   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4424     return false;
4425 
4426   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4427   switch (Op) {
4428   case AtomicExpr::AO__c11_atomic_init:
4429   case AtomicExpr::AO__opencl_atomic_init:
4430     llvm_unreachable("There is no ordering argument for an init");
4431 
4432   case AtomicExpr::AO__c11_atomic_load:
4433   case AtomicExpr::AO__opencl_atomic_load:
4434   case AtomicExpr::AO__atomic_load_n:
4435   case AtomicExpr::AO__atomic_load:
4436     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4437            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4438 
4439   case AtomicExpr::AO__c11_atomic_store:
4440   case AtomicExpr::AO__opencl_atomic_store:
4441   case AtomicExpr::AO__atomic_store:
4442   case AtomicExpr::AO__atomic_store_n:
4443     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4444            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4445            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4446 
4447   default:
4448     return true;
4449   }
4450 }
4451 
4452 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4453                                          AtomicExpr::AtomicOp Op) {
4454   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4455   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4456 
4457   // All the non-OpenCL operations take one of the following forms.
4458   // The OpenCL operations take the __c11 forms with one extra argument for
4459   // synchronization scope.
4460   enum {
4461     // C    __c11_atomic_init(A *, C)
4462     Init,
4463 
4464     // C    __c11_atomic_load(A *, int)
4465     Load,
4466 
4467     // void __atomic_load(A *, CP, int)
4468     LoadCopy,
4469 
4470     // void __atomic_store(A *, CP, int)
4471     Copy,
4472 
4473     // C    __c11_atomic_add(A *, M, int)
4474     Arithmetic,
4475 
4476     // C    __atomic_exchange_n(A *, CP, int)
4477     Xchg,
4478 
4479     // void __atomic_exchange(A *, C *, CP, int)
4480     GNUXchg,
4481 
4482     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4483     C11CmpXchg,
4484 
4485     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4486     GNUCmpXchg
4487   } Form = Init;
4488 
4489   const unsigned NumForm = GNUCmpXchg + 1;
4490   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4491   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4492   // where:
4493   //   C is an appropriate type,
4494   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4495   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4496   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4497   //   the int parameters are for orderings.
4498 
4499   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4500       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4501       "need to update code for modified forms");
4502   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4503                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4504                         AtomicExpr::AO__atomic_load,
4505                 "need to update code for modified C11 atomics");
4506   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4507                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4508   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4509                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4510                IsOpenCL;
4511   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4512              Op == AtomicExpr::AO__atomic_store_n ||
4513              Op == AtomicExpr::AO__atomic_exchange_n ||
4514              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4515   bool IsAddSub = false;
4516   bool IsMinMax = false;
4517 
4518   switch (Op) {
4519   case AtomicExpr::AO__c11_atomic_init:
4520   case AtomicExpr::AO__opencl_atomic_init:
4521     Form = Init;
4522     break;
4523 
4524   case AtomicExpr::AO__c11_atomic_load:
4525   case AtomicExpr::AO__opencl_atomic_load:
4526   case AtomicExpr::AO__atomic_load_n:
4527     Form = Load;
4528     break;
4529 
4530   case AtomicExpr::AO__atomic_load:
4531     Form = LoadCopy;
4532     break;
4533 
4534   case AtomicExpr::AO__c11_atomic_store:
4535   case AtomicExpr::AO__opencl_atomic_store:
4536   case AtomicExpr::AO__atomic_store:
4537   case AtomicExpr::AO__atomic_store_n:
4538     Form = Copy;
4539     break;
4540 
4541   case AtomicExpr::AO__c11_atomic_fetch_add:
4542   case AtomicExpr::AO__c11_atomic_fetch_sub:
4543   case AtomicExpr::AO__opencl_atomic_fetch_add:
4544   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4545   case AtomicExpr::AO__opencl_atomic_fetch_min:
4546   case AtomicExpr::AO__opencl_atomic_fetch_max:
4547   case AtomicExpr::AO__atomic_fetch_add:
4548   case AtomicExpr::AO__atomic_fetch_sub:
4549   case AtomicExpr::AO__atomic_add_fetch:
4550   case AtomicExpr::AO__atomic_sub_fetch:
4551     IsAddSub = true;
4552     LLVM_FALLTHROUGH;
4553   case AtomicExpr::AO__c11_atomic_fetch_and:
4554   case AtomicExpr::AO__c11_atomic_fetch_or:
4555   case AtomicExpr::AO__c11_atomic_fetch_xor:
4556   case AtomicExpr::AO__opencl_atomic_fetch_and:
4557   case AtomicExpr::AO__opencl_atomic_fetch_or:
4558   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4559   case AtomicExpr::AO__atomic_fetch_and:
4560   case AtomicExpr::AO__atomic_fetch_or:
4561   case AtomicExpr::AO__atomic_fetch_xor:
4562   case AtomicExpr::AO__atomic_fetch_nand:
4563   case AtomicExpr::AO__atomic_and_fetch:
4564   case AtomicExpr::AO__atomic_or_fetch:
4565   case AtomicExpr::AO__atomic_xor_fetch:
4566   case AtomicExpr::AO__atomic_nand_fetch:
4567     Form = Arithmetic;
4568     break;
4569 
4570   case AtomicExpr::AO__atomic_fetch_min:
4571   case AtomicExpr::AO__atomic_fetch_max:
4572     IsMinMax = true;
4573     Form = Arithmetic;
4574     break;
4575 
4576   case AtomicExpr::AO__c11_atomic_exchange:
4577   case AtomicExpr::AO__opencl_atomic_exchange:
4578   case AtomicExpr::AO__atomic_exchange_n:
4579     Form = Xchg;
4580     break;
4581 
4582   case AtomicExpr::AO__atomic_exchange:
4583     Form = GNUXchg;
4584     break;
4585 
4586   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4587   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4588   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4589   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4590     Form = C11CmpXchg;
4591     break;
4592 
4593   case AtomicExpr::AO__atomic_compare_exchange:
4594   case AtomicExpr::AO__atomic_compare_exchange_n:
4595     Form = GNUCmpXchg;
4596     break;
4597   }
4598 
4599   unsigned AdjustedNumArgs = NumArgs[Form];
4600   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4601     ++AdjustedNumArgs;
4602   // Check we have the right number of arguments.
4603   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4604     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4605         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4606         << TheCall->getCallee()->getSourceRange();
4607     return ExprError();
4608   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4609     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4610          diag::err_typecheck_call_too_many_args)
4611         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4612         << TheCall->getCallee()->getSourceRange();
4613     return ExprError();
4614   }
4615 
4616   // Inspect the first argument of the atomic operation.
4617   Expr *Ptr = TheCall->getArg(0);
4618   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4619   if (ConvertedPtr.isInvalid())
4620     return ExprError();
4621 
4622   Ptr = ConvertedPtr.get();
4623   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4624   if (!pointerType) {
4625     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4626         << Ptr->getType() << Ptr->getSourceRange();
4627     return ExprError();
4628   }
4629 
4630   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4631   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4632   QualType ValType = AtomTy; // 'C'
4633   if (IsC11) {
4634     if (!AtomTy->isAtomicType()) {
4635       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4636           << Ptr->getType() << Ptr->getSourceRange();
4637       return ExprError();
4638     }
4639     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4640         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4641       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4642           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4643           << Ptr->getSourceRange();
4644       return ExprError();
4645     }
4646     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4647   } else if (Form != Load && Form != LoadCopy) {
4648     if (ValType.isConstQualified()) {
4649       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4650           << Ptr->getType() << Ptr->getSourceRange();
4651       return ExprError();
4652     }
4653   }
4654 
4655   // For an arithmetic operation, the implied arithmetic must be well-formed.
4656   if (Form == Arithmetic) {
4657     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4658     if (IsAddSub && !ValType->isIntegerType()
4659         && !ValType->isPointerType()) {
4660       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4661           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4662       return ExprError();
4663     }
4664     if (IsMinMax) {
4665       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4666       if (!BT || (BT->getKind() != BuiltinType::Int &&
4667                   BT->getKind() != BuiltinType::UInt)) {
4668         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4669         return ExprError();
4670       }
4671     }
4672     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4673       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4674           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4675       return ExprError();
4676     }
4677     if (IsC11 && ValType->isPointerType() &&
4678         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4679                             diag::err_incomplete_type)) {
4680       return ExprError();
4681     }
4682   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4683     // For __atomic_*_n operations, the value type must be a scalar integral or
4684     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4685     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4686         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4687     return ExprError();
4688   }
4689 
4690   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4691       !AtomTy->isScalarType()) {
4692     // For GNU atomics, require a trivially-copyable type. This is not part of
4693     // the GNU atomics specification, but we enforce it for sanity.
4694     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4695         << Ptr->getType() << Ptr->getSourceRange();
4696     return ExprError();
4697   }
4698 
4699   switch (ValType.getObjCLifetime()) {
4700   case Qualifiers::OCL_None:
4701   case Qualifiers::OCL_ExplicitNone:
4702     // okay
4703     break;
4704 
4705   case Qualifiers::OCL_Weak:
4706   case Qualifiers::OCL_Strong:
4707   case Qualifiers::OCL_Autoreleasing:
4708     // FIXME: Can this happen? By this point, ValType should be known
4709     // to be trivially copyable.
4710     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4711         << ValType << Ptr->getSourceRange();
4712     return ExprError();
4713   }
4714 
4715   // All atomic operations have an overload which takes a pointer to a volatile
4716   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4717   // into the result or the other operands. Similarly atomic_load takes a
4718   // pointer to a const 'A'.
4719   ValType.removeLocalVolatile();
4720   ValType.removeLocalConst();
4721   QualType ResultType = ValType;
4722   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4723       Form == Init)
4724     ResultType = Context.VoidTy;
4725   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4726     ResultType = Context.BoolTy;
4727 
4728   // The type of a parameter passed 'by value'. In the GNU atomics, such
4729   // arguments are actually passed as pointers.
4730   QualType ByValType = ValType; // 'CP'
4731   bool IsPassedByAddress = false;
4732   if (!IsC11 && !IsN) {
4733     ByValType = Ptr->getType();
4734     IsPassedByAddress = true;
4735   }
4736 
4737   // The first argument's non-CV pointer type is used to deduce the type of
4738   // subsequent arguments, except for:
4739   //  - weak flag (always converted to bool)
4740   //  - memory order (always converted to int)
4741   //  - scope  (always converted to int)
4742   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4743     QualType Ty;
4744     if (i < NumVals[Form] + 1) {
4745       switch (i) {
4746       case 0:
4747         // The first argument is always a pointer. It has a fixed type.
4748         // It is always dereferenced, a nullptr is undefined.
4749         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4750         // Nothing else to do: we already know all we want about this pointer.
4751         continue;
4752       case 1:
4753         // The second argument is the non-atomic operand. For arithmetic, this
4754         // is always passed by value, and for a compare_exchange it is always
4755         // passed by address. For the rest, GNU uses by-address and C11 uses
4756         // by-value.
4757         assert(Form != Load);
4758         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4759           Ty = ValType;
4760         else if (Form == Copy || Form == Xchg) {
4761           if (IsPassedByAddress)
4762             // The value pointer is always dereferenced, a nullptr is undefined.
4763             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4764           Ty = ByValType;
4765         } else if (Form == Arithmetic)
4766           Ty = Context.getPointerDiffType();
4767         else {
4768           Expr *ValArg = TheCall->getArg(i);
4769           // The value pointer is always dereferenced, a nullptr is undefined.
4770           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4771           LangAS AS = LangAS::Default;
4772           // Keep address space of non-atomic pointer type.
4773           if (const PointerType *PtrTy =
4774                   ValArg->getType()->getAs<PointerType>()) {
4775             AS = PtrTy->getPointeeType().getAddressSpace();
4776           }
4777           Ty = Context.getPointerType(
4778               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4779         }
4780         break;
4781       case 2:
4782         // The third argument to compare_exchange / GNU exchange is the desired
4783         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4784         if (IsPassedByAddress)
4785           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4786         Ty = ByValType;
4787         break;
4788       case 3:
4789         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4790         Ty = Context.BoolTy;
4791         break;
4792       }
4793     } else {
4794       // The order(s) and scope are always converted to int.
4795       Ty = Context.IntTy;
4796     }
4797 
4798     InitializedEntity Entity =
4799         InitializedEntity::InitializeParameter(Context, Ty, false);
4800     ExprResult Arg = TheCall->getArg(i);
4801     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4802     if (Arg.isInvalid())
4803       return true;
4804     TheCall->setArg(i, Arg.get());
4805   }
4806 
4807   // Permute the arguments into a 'consistent' order.
4808   SmallVector<Expr*, 5> SubExprs;
4809   SubExprs.push_back(Ptr);
4810   switch (Form) {
4811   case Init:
4812     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4813     SubExprs.push_back(TheCall->getArg(1)); // Val1
4814     break;
4815   case Load:
4816     SubExprs.push_back(TheCall->getArg(1)); // Order
4817     break;
4818   case LoadCopy:
4819   case Copy:
4820   case Arithmetic:
4821   case Xchg:
4822     SubExprs.push_back(TheCall->getArg(2)); // Order
4823     SubExprs.push_back(TheCall->getArg(1)); // Val1
4824     break;
4825   case GNUXchg:
4826     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4827     SubExprs.push_back(TheCall->getArg(3)); // Order
4828     SubExprs.push_back(TheCall->getArg(1)); // Val1
4829     SubExprs.push_back(TheCall->getArg(2)); // Val2
4830     break;
4831   case C11CmpXchg:
4832     SubExprs.push_back(TheCall->getArg(3)); // Order
4833     SubExprs.push_back(TheCall->getArg(1)); // Val1
4834     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4835     SubExprs.push_back(TheCall->getArg(2)); // Val2
4836     break;
4837   case GNUCmpXchg:
4838     SubExprs.push_back(TheCall->getArg(4)); // Order
4839     SubExprs.push_back(TheCall->getArg(1)); // Val1
4840     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4841     SubExprs.push_back(TheCall->getArg(2)); // Val2
4842     SubExprs.push_back(TheCall->getArg(3)); // Weak
4843     break;
4844   }
4845 
4846   if (SubExprs.size() >= 2 && Form != Init) {
4847     llvm::APSInt Result(32);
4848     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4849         !isValidOrderingForOp(Result.getSExtValue(), Op))
4850       Diag(SubExprs[1]->getBeginLoc(),
4851            diag::warn_atomic_op_has_invalid_memory_order)
4852           << SubExprs[1]->getSourceRange();
4853   }
4854 
4855   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4856     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4857     llvm::APSInt Result(32);
4858     if (Scope->isIntegerConstantExpr(Result, Context) &&
4859         !ScopeModel->isValid(Result.getZExtValue())) {
4860       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4861           << Scope->getSourceRange();
4862     }
4863     SubExprs.push_back(Scope);
4864   }
4865 
4866   AtomicExpr *AE =
4867       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4868                                ResultType, Op, TheCall->getRParenLoc());
4869 
4870   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4871        Op == AtomicExpr::AO__c11_atomic_store ||
4872        Op == AtomicExpr::AO__opencl_atomic_load ||
4873        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4874       Context.AtomicUsesUnsupportedLibcall(AE))
4875     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4876         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4877              Op == AtomicExpr::AO__opencl_atomic_load)
4878                 ? 0
4879                 : 1);
4880 
4881   return AE;
4882 }
4883 
4884 /// checkBuiltinArgument - Given a call to a builtin function, perform
4885 /// normal type-checking on the given argument, updating the call in
4886 /// place.  This is useful when a builtin function requires custom
4887 /// type-checking for some of its arguments but not necessarily all of
4888 /// them.
4889 ///
4890 /// Returns true on error.
4891 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4892   FunctionDecl *Fn = E->getDirectCallee();
4893   assert(Fn && "builtin call without direct callee!");
4894 
4895   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4896   InitializedEntity Entity =
4897     InitializedEntity::InitializeParameter(S.Context, Param);
4898 
4899   ExprResult Arg = E->getArg(0);
4900   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4901   if (Arg.isInvalid())
4902     return true;
4903 
4904   E->setArg(ArgIndex, Arg.get());
4905   return false;
4906 }
4907 
4908 /// We have a call to a function like __sync_fetch_and_add, which is an
4909 /// overloaded function based on the pointer type of its first argument.
4910 /// The main BuildCallExpr routines have already promoted the types of
4911 /// arguments because all of these calls are prototyped as void(...).
4912 ///
4913 /// This function goes through and does final semantic checking for these
4914 /// builtins, as well as generating any warnings.
4915 ExprResult
4916 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4917   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4918   Expr *Callee = TheCall->getCallee();
4919   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4920   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4921 
4922   // Ensure that we have at least one argument to do type inference from.
4923   if (TheCall->getNumArgs() < 1) {
4924     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4925         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4926     return ExprError();
4927   }
4928 
4929   // Inspect the first argument of the atomic builtin.  This should always be
4930   // a pointer type, whose element is an integral scalar or pointer type.
4931   // Because it is a pointer type, we don't have to worry about any implicit
4932   // casts here.
4933   // FIXME: We don't allow floating point scalars as input.
4934   Expr *FirstArg = TheCall->getArg(0);
4935   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4936   if (FirstArgResult.isInvalid())
4937     return ExprError();
4938   FirstArg = FirstArgResult.get();
4939   TheCall->setArg(0, FirstArg);
4940 
4941   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4942   if (!pointerType) {
4943     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4944         << FirstArg->getType() << FirstArg->getSourceRange();
4945     return ExprError();
4946   }
4947 
4948   QualType ValType = pointerType->getPointeeType();
4949   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4950       !ValType->isBlockPointerType()) {
4951     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4952         << FirstArg->getType() << FirstArg->getSourceRange();
4953     return ExprError();
4954   }
4955 
4956   if (ValType.isConstQualified()) {
4957     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4958         << FirstArg->getType() << FirstArg->getSourceRange();
4959     return ExprError();
4960   }
4961 
4962   switch (ValType.getObjCLifetime()) {
4963   case Qualifiers::OCL_None:
4964   case Qualifiers::OCL_ExplicitNone:
4965     // okay
4966     break;
4967 
4968   case Qualifiers::OCL_Weak:
4969   case Qualifiers::OCL_Strong:
4970   case Qualifiers::OCL_Autoreleasing:
4971     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4972         << ValType << FirstArg->getSourceRange();
4973     return ExprError();
4974   }
4975 
4976   // Strip any qualifiers off ValType.
4977   ValType = ValType.getUnqualifiedType();
4978 
4979   // The majority of builtins return a value, but a few have special return
4980   // types, so allow them to override appropriately below.
4981   QualType ResultType = ValType;
4982 
4983   // We need to figure out which concrete builtin this maps onto.  For example,
4984   // __sync_fetch_and_add with a 2 byte object turns into
4985   // __sync_fetch_and_add_2.
4986 #define BUILTIN_ROW(x) \
4987   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4988     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4989 
4990   static const unsigned BuiltinIndices[][5] = {
4991     BUILTIN_ROW(__sync_fetch_and_add),
4992     BUILTIN_ROW(__sync_fetch_and_sub),
4993     BUILTIN_ROW(__sync_fetch_and_or),
4994     BUILTIN_ROW(__sync_fetch_and_and),
4995     BUILTIN_ROW(__sync_fetch_and_xor),
4996     BUILTIN_ROW(__sync_fetch_and_nand),
4997 
4998     BUILTIN_ROW(__sync_add_and_fetch),
4999     BUILTIN_ROW(__sync_sub_and_fetch),
5000     BUILTIN_ROW(__sync_and_and_fetch),
5001     BUILTIN_ROW(__sync_or_and_fetch),
5002     BUILTIN_ROW(__sync_xor_and_fetch),
5003     BUILTIN_ROW(__sync_nand_and_fetch),
5004 
5005     BUILTIN_ROW(__sync_val_compare_and_swap),
5006     BUILTIN_ROW(__sync_bool_compare_and_swap),
5007     BUILTIN_ROW(__sync_lock_test_and_set),
5008     BUILTIN_ROW(__sync_lock_release),
5009     BUILTIN_ROW(__sync_swap)
5010   };
5011 #undef BUILTIN_ROW
5012 
5013   // Determine the index of the size.
5014   unsigned SizeIndex;
5015   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5016   case 1: SizeIndex = 0; break;
5017   case 2: SizeIndex = 1; break;
5018   case 4: SizeIndex = 2; break;
5019   case 8: SizeIndex = 3; break;
5020   case 16: SizeIndex = 4; break;
5021   default:
5022     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5023         << FirstArg->getType() << FirstArg->getSourceRange();
5024     return ExprError();
5025   }
5026 
5027   // Each of these builtins has one pointer argument, followed by some number of
5028   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5029   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5030   // as the number of fixed args.
5031   unsigned BuiltinID = FDecl->getBuiltinID();
5032   unsigned BuiltinIndex, NumFixed = 1;
5033   bool WarnAboutSemanticsChange = false;
5034   switch (BuiltinID) {
5035   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5036   case Builtin::BI__sync_fetch_and_add:
5037   case Builtin::BI__sync_fetch_and_add_1:
5038   case Builtin::BI__sync_fetch_and_add_2:
5039   case Builtin::BI__sync_fetch_and_add_4:
5040   case Builtin::BI__sync_fetch_and_add_8:
5041   case Builtin::BI__sync_fetch_and_add_16:
5042     BuiltinIndex = 0;
5043     break;
5044 
5045   case Builtin::BI__sync_fetch_and_sub:
5046   case Builtin::BI__sync_fetch_and_sub_1:
5047   case Builtin::BI__sync_fetch_and_sub_2:
5048   case Builtin::BI__sync_fetch_and_sub_4:
5049   case Builtin::BI__sync_fetch_and_sub_8:
5050   case Builtin::BI__sync_fetch_and_sub_16:
5051     BuiltinIndex = 1;
5052     break;
5053 
5054   case Builtin::BI__sync_fetch_and_or:
5055   case Builtin::BI__sync_fetch_and_or_1:
5056   case Builtin::BI__sync_fetch_and_or_2:
5057   case Builtin::BI__sync_fetch_and_or_4:
5058   case Builtin::BI__sync_fetch_and_or_8:
5059   case Builtin::BI__sync_fetch_and_or_16:
5060     BuiltinIndex = 2;
5061     break;
5062 
5063   case Builtin::BI__sync_fetch_and_and:
5064   case Builtin::BI__sync_fetch_and_and_1:
5065   case Builtin::BI__sync_fetch_and_and_2:
5066   case Builtin::BI__sync_fetch_and_and_4:
5067   case Builtin::BI__sync_fetch_and_and_8:
5068   case Builtin::BI__sync_fetch_and_and_16:
5069     BuiltinIndex = 3;
5070     break;
5071 
5072   case Builtin::BI__sync_fetch_and_xor:
5073   case Builtin::BI__sync_fetch_and_xor_1:
5074   case Builtin::BI__sync_fetch_and_xor_2:
5075   case Builtin::BI__sync_fetch_and_xor_4:
5076   case Builtin::BI__sync_fetch_and_xor_8:
5077   case Builtin::BI__sync_fetch_and_xor_16:
5078     BuiltinIndex = 4;
5079     break;
5080 
5081   case Builtin::BI__sync_fetch_and_nand:
5082   case Builtin::BI__sync_fetch_and_nand_1:
5083   case Builtin::BI__sync_fetch_and_nand_2:
5084   case Builtin::BI__sync_fetch_and_nand_4:
5085   case Builtin::BI__sync_fetch_and_nand_8:
5086   case Builtin::BI__sync_fetch_and_nand_16:
5087     BuiltinIndex = 5;
5088     WarnAboutSemanticsChange = true;
5089     break;
5090 
5091   case Builtin::BI__sync_add_and_fetch:
5092   case Builtin::BI__sync_add_and_fetch_1:
5093   case Builtin::BI__sync_add_and_fetch_2:
5094   case Builtin::BI__sync_add_and_fetch_4:
5095   case Builtin::BI__sync_add_and_fetch_8:
5096   case Builtin::BI__sync_add_and_fetch_16:
5097     BuiltinIndex = 6;
5098     break;
5099 
5100   case Builtin::BI__sync_sub_and_fetch:
5101   case Builtin::BI__sync_sub_and_fetch_1:
5102   case Builtin::BI__sync_sub_and_fetch_2:
5103   case Builtin::BI__sync_sub_and_fetch_4:
5104   case Builtin::BI__sync_sub_and_fetch_8:
5105   case Builtin::BI__sync_sub_and_fetch_16:
5106     BuiltinIndex = 7;
5107     break;
5108 
5109   case Builtin::BI__sync_and_and_fetch:
5110   case Builtin::BI__sync_and_and_fetch_1:
5111   case Builtin::BI__sync_and_and_fetch_2:
5112   case Builtin::BI__sync_and_and_fetch_4:
5113   case Builtin::BI__sync_and_and_fetch_8:
5114   case Builtin::BI__sync_and_and_fetch_16:
5115     BuiltinIndex = 8;
5116     break;
5117 
5118   case Builtin::BI__sync_or_and_fetch:
5119   case Builtin::BI__sync_or_and_fetch_1:
5120   case Builtin::BI__sync_or_and_fetch_2:
5121   case Builtin::BI__sync_or_and_fetch_4:
5122   case Builtin::BI__sync_or_and_fetch_8:
5123   case Builtin::BI__sync_or_and_fetch_16:
5124     BuiltinIndex = 9;
5125     break;
5126 
5127   case Builtin::BI__sync_xor_and_fetch:
5128   case Builtin::BI__sync_xor_and_fetch_1:
5129   case Builtin::BI__sync_xor_and_fetch_2:
5130   case Builtin::BI__sync_xor_and_fetch_4:
5131   case Builtin::BI__sync_xor_and_fetch_8:
5132   case Builtin::BI__sync_xor_and_fetch_16:
5133     BuiltinIndex = 10;
5134     break;
5135 
5136   case Builtin::BI__sync_nand_and_fetch:
5137   case Builtin::BI__sync_nand_and_fetch_1:
5138   case Builtin::BI__sync_nand_and_fetch_2:
5139   case Builtin::BI__sync_nand_and_fetch_4:
5140   case Builtin::BI__sync_nand_and_fetch_8:
5141   case Builtin::BI__sync_nand_and_fetch_16:
5142     BuiltinIndex = 11;
5143     WarnAboutSemanticsChange = true;
5144     break;
5145 
5146   case Builtin::BI__sync_val_compare_and_swap:
5147   case Builtin::BI__sync_val_compare_and_swap_1:
5148   case Builtin::BI__sync_val_compare_and_swap_2:
5149   case Builtin::BI__sync_val_compare_and_swap_4:
5150   case Builtin::BI__sync_val_compare_and_swap_8:
5151   case Builtin::BI__sync_val_compare_and_swap_16:
5152     BuiltinIndex = 12;
5153     NumFixed = 2;
5154     break;
5155 
5156   case Builtin::BI__sync_bool_compare_and_swap:
5157   case Builtin::BI__sync_bool_compare_and_swap_1:
5158   case Builtin::BI__sync_bool_compare_and_swap_2:
5159   case Builtin::BI__sync_bool_compare_and_swap_4:
5160   case Builtin::BI__sync_bool_compare_and_swap_8:
5161   case Builtin::BI__sync_bool_compare_and_swap_16:
5162     BuiltinIndex = 13;
5163     NumFixed = 2;
5164     ResultType = Context.BoolTy;
5165     break;
5166 
5167   case Builtin::BI__sync_lock_test_and_set:
5168   case Builtin::BI__sync_lock_test_and_set_1:
5169   case Builtin::BI__sync_lock_test_and_set_2:
5170   case Builtin::BI__sync_lock_test_and_set_4:
5171   case Builtin::BI__sync_lock_test_and_set_8:
5172   case Builtin::BI__sync_lock_test_and_set_16:
5173     BuiltinIndex = 14;
5174     break;
5175 
5176   case Builtin::BI__sync_lock_release:
5177   case Builtin::BI__sync_lock_release_1:
5178   case Builtin::BI__sync_lock_release_2:
5179   case Builtin::BI__sync_lock_release_4:
5180   case Builtin::BI__sync_lock_release_8:
5181   case Builtin::BI__sync_lock_release_16:
5182     BuiltinIndex = 15;
5183     NumFixed = 0;
5184     ResultType = Context.VoidTy;
5185     break;
5186 
5187   case Builtin::BI__sync_swap:
5188   case Builtin::BI__sync_swap_1:
5189   case Builtin::BI__sync_swap_2:
5190   case Builtin::BI__sync_swap_4:
5191   case Builtin::BI__sync_swap_8:
5192   case Builtin::BI__sync_swap_16:
5193     BuiltinIndex = 16;
5194     break;
5195   }
5196 
5197   // Now that we know how many fixed arguments we expect, first check that we
5198   // have at least that many.
5199   if (TheCall->getNumArgs() < 1+NumFixed) {
5200     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5201         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5202         << Callee->getSourceRange();
5203     return ExprError();
5204   }
5205 
5206   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5207       << Callee->getSourceRange();
5208 
5209   if (WarnAboutSemanticsChange) {
5210     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5211         << Callee->getSourceRange();
5212   }
5213 
5214   // Get the decl for the concrete builtin from this, we can tell what the
5215   // concrete integer type we should convert to is.
5216   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5217   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5218   FunctionDecl *NewBuiltinDecl;
5219   if (NewBuiltinID == BuiltinID)
5220     NewBuiltinDecl = FDecl;
5221   else {
5222     // Perform builtin lookup to avoid redeclaring it.
5223     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5224     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5225     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5226     assert(Res.getFoundDecl());
5227     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5228     if (!NewBuiltinDecl)
5229       return ExprError();
5230   }
5231 
5232   // The first argument --- the pointer --- has a fixed type; we
5233   // deduce the types of the rest of the arguments accordingly.  Walk
5234   // the remaining arguments, converting them to the deduced value type.
5235   for (unsigned i = 0; i != NumFixed; ++i) {
5236     ExprResult Arg = TheCall->getArg(i+1);
5237 
5238     // GCC does an implicit conversion to the pointer or integer ValType.  This
5239     // can fail in some cases (1i -> int**), check for this error case now.
5240     // Initialize the argument.
5241     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5242                                                    ValType, /*consume*/ false);
5243     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5244     if (Arg.isInvalid())
5245       return ExprError();
5246 
5247     // Okay, we have something that *can* be converted to the right type.  Check
5248     // to see if there is a potentially weird extension going on here.  This can
5249     // happen when you do an atomic operation on something like an char* and
5250     // pass in 42.  The 42 gets converted to char.  This is even more strange
5251     // for things like 45.123 -> char, etc.
5252     // FIXME: Do this check.
5253     TheCall->setArg(i+1, Arg.get());
5254   }
5255 
5256   // Create a new DeclRefExpr to refer to the new decl.
5257   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5258       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5259       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5260       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5261 
5262   // Set the callee in the CallExpr.
5263   // FIXME: This loses syntactic information.
5264   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5265   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5266                                               CK_BuiltinFnToFnPtr);
5267   TheCall->setCallee(PromotedCall.get());
5268 
5269   // Change the result type of the call to match the original value type. This
5270   // is arbitrary, but the codegen for these builtins ins design to handle it
5271   // gracefully.
5272   TheCall->setType(ResultType);
5273 
5274   return TheCallResult;
5275 }
5276 
5277 /// SemaBuiltinNontemporalOverloaded - We have a call to
5278 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5279 /// overloaded function based on the pointer type of its last argument.
5280 ///
5281 /// This function goes through and does final semantic checking for these
5282 /// builtins.
5283 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5284   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5285   DeclRefExpr *DRE =
5286       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5287   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5288   unsigned BuiltinID = FDecl->getBuiltinID();
5289   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5290           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5291          "Unexpected nontemporal load/store builtin!");
5292   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5293   unsigned numArgs = isStore ? 2 : 1;
5294 
5295   // Ensure that we have the proper number of arguments.
5296   if (checkArgCount(*this, TheCall, numArgs))
5297     return ExprError();
5298 
5299   // Inspect the last argument of the nontemporal builtin.  This should always
5300   // be a pointer type, from which we imply the type of the memory access.
5301   // Because it is a pointer type, we don't have to worry about any implicit
5302   // casts here.
5303   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5304   ExprResult PointerArgResult =
5305       DefaultFunctionArrayLvalueConversion(PointerArg);
5306 
5307   if (PointerArgResult.isInvalid())
5308     return ExprError();
5309   PointerArg = PointerArgResult.get();
5310   TheCall->setArg(numArgs - 1, PointerArg);
5311 
5312   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5313   if (!pointerType) {
5314     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5315         << PointerArg->getType() << PointerArg->getSourceRange();
5316     return ExprError();
5317   }
5318 
5319   QualType ValType = pointerType->getPointeeType();
5320 
5321   // Strip any qualifiers off ValType.
5322   ValType = ValType.getUnqualifiedType();
5323   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5324       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5325       !ValType->isVectorType()) {
5326     Diag(DRE->getBeginLoc(),
5327          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5328         << PointerArg->getType() << PointerArg->getSourceRange();
5329     return ExprError();
5330   }
5331 
5332   if (!isStore) {
5333     TheCall->setType(ValType);
5334     return TheCallResult;
5335   }
5336 
5337   ExprResult ValArg = TheCall->getArg(0);
5338   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5339       Context, ValType, /*consume*/ false);
5340   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5341   if (ValArg.isInvalid())
5342     return ExprError();
5343 
5344   TheCall->setArg(0, ValArg.get());
5345   TheCall->setType(Context.VoidTy);
5346   return TheCallResult;
5347 }
5348 
5349 /// CheckObjCString - Checks that the argument to the builtin
5350 /// CFString constructor is correct
5351 /// Note: It might also make sense to do the UTF-16 conversion here (would
5352 /// simplify the backend).
5353 bool Sema::CheckObjCString(Expr *Arg) {
5354   Arg = Arg->IgnoreParenCasts();
5355   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5356 
5357   if (!Literal || !Literal->isAscii()) {
5358     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5359         << Arg->getSourceRange();
5360     return true;
5361   }
5362 
5363   if (Literal->containsNonAsciiOrNull()) {
5364     StringRef String = Literal->getString();
5365     unsigned NumBytes = String.size();
5366     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5367     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5368     llvm::UTF16 *ToPtr = &ToBuf[0];
5369 
5370     llvm::ConversionResult Result =
5371         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5372                                  ToPtr + NumBytes, llvm::strictConversion);
5373     // Check for conversion failure.
5374     if (Result != llvm::conversionOK)
5375       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5376           << Arg->getSourceRange();
5377   }
5378   return false;
5379 }
5380 
5381 /// CheckObjCString - Checks that the format string argument to the os_log()
5382 /// and os_trace() functions is correct, and converts it to const char *.
5383 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5384   Arg = Arg->IgnoreParenCasts();
5385   auto *Literal = dyn_cast<StringLiteral>(Arg);
5386   if (!Literal) {
5387     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5388       Literal = ObjcLiteral->getString();
5389     }
5390   }
5391 
5392   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5393     return ExprError(
5394         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5395         << Arg->getSourceRange());
5396   }
5397 
5398   ExprResult Result(Literal);
5399   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5400   InitializedEntity Entity =
5401       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5402   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5403   return Result;
5404 }
5405 
5406 /// Check that the user is calling the appropriate va_start builtin for the
5407 /// target and calling convention.
5408 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5409   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5410   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5411   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5412   bool IsWindows = TT.isOSWindows();
5413   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5414   if (IsX64 || IsAArch64) {
5415     CallingConv CC = CC_C;
5416     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5417       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5418     if (IsMSVAStart) {
5419       // Don't allow this in System V ABI functions.
5420       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5421         return S.Diag(Fn->getBeginLoc(),
5422                       diag::err_ms_va_start_used_in_sysv_function);
5423     } else {
5424       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5425       // On x64 Windows, don't allow this in System V ABI functions.
5426       // (Yes, that means there's no corresponding way to support variadic
5427       // System V ABI functions on Windows.)
5428       if ((IsWindows && CC == CC_X86_64SysV) ||
5429           (!IsWindows && CC == CC_Win64))
5430         return S.Diag(Fn->getBeginLoc(),
5431                       diag::err_va_start_used_in_wrong_abi_function)
5432                << !IsWindows;
5433     }
5434     return false;
5435   }
5436 
5437   if (IsMSVAStart)
5438     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5439   return false;
5440 }
5441 
5442 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5443                                              ParmVarDecl **LastParam = nullptr) {
5444   // Determine whether the current function, block, or obj-c method is variadic
5445   // and get its parameter list.
5446   bool IsVariadic = false;
5447   ArrayRef<ParmVarDecl *> Params;
5448   DeclContext *Caller = S.CurContext;
5449   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5450     IsVariadic = Block->isVariadic();
5451     Params = Block->parameters();
5452   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5453     IsVariadic = FD->isVariadic();
5454     Params = FD->parameters();
5455   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5456     IsVariadic = MD->isVariadic();
5457     // FIXME: This isn't correct for methods (results in bogus warning).
5458     Params = MD->parameters();
5459   } else if (isa<CapturedDecl>(Caller)) {
5460     // We don't support va_start in a CapturedDecl.
5461     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5462     return true;
5463   } else {
5464     // This must be some other declcontext that parses exprs.
5465     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5466     return true;
5467   }
5468 
5469   if (!IsVariadic) {
5470     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5471     return true;
5472   }
5473 
5474   if (LastParam)
5475     *LastParam = Params.empty() ? nullptr : Params.back();
5476 
5477   return false;
5478 }
5479 
5480 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5481 /// for validity.  Emit an error and return true on failure; return false
5482 /// on success.
5483 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5484   Expr *Fn = TheCall->getCallee();
5485 
5486   if (checkVAStartABI(*this, BuiltinID, Fn))
5487     return true;
5488 
5489   if (TheCall->getNumArgs() > 2) {
5490     Diag(TheCall->getArg(2)->getBeginLoc(),
5491          diag::err_typecheck_call_too_many_args)
5492         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5493         << Fn->getSourceRange()
5494         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5495                        (*(TheCall->arg_end() - 1))->getEndLoc());
5496     return true;
5497   }
5498 
5499   if (TheCall->getNumArgs() < 2) {
5500     return Diag(TheCall->getEndLoc(),
5501                 diag::err_typecheck_call_too_few_args_at_least)
5502            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5503   }
5504 
5505   // Type-check the first argument normally.
5506   if (checkBuiltinArgument(*this, TheCall, 0))
5507     return true;
5508 
5509   // Check that the current function is variadic, and get its last parameter.
5510   ParmVarDecl *LastParam;
5511   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5512     return true;
5513 
5514   // Verify that the second argument to the builtin is the last argument of the
5515   // current function or method.
5516   bool SecondArgIsLastNamedArgument = false;
5517   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5518 
5519   // These are valid if SecondArgIsLastNamedArgument is false after the next
5520   // block.
5521   QualType Type;
5522   SourceLocation ParamLoc;
5523   bool IsCRegister = false;
5524 
5525   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5526     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5527       SecondArgIsLastNamedArgument = PV == LastParam;
5528 
5529       Type = PV->getType();
5530       ParamLoc = PV->getLocation();
5531       IsCRegister =
5532           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5533     }
5534   }
5535 
5536   if (!SecondArgIsLastNamedArgument)
5537     Diag(TheCall->getArg(1)->getBeginLoc(),
5538          diag::warn_second_arg_of_va_start_not_last_named_param);
5539   else if (IsCRegister || Type->isReferenceType() ||
5540            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5541              // Promotable integers are UB, but enumerations need a bit of
5542              // extra checking to see what their promotable type actually is.
5543              if (!Type->isPromotableIntegerType())
5544                return false;
5545              if (!Type->isEnumeralType())
5546                return true;
5547              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5548              return !(ED &&
5549                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5550            }()) {
5551     unsigned Reason = 0;
5552     if (Type->isReferenceType())  Reason = 1;
5553     else if (IsCRegister)         Reason = 2;
5554     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5555     Diag(ParamLoc, diag::note_parameter_type) << Type;
5556   }
5557 
5558   TheCall->setType(Context.VoidTy);
5559   return false;
5560 }
5561 
5562 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5563   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5564   //                 const char *named_addr);
5565 
5566   Expr *Func = Call->getCallee();
5567 
5568   if (Call->getNumArgs() < 3)
5569     return Diag(Call->getEndLoc(),
5570                 diag::err_typecheck_call_too_few_args_at_least)
5571            << 0 /*function call*/ << 3 << Call->getNumArgs();
5572 
5573   // Type-check the first argument normally.
5574   if (checkBuiltinArgument(*this, Call, 0))
5575     return true;
5576 
5577   // Check that the current function is variadic.
5578   if (checkVAStartIsInVariadicFunction(*this, Func))
5579     return true;
5580 
5581   // __va_start on Windows does not validate the parameter qualifiers
5582 
5583   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5584   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5585 
5586   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5587   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5588 
5589   const QualType &ConstCharPtrTy =
5590       Context.getPointerType(Context.CharTy.withConst());
5591   if (!Arg1Ty->isPointerType() ||
5592       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5593     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5594         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5595         << 0                                      /* qualifier difference */
5596         << 3                                      /* parameter mismatch */
5597         << 2 << Arg1->getType() << ConstCharPtrTy;
5598 
5599   const QualType SizeTy = Context.getSizeType();
5600   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5601     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5602         << Arg2->getType() << SizeTy << 1 /* different class */
5603         << 0                              /* qualifier difference */
5604         << 3                              /* parameter mismatch */
5605         << 3 << Arg2->getType() << SizeTy;
5606 
5607   return false;
5608 }
5609 
5610 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5611 /// friends.  This is declared to take (...), so we have to check everything.
5612 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5613   if (TheCall->getNumArgs() < 2)
5614     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5615            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5616   if (TheCall->getNumArgs() > 2)
5617     return Diag(TheCall->getArg(2)->getBeginLoc(),
5618                 diag::err_typecheck_call_too_many_args)
5619            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5620            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5621                           (*(TheCall->arg_end() - 1))->getEndLoc());
5622 
5623   ExprResult OrigArg0 = TheCall->getArg(0);
5624   ExprResult OrigArg1 = TheCall->getArg(1);
5625 
5626   // Do standard promotions between the two arguments, returning their common
5627   // type.
5628   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5629   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5630     return true;
5631 
5632   // Make sure any conversions are pushed back into the call; this is
5633   // type safe since unordered compare builtins are declared as "_Bool
5634   // foo(...)".
5635   TheCall->setArg(0, OrigArg0.get());
5636   TheCall->setArg(1, OrigArg1.get());
5637 
5638   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5639     return false;
5640 
5641   // If the common type isn't a real floating type, then the arguments were
5642   // invalid for this operation.
5643   if (Res.isNull() || !Res->isRealFloatingType())
5644     return Diag(OrigArg0.get()->getBeginLoc(),
5645                 diag::err_typecheck_call_invalid_ordered_compare)
5646            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5647            << SourceRange(OrigArg0.get()->getBeginLoc(),
5648                           OrigArg1.get()->getEndLoc());
5649 
5650   return false;
5651 }
5652 
5653 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5654 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5655 /// to check everything. We expect the last argument to be a floating point
5656 /// value.
5657 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5658   if (TheCall->getNumArgs() < NumArgs)
5659     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5660            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5661   if (TheCall->getNumArgs() > NumArgs)
5662     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5663                 diag::err_typecheck_call_too_many_args)
5664            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5665            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5666                           (*(TheCall->arg_end() - 1))->getEndLoc());
5667 
5668   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5669 
5670   if (OrigArg->isTypeDependent())
5671     return false;
5672 
5673   // This operation requires a non-_Complex floating-point number.
5674   if (!OrigArg->getType()->isRealFloatingType())
5675     return Diag(OrigArg->getBeginLoc(),
5676                 diag::err_typecheck_call_invalid_unary_fp)
5677            << OrigArg->getType() << OrigArg->getSourceRange();
5678 
5679   // If this is an implicit conversion from float -> float, double, or
5680   // long double, remove it.
5681   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5682     // Only remove standard FloatCasts, leaving other casts inplace
5683     if (Cast->getCastKind() == CK_FloatingCast) {
5684       Expr *CastArg = Cast->getSubExpr();
5685       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5686         assert(
5687             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5688              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5689              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5690             "promotion from float to either float, double, or long double is "
5691             "the only expected cast here");
5692         Cast->setSubExpr(nullptr);
5693         TheCall->setArg(NumArgs-1, CastArg);
5694       }
5695     }
5696   }
5697 
5698   return false;
5699 }
5700 
5701 // Customized Sema Checking for VSX builtins that have the following signature:
5702 // vector [...] builtinName(vector [...], vector [...], const int);
5703 // Which takes the same type of vectors (any legal vector type) for the first
5704 // two arguments and takes compile time constant for the third argument.
5705 // Example builtins are :
5706 // vector double vec_xxpermdi(vector double, vector double, int);
5707 // vector short vec_xxsldwi(vector short, vector short, int);
5708 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5709   unsigned ExpectedNumArgs = 3;
5710   if (TheCall->getNumArgs() < ExpectedNumArgs)
5711     return Diag(TheCall->getEndLoc(),
5712                 diag::err_typecheck_call_too_few_args_at_least)
5713            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5714            << TheCall->getSourceRange();
5715 
5716   if (TheCall->getNumArgs() > ExpectedNumArgs)
5717     return Diag(TheCall->getEndLoc(),
5718                 diag::err_typecheck_call_too_many_args_at_most)
5719            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5720            << TheCall->getSourceRange();
5721 
5722   // Check the third argument is a compile time constant
5723   llvm::APSInt Value;
5724   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5725     return Diag(TheCall->getBeginLoc(),
5726                 diag::err_vsx_builtin_nonconstant_argument)
5727            << 3 /* argument index */ << TheCall->getDirectCallee()
5728            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5729                           TheCall->getArg(2)->getEndLoc());
5730 
5731   QualType Arg1Ty = TheCall->getArg(0)->getType();
5732   QualType Arg2Ty = TheCall->getArg(1)->getType();
5733 
5734   // Check the type of argument 1 and argument 2 are vectors.
5735   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5736   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5737       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5738     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5739            << TheCall->getDirectCallee()
5740            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5741                           TheCall->getArg(1)->getEndLoc());
5742   }
5743 
5744   // Check the first two arguments are the same type.
5745   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5746     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5747            << TheCall->getDirectCallee()
5748            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5749                           TheCall->getArg(1)->getEndLoc());
5750   }
5751 
5752   // When default clang type checking is turned off and the customized type
5753   // checking is used, the returning type of the function must be explicitly
5754   // set. Otherwise it is _Bool by default.
5755   TheCall->setType(Arg1Ty);
5756 
5757   return false;
5758 }
5759 
5760 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5761 // This is declared to take (...), so we have to check everything.
5762 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5763   if (TheCall->getNumArgs() < 2)
5764     return ExprError(Diag(TheCall->getEndLoc(),
5765                           diag::err_typecheck_call_too_few_args_at_least)
5766                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5767                      << TheCall->getSourceRange());
5768 
5769   // Determine which of the following types of shufflevector we're checking:
5770   // 1) unary, vector mask: (lhs, mask)
5771   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5772   QualType resType = TheCall->getArg(0)->getType();
5773   unsigned numElements = 0;
5774 
5775   if (!TheCall->getArg(0)->isTypeDependent() &&
5776       !TheCall->getArg(1)->isTypeDependent()) {
5777     QualType LHSType = TheCall->getArg(0)->getType();
5778     QualType RHSType = TheCall->getArg(1)->getType();
5779 
5780     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5781       return ExprError(
5782           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5783           << TheCall->getDirectCallee()
5784           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5785                          TheCall->getArg(1)->getEndLoc()));
5786 
5787     numElements = LHSType->getAs<VectorType>()->getNumElements();
5788     unsigned numResElements = TheCall->getNumArgs() - 2;
5789 
5790     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5791     // with mask.  If so, verify that RHS is an integer vector type with the
5792     // same number of elts as lhs.
5793     if (TheCall->getNumArgs() == 2) {
5794       if (!RHSType->hasIntegerRepresentation() ||
5795           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5796         return ExprError(Diag(TheCall->getBeginLoc(),
5797                               diag::err_vec_builtin_incompatible_vector)
5798                          << TheCall->getDirectCallee()
5799                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5800                                         TheCall->getArg(1)->getEndLoc()));
5801     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5802       return ExprError(Diag(TheCall->getBeginLoc(),
5803                             diag::err_vec_builtin_incompatible_vector)
5804                        << TheCall->getDirectCallee()
5805                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5806                                       TheCall->getArg(1)->getEndLoc()));
5807     } else if (numElements != numResElements) {
5808       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5809       resType = Context.getVectorType(eltType, numResElements,
5810                                       VectorType::GenericVector);
5811     }
5812   }
5813 
5814   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5815     if (TheCall->getArg(i)->isTypeDependent() ||
5816         TheCall->getArg(i)->isValueDependent())
5817       continue;
5818 
5819     llvm::APSInt Result(32);
5820     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5821       return ExprError(Diag(TheCall->getBeginLoc(),
5822                             diag::err_shufflevector_nonconstant_argument)
5823                        << TheCall->getArg(i)->getSourceRange());
5824 
5825     // Allow -1 which will be translated to undef in the IR.
5826     if (Result.isSigned() && Result.isAllOnesValue())
5827       continue;
5828 
5829     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5830       return ExprError(Diag(TheCall->getBeginLoc(),
5831                             diag::err_shufflevector_argument_too_large)
5832                        << TheCall->getArg(i)->getSourceRange());
5833   }
5834 
5835   SmallVector<Expr*, 32> exprs;
5836 
5837   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5838     exprs.push_back(TheCall->getArg(i));
5839     TheCall->setArg(i, nullptr);
5840   }
5841 
5842   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5843                                          TheCall->getCallee()->getBeginLoc(),
5844                                          TheCall->getRParenLoc());
5845 }
5846 
5847 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5848 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5849                                        SourceLocation BuiltinLoc,
5850                                        SourceLocation RParenLoc) {
5851   ExprValueKind VK = VK_RValue;
5852   ExprObjectKind OK = OK_Ordinary;
5853   QualType DstTy = TInfo->getType();
5854   QualType SrcTy = E->getType();
5855 
5856   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5857     return ExprError(Diag(BuiltinLoc,
5858                           diag::err_convertvector_non_vector)
5859                      << E->getSourceRange());
5860   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5861     return ExprError(Diag(BuiltinLoc,
5862                           diag::err_convertvector_non_vector_type));
5863 
5864   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5865     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5866     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5867     if (SrcElts != DstElts)
5868       return ExprError(Diag(BuiltinLoc,
5869                             diag::err_convertvector_incompatible_vector)
5870                        << E->getSourceRange());
5871   }
5872 
5873   return new (Context)
5874       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5875 }
5876 
5877 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5878 // This is declared to take (const void*, ...) and can take two
5879 // optional constant int args.
5880 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5881   unsigned NumArgs = TheCall->getNumArgs();
5882 
5883   if (NumArgs > 3)
5884     return Diag(TheCall->getEndLoc(),
5885                 diag::err_typecheck_call_too_many_args_at_most)
5886            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5887 
5888   // Argument 0 is checked for us and the remaining arguments must be
5889   // constant integers.
5890   for (unsigned i = 1; i != NumArgs; ++i)
5891     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5892       return true;
5893 
5894   return false;
5895 }
5896 
5897 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5898 // __assume does not evaluate its arguments, and should warn if its argument
5899 // has side effects.
5900 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5901   Expr *Arg = TheCall->getArg(0);
5902   if (Arg->isInstantiationDependent()) return false;
5903 
5904   if (Arg->HasSideEffects(Context))
5905     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5906         << Arg->getSourceRange()
5907         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5908 
5909   return false;
5910 }
5911 
5912 /// Handle __builtin_alloca_with_align. This is declared
5913 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5914 /// than 8.
5915 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5916   // The alignment must be a constant integer.
5917   Expr *Arg = TheCall->getArg(1);
5918 
5919   // We can't check the value of a dependent argument.
5920   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5921     if (const auto *UE =
5922             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5923       if (UE->getKind() == UETT_AlignOf ||
5924           UE->getKind() == UETT_PreferredAlignOf)
5925         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5926             << Arg->getSourceRange();
5927 
5928     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5929 
5930     if (!Result.isPowerOf2())
5931       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5932              << Arg->getSourceRange();
5933 
5934     if (Result < Context.getCharWidth())
5935       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5936              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5937 
5938     if (Result > std::numeric_limits<int32_t>::max())
5939       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5940              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5941   }
5942 
5943   return false;
5944 }
5945 
5946 /// Handle __builtin_assume_aligned. This is declared
5947 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5948 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5949   unsigned NumArgs = TheCall->getNumArgs();
5950 
5951   if (NumArgs > 3)
5952     return Diag(TheCall->getEndLoc(),
5953                 diag::err_typecheck_call_too_many_args_at_most)
5954            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5955 
5956   // The alignment must be a constant integer.
5957   Expr *Arg = TheCall->getArg(1);
5958 
5959   // We can't check the value of a dependent argument.
5960   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5961     llvm::APSInt Result;
5962     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5963       return true;
5964 
5965     if (!Result.isPowerOf2())
5966       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5967              << Arg->getSourceRange();
5968   }
5969 
5970   if (NumArgs > 2) {
5971     ExprResult Arg(TheCall->getArg(2));
5972     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5973       Context.getSizeType(), false);
5974     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5975     if (Arg.isInvalid()) return true;
5976     TheCall->setArg(2, Arg.get());
5977   }
5978 
5979   return false;
5980 }
5981 
5982 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5983   unsigned BuiltinID =
5984       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5985   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5986 
5987   unsigned NumArgs = TheCall->getNumArgs();
5988   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5989   if (NumArgs < NumRequiredArgs) {
5990     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5991            << 0 /* function call */ << NumRequiredArgs << NumArgs
5992            << TheCall->getSourceRange();
5993   }
5994   if (NumArgs >= NumRequiredArgs + 0x100) {
5995     return Diag(TheCall->getEndLoc(),
5996                 diag::err_typecheck_call_too_many_args_at_most)
5997            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5998            << TheCall->getSourceRange();
5999   }
6000   unsigned i = 0;
6001 
6002   // For formatting call, check buffer arg.
6003   if (!IsSizeCall) {
6004     ExprResult Arg(TheCall->getArg(i));
6005     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6006         Context, Context.VoidPtrTy, false);
6007     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6008     if (Arg.isInvalid())
6009       return true;
6010     TheCall->setArg(i, Arg.get());
6011     i++;
6012   }
6013 
6014   // Check string literal arg.
6015   unsigned FormatIdx = i;
6016   {
6017     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6018     if (Arg.isInvalid())
6019       return true;
6020     TheCall->setArg(i, Arg.get());
6021     i++;
6022   }
6023 
6024   // Make sure variadic args are scalar.
6025   unsigned FirstDataArg = i;
6026   while (i < NumArgs) {
6027     ExprResult Arg = DefaultVariadicArgumentPromotion(
6028         TheCall->getArg(i), VariadicFunction, nullptr);
6029     if (Arg.isInvalid())
6030       return true;
6031     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6032     if (ArgSize.getQuantity() >= 0x100) {
6033       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6034              << i << (int)ArgSize.getQuantity() << 0xff
6035              << TheCall->getSourceRange();
6036     }
6037     TheCall->setArg(i, Arg.get());
6038     i++;
6039   }
6040 
6041   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6042   // call to avoid duplicate diagnostics.
6043   if (!IsSizeCall) {
6044     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6045     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6046     bool Success = CheckFormatArguments(
6047         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6048         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6049         CheckedVarArgs);
6050     if (!Success)
6051       return true;
6052   }
6053 
6054   if (IsSizeCall) {
6055     TheCall->setType(Context.getSizeType());
6056   } else {
6057     TheCall->setType(Context.VoidPtrTy);
6058   }
6059   return false;
6060 }
6061 
6062 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6063 /// TheCall is a constant expression.
6064 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6065                                   llvm::APSInt &Result) {
6066   Expr *Arg = TheCall->getArg(ArgNum);
6067   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6068   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6069 
6070   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6071 
6072   if (!Arg->isIntegerConstantExpr(Result, Context))
6073     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6074            << FDecl->getDeclName() << Arg->getSourceRange();
6075 
6076   return false;
6077 }
6078 
6079 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6080 /// TheCall is a constant expression in the range [Low, High].
6081 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6082                                        int Low, int High, bool RangeIsError) {
6083   if (isConstantEvaluated())
6084     return false;
6085   llvm::APSInt Result;
6086 
6087   // We can't check the value of a dependent argument.
6088   Expr *Arg = TheCall->getArg(ArgNum);
6089   if (Arg->isTypeDependent() || Arg->isValueDependent())
6090     return false;
6091 
6092   // Check constant-ness first.
6093   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6094     return true;
6095 
6096   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6097     if (RangeIsError)
6098       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6099              << Result.toString(10) << Low << High << Arg->getSourceRange();
6100     else
6101       // Defer the warning until we know if the code will be emitted so that
6102       // dead code can ignore this.
6103       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6104                           PDiag(diag::warn_argument_invalid_range)
6105                               << Result.toString(10) << Low << High
6106                               << Arg->getSourceRange());
6107   }
6108 
6109   return false;
6110 }
6111 
6112 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6113 /// TheCall is a constant expression is a multiple of Num..
6114 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6115                                           unsigned Num) {
6116   llvm::APSInt Result;
6117 
6118   // We can't check the value of a dependent argument.
6119   Expr *Arg = TheCall->getArg(ArgNum);
6120   if (Arg->isTypeDependent() || Arg->isValueDependent())
6121     return false;
6122 
6123   // Check constant-ness first.
6124   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6125     return true;
6126 
6127   if (Result.getSExtValue() % Num != 0)
6128     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6129            << Num << Arg->getSourceRange();
6130 
6131   return false;
6132 }
6133 
6134 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6135 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6136   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6137     if (checkArgCount(*this, TheCall, 2))
6138       return true;
6139     Expr *Arg0 = TheCall->getArg(0);
6140     Expr *Arg1 = TheCall->getArg(1);
6141 
6142     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6143     if (FirstArg.isInvalid())
6144       return true;
6145     QualType FirstArgType = FirstArg.get()->getType();
6146     if (!FirstArgType->isAnyPointerType())
6147       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6148                << "first" << FirstArgType << Arg0->getSourceRange();
6149     TheCall->setArg(0, FirstArg.get());
6150 
6151     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6152     if (SecArg.isInvalid())
6153       return true;
6154     QualType SecArgType = SecArg.get()->getType();
6155     if (!SecArgType->isIntegerType())
6156       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6157                << "second" << SecArgType << Arg1->getSourceRange();
6158 
6159     // Derive the return type from the pointer argument.
6160     TheCall->setType(FirstArgType);
6161     return false;
6162   }
6163 
6164   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6165     if (checkArgCount(*this, TheCall, 2))
6166       return true;
6167 
6168     Expr *Arg0 = TheCall->getArg(0);
6169     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6170     if (FirstArg.isInvalid())
6171       return true;
6172     QualType FirstArgType = FirstArg.get()->getType();
6173     if (!FirstArgType->isAnyPointerType())
6174       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6175                << "first" << FirstArgType << Arg0->getSourceRange();
6176     TheCall->setArg(0, FirstArg.get());
6177 
6178     // Derive the return type from the pointer argument.
6179     TheCall->setType(FirstArgType);
6180 
6181     // Second arg must be an constant in range [0,15]
6182     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6183   }
6184 
6185   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6186     if (checkArgCount(*this, TheCall, 2))
6187       return true;
6188     Expr *Arg0 = TheCall->getArg(0);
6189     Expr *Arg1 = TheCall->getArg(1);
6190 
6191     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6192     if (FirstArg.isInvalid())
6193       return true;
6194     QualType FirstArgType = FirstArg.get()->getType();
6195     if (!FirstArgType->isAnyPointerType())
6196       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6197                << "first" << FirstArgType << Arg0->getSourceRange();
6198 
6199     QualType SecArgType = Arg1->getType();
6200     if (!SecArgType->isIntegerType())
6201       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6202                << "second" << SecArgType << Arg1->getSourceRange();
6203     TheCall->setType(Context.IntTy);
6204     return false;
6205   }
6206 
6207   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6208       BuiltinID == AArch64::BI__builtin_arm_stg) {
6209     if (checkArgCount(*this, TheCall, 1))
6210       return true;
6211     Expr *Arg0 = TheCall->getArg(0);
6212     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6213     if (FirstArg.isInvalid())
6214       return true;
6215 
6216     QualType FirstArgType = FirstArg.get()->getType();
6217     if (!FirstArgType->isAnyPointerType())
6218       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6219                << "first" << FirstArgType << Arg0->getSourceRange();
6220     TheCall->setArg(0, FirstArg.get());
6221 
6222     // Derive the return type from the pointer argument.
6223     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6224       TheCall->setType(FirstArgType);
6225     return false;
6226   }
6227 
6228   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6229     Expr *ArgA = TheCall->getArg(0);
6230     Expr *ArgB = TheCall->getArg(1);
6231 
6232     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6233     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6234 
6235     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6236       return true;
6237 
6238     QualType ArgTypeA = ArgExprA.get()->getType();
6239     QualType ArgTypeB = ArgExprB.get()->getType();
6240 
6241     auto isNull = [&] (Expr *E) -> bool {
6242       return E->isNullPointerConstant(
6243                         Context, Expr::NPC_ValueDependentIsNotNull); };
6244 
6245     // argument should be either a pointer or null
6246     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6247       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6248         << "first" << ArgTypeA << ArgA->getSourceRange();
6249 
6250     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6251       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6252         << "second" << ArgTypeB << ArgB->getSourceRange();
6253 
6254     // Ensure Pointee types are compatible
6255     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6256         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6257       QualType pointeeA = ArgTypeA->getPointeeType();
6258       QualType pointeeB = ArgTypeB->getPointeeType();
6259       if (!Context.typesAreCompatible(
6260              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6261              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6262         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6263           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6264           << ArgB->getSourceRange();
6265       }
6266     }
6267 
6268     // at least one argument should be pointer type
6269     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6270       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6271         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6272 
6273     if (isNull(ArgA)) // adopt type of the other pointer
6274       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6275 
6276     if (isNull(ArgB))
6277       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6278 
6279     TheCall->setArg(0, ArgExprA.get());
6280     TheCall->setArg(1, ArgExprB.get());
6281     TheCall->setType(Context.LongLongTy);
6282     return false;
6283   }
6284   assert(false && "Unhandled ARM MTE intrinsic");
6285   return true;
6286 }
6287 
6288 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6289 /// TheCall is an ARM/AArch64 special register string literal.
6290 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6291                                     int ArgNum, unsigned ExpectedFieldNum,
6292                                     bool AllowName) {
6293   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6294                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6295                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6296                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6297                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6298                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6299   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6300                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6301                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6302                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6303                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6304                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6305   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6306 
6307   // We can't check the value of a dependent argument.
6308   Expr *Arg = TheCall->getArg(ArgNum);
6309   if (Arg->isTypeDependent() || Arg->isValueDependent())
6310     return false;
6311 
6312   // Check if the argument is a string literal.
6313   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6314     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6315            << Arg->getSourceRange();
6316 
6317   // Check the type of special register given.
6318   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6319   SmallVector<StringRef, 6> Fields;
6320   Reg.split(Fields, ":");
6321 
6322   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6323     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6324            << Arg->getSourceRange();
6325 
6326   // If the string is the name of a register then we cannot check that it is
6327   // valid here but if the string is of one the forms described in ACLE then we
6328   // can check that the supplied fields are integers and within the valid
6329   // ranges.
6330   if (Fields.size() > 1) {
6331     bool FiveFields = Fields.size() == 5;
6332 
6333     bool ValidString = true;
6334     if (IsARMBuiltin) {
6335       ValidString &= Fields[0].startswith_lower("cp") ||
6336                      Fields[0].startswith_lower("p");
6337       if (ValidString)
6338         Fields[0] =
6339           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6340 
6341       ValidString &= Fields[2].startswith_lower("c");
6342       if (ValidString)
6343         Fields[2] = Fields[2].drop_front(1);
6344 
6345       if (FiveFields) {
6346         ValidString &= Fields[3].startswith_lower("c");
6347         if (ValidString)
6348           Fields[3] = Fields[3].drop_front(1);
6349       }
6350     }
6351 
6352     SmallVector<int, 5> Ranges;
6353     if (FiveFields)
6354       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6355     else
6356       Ranges.append({15, 7, 15});
6357 
6358     for (unsigned i=0; i<Fields.size(); ++i) {
6359       int IntField;
6360       ValidString &= !Fields[i].getAsInteger(10, IntField);
6361       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6362     }
6363 
6364     if (!ValidString)
6365       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6366              << Arg->getSourceRange();
6367   } else if (IsAArch64Builtin && Fields.size() == 1) {
6368     // If the register name is one of those that appear in the condition below
6369     // and the special register builtin being used is one of the write builtins,
6370     // then we require that the argument provided for writing to the register
6371     // is an integer constant expression. This is because it will be lowered to
6372     // an MSR (immediate) instruction, so we need to know the immediate at
6373     // compile time.
6374     if (TheCall->getNumArgs() != 2)
6375       return false;
6376 
6377     std::string RegLower = Reg.lower();
6378     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6379         RegLower != "pan" && RegLower != "uao")
6380       return false;
6381 
6382     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6383   }
6384 
6385   return false;
6386 }
6387 
6388 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6389 /// This checks that the target supports __builtin_longjmp and
6390 /// that val is a constant 1.
6391 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6392   if (!Context.getTargetInfo().hasSjLjLowering())
6393     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6394            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6395 
6396   Expr *Arg = TheCall->getArg(1);
6397   llvm::APSInt Result;
6398 
6399   // TODO: This is less than ideal. Overload this to take a value.
6400   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6401     return true;
6402 
6403   if (Result != 1)
6404     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6405            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6406 
6407   return false;
6408 }
6409 
6410 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6411 /// This checks that the target supports __builtin_setjmp.
6412 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6413   if (!Context.getTargetInfo().hasSjLjLowering())
6414     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6415            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6416   return false;
6417 }
6418 
6419 namespace {
6420 
6421 class UncoveredArgHandler {
6422   enum { Unknown = -1, AllCovered = -2 };
6423 
6424   signed FirstUncoveredArg = Unknown;
6425   SmallVector<const Expr *, 4> DiagnosticExprs;
6426 
6427 public:
6428   UncoveredArgHandler() = default;
6429 
6430   bool hasUncoveredArg() const {
6431     return (FirstUncoveredArg >= 0);
6432   }
6433 
6434   unsigned getUncoveredArg() const {
6435     assert(hasUncoveredArg() && "no uncovered argument");
6436     return FirstUncoveredArg;
6437   }
6438 
6439   void setAllCovered() {
6440     // A string has been found with all arguments covered, so clear out
6441     // the diagnostics.
6442     DiagnosticExprs.clear();
6443     FirstUncoveredArg = AllCovered;
6444   }
6445 
6446   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6447     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6448 
6449     // Don't update if a previous string covers all arguments.
6450     if (FirstUncoveredArg == AllCovered)
6451       return;
6452 
6453     // UncoveredArgHandler tracks the highest uncovered argument index
6454     // and with it all the strings that match this index.
6455     if (NewFirstUncoveredArg == FirstUncoveredArg)
6456       DiagnosticExprs.push_back(StrExpr);
6457     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6458       DiagnosticExprs.clear();
6459       DiagnosticExprs.push_back(StrExpr);
6460       FirstUncoveredArg = NewFirstUncoveredArg;
6461     }
6462   }
6463 
6464   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6465 };
6466 
6467 enum StringLiteralCheckType {
6468   SLCT_NotALiteral,
6469   SLCT_UncheckedLiteral,
6470   SLCT_CheckedLiteral
6471 };
6472 
6473 } // namespace
6474 
6475 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6476                                      BinaryOperatorKind BinOpKind,
6477                                      bool AddendIsRight) {
6478   unsigned BitWidth = Offset.getBitWidth();
6479   unsigned AddendBitWidth = Addend.getBitWidth();
6480   // There might be negative interim results.
6481   if (Addend.isUnsigned()) {
6482     Addend = Addend.zext(++AddendBitWidth);
6483     Addend.setIsSigned(true);
6484   }
6485   // Adjust the bit width of the APSInts.
6486   if (AddendBitWidth > BitWidth) {
6487     Offset = Offset.sext(AddendBitWidth);
6488     BitWidth = AddendBitWidth;
6489   } else if (BitWidth > AddendBitWidth) {
6490     Addend = Addend.sext(BitWidth);
6491   }
6492 
6493   bool Ov = false;
6494   llvm::APSInt ResOffset = Offset;
6495   if (BinOpKind == BO_Add)
6496     ResOffset = Offset.sadd_ov(Addend, Ov);
6497   else {
6498     assert(AddendIsRight && BinOpKind == BO_Sub &&
6499            "operator must be add or sub with addend on the right");
6500     ResOffset = Offset.ssub_ov(Addend, Ov);
6501   }
6502 
6503   // We add an offset to a pointer here so we should support an offset as big as
6504   // possible.
6505   if (Ov) {
6506     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6507            "index (intermediate) result too big");
6508     Offset = Offset.sext(2 * BitWidth);
6509     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6510     return;
6511   }
6512 
6513   Offset = ResOffset;
6514 }
6515 
6516 namespace {
6517 
6518 // This is a wrapper class around StringLiteral to support offsetted string
6519 // literals as format strings. It takes the offset into account when returning
6520 // the string and its length or the source locations to display notes correctly.
6521 class FormatStringLiteral {
6522   const StringLiteral *FExpr;
6523   int64_t Offset;
6524 
6525  public:
6526   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6527       : FExpr(fexpr), Offset(Offset) {}
6528 
6529   StringRef getString() const {
6530     return FExpr->getString().drop_front(Offset);
6531   }
6532 
6533   unsigned getByteLength() const {
6534     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6535   }
6536 
6537   unsigned getLength() const { return FExpr->getLength() - Offset; }
6538   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6539 
6540   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6541 
6542   QualType getType() const { return FExpr->getType(); }
6543 
6544   bool isAscii() const { return FExpr->isAscii(); }
6545   bool isWide() const { return FExpr->isWide(); }
6546   bool isUTF8() const { return FExpr->isUTF8(); }
6547   bool isUTF16() const { return FExpr->isUTF16(); }
6548   bool isUTF32() const { return FExpr->isUTF32(); }
6549   bool isPascal() const { return FExpr->isPascal(); }
6550 
6551   SourceLocation getLocationOfByte(
6552       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6553       const TargetInfo &Target, unsigned *StartToken = nullptr,
6554       unsigned *StartTokenByteOffset = nullptr) const {
6555     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6556                                     StartToken, StartTokenByteOffset);
6557   }
6558 
6559   SourceLocation getBeginLoc() const LLVM_READONLY {
6560     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6561   }
6562 
6563   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6564 };
6565 
6566 }  // namespace
6567 
6568 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6569                               const Expr *OrigFormatExpr,
6570                               ArrayRef<const Expr *> Args,
6571                               bool HasVAListArg, unsigned format_idx,
6572                               unsigned firstDataArg,
6573                               Sema::FormatStringType Type,
6574                               bool inFunctionCall,
6575                               Sema::VariadicCallType CallType,
6576                               llvm::SmallBitVector &CheckedVarArgs,
6577                               UncoveredArgHandler &UncoveredArg);
6578 
6579 // Determine if an expression is a string literal or constant string.
6580 // If this function returns false on the arguments to a function expecting a
6581 // format string, we will usually need to emit a warning.
6582 // True string literals are then checked by CheckFormatString.
6583 static StringLiteralCheckType
6584 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6585                       bool HasVAListArg, unsigned format_idx,
6586                       unsigned firstDataArg, Sema::FormatStringType Type,
6587                       Sema::VariadicCallType CallType, bool InFunctionCall,
6588                       llvm::SmallBitVector &CheckedVarArgs,
6589                       UncoveredArgHandler &UncoveredArg,
6590                       llvm::APSInt Offset) {
6591   if (S.isConstantEvaluated())
6592     return SLCT_NotALiteral;
6593  tryAgain:
6594   assert(Offset.isSigned() && "invalid offset");
6595 
6596   if (E->isTypeDependent() || E->isValueDependent())
6597     return SLCT_NotALiteral;
6598 
6599   E = E->IgnoreParenCasts();
6600 
6601   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6602     // Technically -Wformat-nonliteral does not warn about this case.
6603     // The behavior of printf and friends in this case is implementation
6604     // dependent.  Ideally if the format string cannot be null then
6605     // it should have a 'nonnull' attribute in the function prototype.
6606     return SLCT_UncheckedLiteral;
6607 
6608   switch (E->getStmtClass()) {
6609   case Stmt::BinaryConditionalOperatorClass:
6610   case Stmt::ConditionalOperatorClass: {
6611     // The expression is a literal if both sub-expressions were, and it was
6612     // completely checked only if both sub-expressions were checked.
6613     const AbstractConditionalOperator *C =
6614         cast<AbstractConditionalOperator>(E);
6615 
6616     // Determine whether it is necessary to check both sub-expressions, for
6617     // example, because the condition expression is a constant that can be
6618     // evaluated at compile time.
6619     bool CheckLeft = true, CheckRight = true;
6620 
6621     bool Cond;
6622     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6623                                                  S.isConstantEvaluated())) {
6624       if (Cond)
6625         CheckRight = false;
6626       else
6627         CheckLeft = false;
6628     }
6629 
6630     // We need to maintain the offsets for the right and the left hand side
6631     // separately to check if every possible indexed expression is a valid
6632     // string literal. They might have different offsets for different string
6633     // literals in the end.
6634     StringLiteralCheckType Left;
6635     if (!CheckLeft)
6636       Left = SLCT_UncheckedLiteral;
6637     else {
6638       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6639                                    HasVAListArg, format_idx, firstDataArg,
6640                                    Type, CallType, InFunctionCall,
6641                                    CheckedVarArgs, UncoveredArg, Offset);
6642       if (Left == SLCT_NotALiteral || !CheckRight) {
6643         return Left;
6644       }
6645     }
6646 
6647     StringLiteralCheckType Right =
6648         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6649                               HasVAListArg, format_idx, firstDataArg,
6650                               Type, CallType, InFunctionCall, CheckedVarArgs,
6651                               UncoveredArg, Offset);
6652 
6653     return (CheckLeft && Left < Right) ? Left : Right;
6654   }
6655 
6656   case Stmt::ImplicitCastExprClass:
6657     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6658     goto tryAgain;
6659 
6660   case Stmt::OpaqueValueExprClass:
6661     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6662       E = src;
6663       goto tryAgain;
6664     }
6665     return SLCT_NotALiteral;
6666 
6667   case Stmt::PredefinedExprClass:
6668     // While __func__, etc., are technically not string literals, they
6669     // cannot contain format specifiers and thus are not a security
6670     // liability.
6671     return SLCT_UncheckedLiteral;
6672 
6673   case Stmt::DeclRefExprClass: {
6674     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6675 
6676     // As an exception, do not flag errors for variables binding to
6677     // const string literals.
6678     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6679       bool isConstant = false;
6680       QualType T = DR->getType();
6681 
6682       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6683         isConstant = AT->getElementType().isConstant(S.Context);
6684       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6685         isConstant = T.isConstant(S.Context) &&
6686                      PT->getPointeeType().isConstant(S.Context);
6687       } else if (T->isObjCObjectPointerType()) {
6688         // In ObjC, there is usually no "const ObjectPointer" type,
6689         // so don't check if the pointee type is constant.
6690         isConstant = T.isConstant(S.Context);
6691       }
6692 
6693       if (isConstant) {
6694         if (const Expr *Init = VD->getAnyInitializer()) {
6695           // Look through initializers like const char c[] = { "foo" }
6696           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6697             if (InitList->isStringLiteralInit())
6698               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6699           }
6700           return checkFormatStringExpr(S, Init, Args,
6701                                        HasVAListArg, format_idx,
6702                                        firstDataArg, Type, CallType,
6703                                        /*InFunctionCall*/ false, CheckedVarArgs,
6704                                        UncoveredArg, Offset);
6705         }
6706       }
6707 
6708       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6709       // special check to see if the format string is a function parameter
6710       // of the function calling the printf function.  If the function
6711       // has an attribute indicating it is a printf-like function, then we
6712       // should suppress warnings concerning non-literals being used in a call
6713       // to a vprintf function.  For example:
6714       //
6715       // void
6716       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6717       //      va_list ap;
6718       //      va_start(ap, fmt);
6719       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6720       //      ...
6721       // }
6722       if (HasVAListArg) {
6723         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6724           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6725             int PVIndex = PV->getFunctionScopeIndex() + 1;
6726             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6727               // adjust for implicit parameter
6728               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6729                 if (MD->isInstance())
6730                   ++PVIndex;
6731               // We also check if the formats are compatible.
6732               // We can't pass a 'scanf' string to a 'printf' function.
6733               if (PVIndex == PVFormat->getFormatIdx() &&
6734                   Type == S.GetFormatStringType(PVFormat))
6735                 return SLCT_UncheckedLiteral;
6736             }
6737           }
6738         }
6739       }
6740     }
6741 
6742     return SLCT_NotALiteral;
6743   }
6744 
6745   case Stmt::CallExprClass:
6746   case Stmt::CXXMemberCallExprClass: {
6747     const CallExpr *CE = cast<CallExpr>(E);
6748     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6749       bool IsFirst = true;
6750       StringLiteralCheckType CommonResult;
6751       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6752         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6753         StringLiteralCheckType Result = checkFormatStringExpr(
6754             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6755             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6756         if (IsFirst) {
6757           CommonResult = Result;
6758           IsFirst = false;
6759         }
6760       }
6761       if (!IsFirst)
6762         return CommonResult;
6763 
6764       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6765         unsigned BuiltinID = FD->getBuiltinID();
6766         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6767             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6768           const Expr *Arg = CE->getArg(0);
6769           return checkFormatStringExpr(S, Arg, Args,
6770                                        HasVAListArg, format_idx,
6771                                        firstDataArg, Type, CallType,
6772                                        InFunctionCall, CheckedVarArgs,
6773                                        UncoveredArg, Offset);
6774         }
6775       }
6776     }
6777 
6778     return SLCT_NotALiteral;
6779   }
6780   case Stmt::ObjCMessageExprClass: {
6781     const auto *ME = cast<ObjCMessageExpr>(E);
6782     if (const auto *ND = ME->getMethodDecl()) {
6783       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6784         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6785         return checkFormatStringExpr(
6786             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6787             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6788       }
6789     }
6790 
6791     return SLCT_NotALiteral;
6792   }
6793   case Stmt::ObjCStringLiteralClass:
6794   case Stmt::StringLiteralClass: {
6795     const StringLiteral *StrE = nullptr;
6796 
6797     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6798       StrE = ObjCFExpr->getString();
6799     else
6800       StrE = cast<StringLiteral>(E);
6801 
6802     if (StrE) {
6803       if (Offset.isNegative() || Offset > StrE->getLength()) {
6804         // TODO: It would be better to have an explicit warning for out of
6805         // bounds literals.
6806         return SLCT_NotALiteral;
6807       }
6808       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6809       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6810                         firstDataArg, Type, InFunctionCall, CallType,
6811                         CheckedVarArgs, UncoveredArg);
6812       return SLCT_CheckedLiteral;
6813     }
6814 
6815     return SLCT_NotALiteral;
6816   }
6817   case Stmt::BinaryOperatorClass: {
6818     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6819 
6820     // A string literal + an int offset is still a string literal.
6821     if (BinOp->isAdditiveOp()) {
6822       Expr::EvalResult LResult, RResult;
6823 
6824       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6825           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6826       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6827           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6828 
6829       if (LIsInt != RIsInt) {
6830         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6831 
6832         if (LIsInt) {
6833           if (BinOpKind == BO_Add) {
6834             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6835             E = BinOp->getRHS();
6836             goto tryAgain;
6837           }
6838         } else {
6839           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6840           E = BinOp->getLHS();
6841           goto tryAgain;
6842         }
6843       }
6844     }
6845 
6846     return SLCT_NotALiteral;
6847   }
6848   case Stmt::UnaryOperatorClass: {
6849     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6850     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6851     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6852       Expr::EvalResult IndexResult;
6853       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6854                                        Expr::SE_NoSideEffects,
6855                                        S.isConstantEvaluated())) {
6856         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6857                    /*RHS is int*/ true);
6858         E = ASE->getBase();
6859         goto tryAgain;
6860       }
6861     }
6862 
6863     return SLCT_NotALiteral;
6864   }
6865 
6866   default:
6867     return SLCT_NotALiteral;
6868   }
6869 }
6870 
6871 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6872   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6873       .Case("scanf", FST_Scanf)
6874       .Cases("printf", "printf0", FST_Printf)
6875       .Cases("NSString", "CFString", FST_NSString)
6876       .Case("strftime", FST_Strftime)
6877       .Case("strfmon", FST_Strfmon)
6878       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6879       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6880       .Case("os_trace", FST_OSLog)
6881       .Case("os_log", FST_OSLog)
6882       .Default(FST_Unknown);
6883 }
6884 
6885 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6886 /// functions) for correct use of format strings.
6887 /// Returns true if a format string has been fully checked.
6888 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6889                                 ArrayRef<const Expr *> Args,
6890                                 bool IsCXXMember,
6891                                 VariadicCallType CallType,
6892                                 SourceLocation Loc, SourceRange Range,
6893                                 llvm::SmallBitVector &CheckedVarArgs) {
6894   FormatStringInfo FSI;
6895   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6896     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6897                                 FSI.FirstDataArg, GetFormatStringType(Format),
6898                                 CallType, Loc, Range, CheckedVarArgs);
6899   return false;
6900 }
6901 
6902 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6903                                 bool HasVAListArg, unsigned format_idx,
6904                                 unsigned firstDataArg, FormatStringType Type,
6905                                 VariadicCallType CallType,
6906                                 SourceLocation Loc, SourceRange Range,
6907                                 llvm::SmallBitVector &CheckedVarArgs) {
6908   // CHECK: printf/scanf-like function is called with no format string.
6909   if (format_idx >= Args.size()) {
6910     Diag(Loc, diag::warn_missing_format_string) << Range;
6911     return false;
6912   }
6913 
6914   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6915 
6916   // CHECK: format string is not a string literal.
6917   //
6918   // Dynamically generated format strings are difficult to
6919   // automatically vet at compile time.  Requiring that format strings
6920   // are string literals: (1) permits the checking of format strings by
6921   // the compiler and thereby (2) can practically remove the source of
6922   // many format string exploits.
6923 
6924   // Format string can be either ObjC string (e.g. @"%d") or
6925   // C string (e.g. "%d")
6926   // ObjC string uses the same format specifiers as C string, so we can use
6927   // the same format string checking logic for both ObjC and C strings.
6928   UncoveredArgHandler UncoveredArg;
6929   StringLiteralCheckType CT =
6930       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6931                             format_idx, firstDataArg, Type, CallType,
6932                             /*IsFunctionCall*/ true, CheckedVarArgs,
6933                             UncoveredArg,
6934                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6935 
6936   // Generate a diagnostic where an uncovered argument is detected.
6937   if (UncoveredArg.hasUncoveredArg()) {
6938     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6939     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6940     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6941   }
6942 
6943   if (CT != SLCT_NotALiteral)
6944     // Literal format string found, check done!
6945     return CT == SLCT_CheckedLiteral;
6946 
6947   // Strftime is particular as it always uses a single 'time' argument,
6948   // so it is safe to pass a non-literal string.
6949   if (Type == FST_Strftime)
6950     return false;
6951 
6952   // Do not emit diag when the string param is a macro expansion and the
6953   // format is either NSString or CFString. This is a hack to prevent
6954   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6955   // which are usually used in place of NS and CF string literals.
6956   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6957   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6958     return false;
6959 
6960   // If there are no arguments specified, warn with -Wformat-security, otherwise
6961   // warn only with -Wformat-nonliteral.
6962   if (Args.size() == firstDataArg) {
6963     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6964       << OrigFormatExpr->getSourceRange();
6965     switch (Type) {
6966     default:
6967       break;
6968     case FST_Kprintf:
6969     case FST_FreeBSDKPrintf:
6970     case FST_Printf:
6971       Diag(FormatLoc, diag::note_format_security_fixit)
6972         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6973       break;
6974     case FST_NSString:
6975       Diag(FormatLoc, diag::note_format_security_fixit)
6976         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6977       break;
6978     }
6979   } else {
6980     Diag(FormatLoc, diag::warn_format_nonliteral)
6981       << OrigFormatExpr->getSourceRange();
6982   }
6983   return false;
6984 }
6985 
6986 namespace {
6987 
6988 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6989 protected:
6990   Sema &S;
6991   const FormatStringLiteral *FExpr;
6992   const Expr *OrigFormatExpr;
6993   const Sema::FormatStringType FSType;
6994   const unsigned FirstDataArg;
6995   const unsigned NumDataArgs;
6996   const char *Beg; // Start of format string.
6997   const bool HasVAListArg;
6998   ArrayRef<const Expr *> Args;
6999   unsigned FormatIdx;
7000   llvm::SmallBitVector CoveredArgs;
7001   bool usesPositionalArgs = false;
7002   bool atFirstArg = true;
7003   bool inFunctionCall;
7004   Sema::VariadicCallType CallType;
7005   llvm::SmallBitVector &CheckedVarArgs;
7006   UncoveredArgHandler &UncoveredArg;
7007 
7008 public:
7009   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7010                      const Expr *origFormatExpr,
7011                      const Sema::FormatStringType type, unsigned firstDataArg,
7012                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7013                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7014                      bool inFunctionCall, Sema::VariadicCallType callType,
7015                      llvm::SmallBitVector &CheckedVarArgs,
7016                      UncoveredArgHandler &UncoveredArg)
7017       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7018         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7019         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7020         inFunctionCall(inFunctionCall), CallType(callType),
7021         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7022     CoveredArgs.resize(numDataArgs);
7023     CoveredArgs.reset();
7024   }
7025 
7026   void DoneProcessing();
7027 
7028   void HandleIncompleteSpecifier(const char *startSpecifier,
7029                                  unsigned specifierLen) override;
7030 
7031   void HandleInvalidLengthModifier(
7032                            const analyze_format_string::FormatSpecifier &FS,
7033                            const analyze_format_string::ConversionSpecifier &CS,
7034                            const char *startSpecifier, unsigned specifierLen,
7035                            unsigned DiagID);
7036 
7037   void HandleNonStandardLengthModifier(
7038                     const analyze_format_string::FormatSpecifier &FS,
7039                     const char *startSpecifier, unsigned specifierLen);
7040 
7041   void HandleNonStandardConversionSpecifier(
7042                     const analyze_format_string::ConversionSpecifier &CS,
7043                     const char *startSpecifier, unsigned specifierLen);
7044 
7045   void HandlePosition(const char *startPos, unsigned posLen) override;
7046 
7047   void HandleInvalidPosition(const char *startSpecifier,
7048                              unsigned specifierLen,
7049                              analyze_format_string::PositionContext p) override;
7050 
7051   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7052 
7053   void HandleNullChar(const char *nullCharacter) override;
7054 
7055   template <typename Range>
7056   static void
7057   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7058                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7059                        bool IsStringLocation, Range StringRange,
7060                        ArrayRef<FixItHint> Fixit = None);
7061 
7062 protected:
7063   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7064                                         const char *startSpec,
7065                                         unsigned specifierLen,
7066                                         const char *csStart, unsigned csLen);
7067 
7068   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7069                                          const char *startSpec,
7070                                          unsigned specifierLen);
7071 
7072   SourceRange getFormatStringRange();
7073   CharSourceRange getSpecifierRange(const char *startSpecifier,
7074                                     unsigned specifierLen);
7075   SourceLocation getLocationOfByte(const char *x);
7076 
7077   const Expr *getDataArg(unsigned i) const;
7078 
7079   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7080                     const analyze_format_string::ConversionSpecifier &CS,
7081                     const char *startSpecifier, unsigned specifierLen,
7082                     unsigned argIndex);
7083 
7084   template <typename Range>
7085   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7086                             bool IsStringLocation, Range StringRange,
7087                             ArrayRef<FixItHint> Fixit = None);
7088 };
7089 
7090 } // namespace
7091 
7092 SourceRange CheckFormatHandler::getFormatStringRange() {
7093   return OrigFormatExpr->getSourceRange();
7094 }
7095 
7096 CharSourceRange CheckFormatHandler::
7097 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7098   SourceLocation Start = getLocationOfByte(startSpecifier);
7099   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7100 
7101   // Advance the end SourceLocation by one due to half-open ranges.
7102   End = End.getLocWithOffset(1);
7103 
7104   return CharSourceRange::getCharRange(Start, End);
7105 }
7106 
7107 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7108   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7109                                   S.getLangOpts(), S.Context.getTargetInfo());
7110 }
7111 
7112 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7113                                                    unsigned specifierLen){
7114   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7115                        getLocationOfByte(startSpecifier),
7116                        /*IsStringLocation*/true,
7117                        getSpecifierRange(startSpecifier, specifierLen));
7118 }
7119 
7120 void CheckFormatHandler::HandleInvalidLengthModifier(
7121     const analyze_format_string::FormatSpecifier &FS,
7122     const analyze_format_string::ConversionSpecifier &CS,
7123     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7124   using namespace analyze_format_string;
7125 
7126   const LengthModifier &LM = FS.getLengthModifier();
7127   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7128 
7129   // See if we know how to fix this length modifier.
7130   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7131   if (FixedLM) {
7132     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7133                          getLocationOfByte(LM.getStart()),
7134                          /*IsStringLocation*/true,
7135                          getSpecifierRange(startSpecifier, specifierLen));
7136 
7137     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7138       << FixedLM->toString()
7139       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7140 
7141   } else {
7142     FixItHint Hint;
7143     if (DiagID == diag::warn_format_nonsensical_length)
7144       Hint = FixItHint::CreateRemoval(LMRange);
7145 
7146     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7147                          getLocationOfByte(LM.getStart()),
7148                          /*IsStringLocation*/true,
7149                          getSpecifierRange(startSpecifier, specifierLen),
7150                          Hint);
7151   }
7152 }
7153 
7154 void CheckFormatHandler::HandleNonStandardLengthModifier(
7155     const analyze_format_string::FormatSpecifier &FS,
7156     const char *startSpecifier, unsigned specifierLen) {
7157   using namespace analyze_format_string;
7158 
7159   const LengthModifier &LM = FS.getLengthModifier();
7160   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7161 
7162   // See if we know how to fix this length modifier.
7163   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7164   if (FixedLM) {
7165     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7166                            << LM.toString() << 0,
7167                          getLocationOfByte(LM.getStart()),
7168                          /*IsStringLocation*/true,
7169                          getSpecifierRange(startSpecifier, specifierLen));
7170 
7171     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7172       << FixedLM->toString()
7173       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7174 
7175   } else {
7176     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7177                            << LM.toString() << 0,
7178                          getLocationOfByte(LM.getStart()),
7179                          /*IsStringLocation*/true,
7180                          getSpecifierRange(startSpecifier, specifierLen));
7181   }
7182 }
7183 
7184 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7185     const analyze_format_string::ConversionSpecifier &CS,
7186     const char *startSpecifier, unsigned specifierLen) {
7187   using namespace analyze_format_string;
7188 
7189   // See if we know how to fix this conversion specifier.
7190   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7191   if (FixedCS) {
7192     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7193                           << CS.toString() << /*conversion specifier*/1,
7194                          getLocationOfByte(CS.getStart()),
7195                          /*IsStringLocation*/true,
7196                          getSpecifierRange(startSpecifier, specifierLen));
7197 
7198     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7199     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7200       << FixedCS->toString()
7201       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7202   } else {
7203     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7204                           << CS.toString() << /*conversion specifier*/1,
7205                          getLocationOfByte(CS.getStart()),
7206                          /*IsStringLocation*/true,
7207                          getSpecifierRange(startSpecifier, specifierLen));
7208   }
7209 }
7210 
7211 void CheckFormatHandler::HandlePosition(const char *startPos,
7212                                         unsigned posLen) {
7213   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7214                                getLocationOfByte(startPos),
7215                                /*IsStringLocation*/true,
7216                                getSpecifierRange(startPos, posLen));
7217 }
7218 
7219 void
7220 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7221                                      analyze_format_string::PositionContext p) {
7222   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7223                          << (unsigned) p,
7224                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7225                        getSpecifierRange(startPos, posLen));
7226 }
7227 
7228 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7229                                             unsigned posLen) {
7230   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7231                                getLocationOfByte(startPos),
7232                                /*IsStringLocation*/true,
7233                                getSpecifierRange(startPos, posLen));
7234 }
7235 
7236 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7237   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7238     // The presence of a null character is likely an error.
7239     EmitFormatDiagnostic(
7240       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7241       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7242       getFormatStringRange());
7243   }
7244 }
7245 
7246 // Note that this may return NULL if there was an error parsing or building
7247 // one of the argument expressions.
7248 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7249   return Args[FirstDataArg + i];
7250 }
7251 
7252 void CheckFormatHandler::DoneProcessing() {
7253   // Does the number of data arguments exceed the number of
7254   // format conversions in the format string?
7255   if (!HasVAListArg) {
7256       // Find any arguments that weren't covered.
7257     CoveredArgs.flip();
7258     signed notCoveredArg = CoveredArgs.find_first();
7259     if (notCoveredArg >= 0) {
7260       assert((unsigned)notCoveredArg < NumDataArgs);
7261       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7262     } else {
7263       UncoveredArg.setAllCovered();
7264     }
7265   }
7266 }
7267 
7268 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7269                                    const Expr *ArgExpr) {
7270   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7271          "Invalid state");
7272 
7273   if (!ArgExpr)
7274     return;
7275 
7276   SourceLocation Loc = ArgExpr->getBeginLoc();
7277 
7278   if (S.getSourceManager().isInSystemMacro(Loc))
7279     return;
7280 
7281   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7282   for (auto E : DiagnosticExprs)
7283     PDiag << E->getSourceRange();
7284 
7285   CheckFormatHandler::EmitFormatDiagnostic(
7286                                   S, IsFunctionCall, DiagnosticExprs[0],
7287                                   PDiag, Loc, /*IsStringLocation*/false,
7288                                   DiagnosticExprs[0]->getSourceRange());
7289 }
7290 
7291 bool
7292 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7293                                                      SourceLocation Loc,
7294                                                      const char *startSpec,
7295                                                      unsigned specifierLen,
7296                                                      const char *csStart,
7297                                                      unsigned csLen) {
7298   bool keepGoing = true;
7299   if (argIndex < NumDataArgs) {
7300     // Consider the argument coverered, even though the specifier doesn't
7301     // make sense.
7302     CoveredArgs.set(argIndex);
7303   }
7304   else {
7305     // If argIndex exceeds the number of data arguments we
7306     // don't issue a warning because that is just a cascade of warnings (and
7307     // they may have intended '%%' anyway). We don't want to continue processing
7308     // the format string after this point, however, as we will like just get
7309     // gibberish when trying to match arguments.
7310     keepGoing = false;
7311   }
7312 
7313   StringRef Specifier(csStart, csLen);
7314 
7315   // If the specifier in non-printable, it could be the first byte of a UTF-8
7316   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7317   // hex value.
7318   std::string CodePointStr;
7319   if (!llvm::sys::locale::isPrint(*csStart)) {
7320     llvm::UTF32 CodePoint;
7321     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7322     const llvm::UTF8 *E =
7323         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7324     llvm::ConversionResult Result =
7325         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7326 
7327     if (Result != llvm::conversionOK) {
7328       unsigned char FirstChar = *csStart;
7329       CodePoint = (llvm::UTF32)FirstChar;
7330     }
7331 
7332     llvm::raw_string_ostream OS(CodePointStr);
7333     if (CodePoint < 256)
7334       OS << "\\x" << llvm::format("%02x", CodePoint);
7335     else if (CodePoint <= 0xFFFF)
7336       OS << "\\u" << llvm::format("%04x", CodePoint);
7337     else
7338       OS << "\\U" << llvm::format("%08x", CodePoint);
7339     OS.flush();
7340     Specifier = CodePointStr;
7341   }
7342 
7343   EmitFormatDiagnostic(
7344       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7345       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7346 
7347   return keepGoing;
7348 }
7349 
7350 void
7351 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7352                                                       const char *startSpec,
7353                                                       unsigned specifierLen) {
7354   EmitFormatDiagnostic(
7355     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7356     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7357 }
7358 
7359 bool
7360 CheckFormatHandler::CheckNumArgs(
7361   const analyze_format_string::FormatSpecifier &FS,
7362   const analyze_format_string::ConversionSpecifier &CS,
7363   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7364 
7365   if (argIndex >= NumDataArgs) {
7366     PartialDiagnostic PDiag = FS.usesPositionalArg()
7367       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7368            << (argIndex+1) << NumDataArgs)
7369       : S.PDiag(diag::warn_printf_insufficient_data_args);
7370     EmitFormatDiagnostic(
7371       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7372       getSpecifierRange(startSpecifier, specifierLen));
7373 
7374     // Since more arguments than conversion tokens are given, by extension
7375     // all arguments are covered, so mark this as so.
7376     UncoveredArg.setAllCovered();
7377     return false;
7378   }
7379   return true;
7380 }
7381 
7382 template<typename Range>
7383 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7384                                               SourceLocation Loc,
7385                                               bool IsStringLocation,
7386                                               Range StringRange,
7387                                               ArrayRef<FixItHint> FixIt) {
7388   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7389                        Loc, IsStringLocation, StringRange, FixIt);
7390 }
7391 
7392 /// If the format string is not within the function call, emit a note
7393 /// so that the function call and string are in diagnostic messages.
7394 ///
7395 /// \param InFunctionCall if true, the format string is within the function
7396 /// call and only one diagnostic message will be produced.  Otherwise, an
7397 /// extra note will be emitted pointing to location of the format string.
7398 ///
7399 /// \param ArgumentExpr the expression that is passed as the format string
7400 /// argument in the function call.  Used for getting locations when two
7401 /// diagnostics are emitted.
7402 ///
7403 /// \param PDiag the callee should already have provided any strings for the
7404 /// diagnostic message.  This function only adds locations and fixits
7405 /// to diagnostics.
7406 ///
7407 /// \param Loc primary location for diagnostic.  If two diagnostics are
7408 /// required, one will be at Loc and a new SourceLocation will be created for
7409 /// the other one.
7410 ///
7411 /// \param IsStringLocation if true, Loc points to the format string should be
7412 /// used for the note.  Otherwise, Loc points to the argument list and will
7413 /// be used with PDiag.
7414 ///
7415 /// \param StringRange some or all of the string to highlight.  This is
7416 /// templated so it can accept either a CharSourceRange or a SourceRange.
7417 ///
7418 /// \param FixIt optional fix it hint for the format string.
7419 template <typename Range>
7420 void CheckFormatHandler::EmitFormatDiagnostic(
7421     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7422     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7423     Range StringRange, ArrayRef<FixItHint> FixIt) {
7424   if (InFunctionCall) {
7425     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7426     D << StringRange;
7427     D << FixIt;
7428   } else {
7429     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7430       << ArgumentExpr->getSourceRange();
7431 
7432     const Sema::SemaDiagnosticBuilder &Note =
7433       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7434              diag::note_format_string_defined);
7435 
7436     Note << StringRange;
7437     Note << FixIt;
7438   }
7439 }
7440 
7441 //===--- CHECK: Printf format string checking ------------------------------===//
7442 
7443 namespace {
7444 
7445 class CheckPrintfHandler : public CheckFormatHandler {
7446 public:
7447   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7448                      const Expr *origFormatExpr,
7449                      const Sema::FormatStringType type, unsigned firstDataArg,
7450                      unsigned numDataArgs, bool isObjC, const char *beg,
7451                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7452                      unsigned formatIdx, bool inFunctionCall,
7453                      Sema::VariadicCallType CallType,
7454                      llvm::SmallBitVector &CheckedVarArgs,
7455                      UncoveredArgHandler &UncoveredArg)
7456       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7457                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7458                            inFunctionCall, CallType, CheckedVarArgs,
7459                            UncoveredArg) {}
7460 
7461   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7462 
7463   /// Returns true if '%@' specifiers are allowed in the format string.
7464   bool allowsObjCArg() const {
7465     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7466            FSType == Sema::FST_OSTrace;
7467   }
7468 
7469   bool HandleInvalidPrintfConversionSpecifier(
7470                                       const analyze_printf::PrintfSpecifier &FS,
7471                                       const char *startSpecifier,
7472                                       unsigned specifierLen) override;
7473 
7474   void handleInvalidMaskType(StringRef MaskType) override;
7475 
7476   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7477                              const char *startSpecifier,
7478                              unsigned specifierLen) override;
7479   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7480                        const char *StartSpecifier,
7481                        unsigned SpecifierLen,
7482                        const Expr *E);
7483 
7484   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7485                     const char *startSpecifier, unsigned specifierLen);
7486   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7487                            const analyze_printf::OptionalAmount &Amt,
7488                            unsigned type,
7489                            const char *startSpecifier, unsigned specifierLen);
7490   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7491                   const analyze_printf::OptionalFlag &flag,
7492                   const char *startSpecifier, unsigned specifierLen);
7493   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7494                          const analyze_printf::OptionalFlag &ignoredFlag,
7495                          const analyze_printf::OptionalFlag &flag,
7496                          const char *startSpecifier, unsigned specifierLen);
7497   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7498                            const Expr *E);
7499 
7500   void HandleEmptyObjCModifierFlag(const char *startFlag,
7501                                    unsigned flagLen) override;
7502 
7503   void HandleInvalidObjCModifierFlag(const char *startFlag,
7504                                             unsigned flagLen) override;
7505 
7506   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7507                                            const char *flagsEnd,
7508                                            const char *conversionPosition)
7509                                              override;
7510 };
7511 
7512 } // namespace
7513 
7514 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7515                                       const analyze_printf::PrintfSpecifier &FS,
7516                                       const char *startSpecifier,
7517                                       unsigned specifierLen) {
7518   const analyze_printf::PrintfConversionSpecifier &CS =
7519     FS.getConversionSpecifier();
7520 
7521   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7522                                           getLocationOfByte(CS.getStart()),
7523                                           startSpecifier, specifierLen,
7524                                           CS.getStart(), CS.getLength());
7525 }
7526 
7527 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7528   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7529 }
7530 
7531 bool CheckPrintfHandler::HandleAmount(
7532                                const analyze_format_string::OptionalAmount &Amt,
7533                                unsigned k, const char *startSpecifier,
7534                                unsigned specifierLen) {
7535   if (Amt.hasDataArgument()) {
7536     if (!HasVAListArg) {
7537       unsigned argIndex = Amt.getArgIndex();
7538       if (argIndex >= NumDataArgs) {
7539         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7540                                << k,
7541                              getLocationOfByte(Amt.getStart()),
7542                              /*IsStringLocation*/true,
7543                              getSpecifierRange(startSpecifier, specifierLen));
7544         // Don't do any more checking.  We will just emit
7545         // spurious errors.
7546         return false;
7547       }
7548 
7549       // Type check the data argument.  It should be an 'int'.
7550       // Although not in conformance with C99, we also allow the argument to be
7551       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7552       // doesn't emit a warning for that case.
7553       CoveredArgs.set(argIndex);
7554       const Expr *Arg = getDataArg(argIndex);
7555       if (!Arg)
7556         return false;
7557 
7558       QualType T = Arg->getType();
7559 
7560       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7561       assert(AT.isValid());
7562 
7563       if (!AT.matchesType(S.Context, T)) {
7564         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7565                                << k << AT.getRepresentativeTypeName(S.Context)
7566                                << T << Arg->getSourceRange(),
7567                              getLocationOfByte(Amt.getStart()),
7568                              /*IsStringLocation*/true,
7569                              getSpecifierRange(startSpecifier, specifierLen));
7570         // Don't do any more checking.  We will just emit
7571         // spurious errors.
7572         return false;
7573       }
7574     }
7575   }
7576   return true;
7577 }
7578 
7579 void CheckPrintfHandler::HandleInvalidAmount(
7580                                       const analyze_printf::PrintfSpecifier &FS,
7581                                       const analyze_printf::OptionalAmount &Amt,
7582                                       unsigned type,
7583                                       const char *startSpecifier,
7584                                       unsigned specifierLen) {
7585   const analyze_printf::PrintfConversionSpecifier &CS =
7586     FS.getConversionSpecifier();
7587 
7588   FixItHint fixit =
7589     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7590       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7591                                  Amt.getConstantLength()))
7592       : FixItHint();
7593 
7594   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7595                          << type << CS.toString(),
7596                        getLocationOfByte(Amt.getStart()),
7597                        /*IsStringLocation*/true,
7598                        getSpecifierRange(startSpecifier, specifierLen),
7599                        fixit);
7600 }
7601 
7602 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7603                                     const analyze_printf::OptionalFlag &flag,
7604                                     const char *startSpecifier,
7605                                     unsigned specifierLen) {
7606   // Warn about pointless flag with a fixit removal.
7607   const analyze_printf::PrintfConversionSpecifier &CS =
7608     FS.getConversionSpecifier();
7609   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7610                          << flag.toString() << CS.toString(),
7611                        getLocationOfByte(flag.getPosition()),
7612                        /*IsStringLocation*/true,
7613                        getSpecifierRange(startSpecifier, specifierLen),
7614                        FixItHint::CreateRemoval(
7615                          getSpecifierRange(flag.getPosition(), 1)));
7616 }
7617 
7618 void CheckPrintfHandler::HandleIgnoredFlag(
7619                                 const analyze_printf::PrintfSpecifier &FS,
7620                                 const analyze_printf::OptionalFlag &ignoredFlag,
7621                                 const analyze_printf::OptionalFlag &flag,
7622                                 const char *startSpecifier,
7623                                 unsigned specifierLen) {
7624   // Warn about ignored flag with a fixit removal.
7625   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7626                          << ignoredFlag.toString() << flag.toString(),
7627                        getLocationOfByte(ignoredFlag.getPosition()),
7628                        /*IsStringLocation*/true,
7629                        getSpecifierRange(startSpecifier, specifierLen),
7630                        FixItHint::CreateRemoval(
7631                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7632 }
7633 
7634 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7635                                                      unsigned flagLen) {
7636   // Warn about an empty flag.
7637   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7638                        getLocationOfByte(startFlag),
7639                        /*IsStringLocation*/true,
7640                        getSpecifierRange(startFlag, flagLen));
7641 }
7642 
7643 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7644                                                        unsigned flagLen) {
7645   // Warn about an invalid flag.
7646   auto Range = getSpecifierRange(startFlag, flagLen);
7647   StringRef flag(startFlag, flagLen);
7648   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7649                       getLocationOfByte(startFlag),
7650                       /*IsStringLocation*/true,
7651                       Range, FixItHint::CreateRemoval(Range));
7652 }
7653 
7654 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7655     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7656     // Warn about using '[...]' without a '@' conversion.
7657     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7658     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7659     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7660                          getLocationOfByte(conversionPosition),
7661                          /*IsStringLocation*/true,
7662                          Range, FixItHint::CreateRemoval(Range));
7663 }
7664 
7665 // Determines if the specified is a C++ class or struct containing
7666 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7667 // "c_str()").
7668 template<typename MemberKind>
7669 static llvm::SmallPtrSet<MemberKind*, 1>
7670 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7671   const RecordType *RT = Ty->getAs<RecordType>();
7672   llvm::SmallPtrSet<MemberKind*, 1> Results;
7673 
7674   if (!RT)
7675     return Results;
7676   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7677   if (!RD || !RD->getDefinition())
7678     return Results;
7679 
7680   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7681                  Sema::LookupMemberName);
7682   R.suppressDiagnostics();
7683 
7684   // We just need to include all members of the right kind turned up by the
7685   // filter, at this point.
7686   if (S.LookupQualifiedName(R, RT->getDecl()))
7687     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7688       NamedDecl *decl = (*I)->getUnderlyingDecl();
7689       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7690         Results.insert(FK);
7691     }
7692   return Results;
7693 }
7694 
7695 /// Check if we could call '.c_str()' on an object.
7696 ///
7697 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7698 /// allow the call, or if it would be ambiguous).
7699 bool Sema::hasCStrMethod(const Expr *E) {
7700   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7701 
7702   MethodSet Results =
7703       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7704   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7705        MI != ME; ++MI)
7706     if ((*MI)->getMinRequiredArguments() == 0)
7707       return true;
7708   return false;
7709 }
7710 
7711 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7712 // better diagnostic if so. AT is assumed to be valid.
7713 // Returns true when a c_str() conversion method is found.
7714 bool CheckPrintfHandler::checkForCStrMembers(
7715     const analyze_printf::ArgType &AT, const Expr *E) {
7716   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7717 
7718   MethodSet Results =
7719       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7720 
7721   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7722        MI != ME; ++MI) {
7723     const CXXMethodDecl *Method = *MI;
7724     if (Method->getMinRequiredArguments() == 0 &&
7725         AT.matchesType(S.Context, Method->getReturnType())) {
7726       // FIXME: Suggest parens if the expression needs them.
7727       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7728       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7729           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7730       return true;
7731     }
7732   }
7733 
7734   return false;
7735 }
7736 
7737 bool
7738 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7739                                             &FS,
7740                                           const char *startSpecifier,
7741                                           unsigned specifierLen) {
7742   using namespace analyze_format_string;
7743   using namespace analyze_printf;
7744 
7745   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7746 
7747   if (FS.consumesDataArgument()) {
7748     if (atFirstArg) {
7749         atFirstArg = false;
7750         usesPositionalArgs = FS.usesPositionalArg();
7751     }
7752     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7753       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7754                                         startSpecifier, specifierLen);
7755       return false;
7756     }
7757   }
7758 
7759   // First check if the field width, precision, and conversion specifier
7760   // have matching data arguments.
7761   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7762                     startSpecifier, specifierLen)) {
7763     return false;
7764   }
7765 
7766   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7767                     startSpecifier, specifierLen)) {
7768     return false;
7769   }
7770 
7771   if (!CS.consumesDataArgument()) {
7772     // FIXME: Technically specifying a precision or field width here
7773     // makes no sense.  Worth issuing a warning at some point.
7774     return true;
7775   }
7776 
7777   // Consume the argument.
7778   unsigned argIndex = FS.getArgIndex();
7779   if (argIndex < NumDataArgs) {
7780     // The check to see if the argIndex is valid will come later.
7781     // We set the bit here because we may exit early from this
7782     // function if we encounter some other error.
7783     CoveredArgs.set(argIndex);
7784   }
7785 
7786   // FreeBSD kernel extensions.
7787   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7788       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7789     // We need at least two arguments.
7790     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7791       return false;
7792 
7793     // Claim the second argument.
7794     CoveredArgs.set(argIndex + 1);
7795 
7796     // Type check the first argument (int for %b, pointer for %D)
7797     const Expr *Ex = getDataArg(argIndex);
7798     const analyze_printf::ArgType &AT =
7799       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7800         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7801     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7802       EmitFormatDiagnostic(
7803           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7804               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7805               << false << Ex->getSourceRange(),
7806           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7807           getSpecifierRange(startSpecifier, specifierLen));
7808 
7809     // Type check the second argument (char * for both %b and %D)
7810     Ex = getDataArg(argIndex + 1);
7811     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7812     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7813       EmitFormatDiagnostic(
7814           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7815               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7816               << false << Ex->getSourceRange(),
7817           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7818           getSpecifierRange(startSpecifier, specifierLen));
7819 
7820      return true;
7821   }
7822 
7823   // Check for using an Objective-C specific conversion specifier
7824   // in a non-ObjC literal.
7825   if (!allowsObjCArg() && CS.isObjCArg()) {
7826     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7827                                                   specifierLen);
7828   }
7829 
7830   // %P can only be used with os_log.
7831   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7832     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7833                                                   specifierLen);
7834   }
7835 
7836   // %n is not allowed with os_log.
7837   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7838     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7839                          getLocationOfByte(CS.getStart()),
7840                          /*IsStringLocation*/ false,
7841                          getSpecifierRange(startSpecifier, specifierLen));
7842 
7843     return true;
7844   }
7845 
7846   // Only scalars are allowed for os_trace.
7847   if (FSType == Sema::FST_OSTrace &&
7848       (CS.getKind() == ConversionSpecifier::PArg ||
7849        CS.getKind() == ConversionSpecifier::sArg ||
7850        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7851     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7852                                                   specifierLen);
7853   }
7854 
7855   // Check for use of public/private annotation outside of os_log().
7856   if (FSType != Sema::FST_OSLog) {
7857     if (FS.isPublic().isSet()) {
7858       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7859                                << "public",
7860                            getLocationOfByte(FS.isPublic().getPosition()),
7861                            /*IsStringLocation*/ false,
7862                            getSpecifierRange(startSpecifier, specifierLen));
7863     }
7864     if (FS.isPrivate().isSet()) {
7865       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7866                                << "private",
7867                            getLocationOfByte(FS.isPrivate().getPosition()),
7868                            /*IsStringLocation*/ false,
7869                            getSpecifierRange(startSpecifier, specifierLen));
7870     }
7871   }
7872 
7873   // Check for invalid use of field width
7874   if (!FS.hasValidFieldWidth()) {
7875     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7876         startSpecifier, specifierLen);
7877   }
7878 
7879   // Check for invalid use of precision
7880   if (!FS.hasValidPrecision()) {
7881     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7882         startSpecifier, specifierLen);
7883   }
7884 
7885   // Precision is mandatory for %P specifier.
7886   if (CS.getKind() == ConversionSpecifier::PArg &&
7887       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7888     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7889                          getLocationOfByte(startSpecifier),
7890                          /*IsStringLocation*/ false,
7891                          getSpecifierRange(startSpecifier, specifierLen));
7892   }
7893 
7894   // Check each flag does not conflict with any other component.
7895   if (!FS.hasValidThousandsGroupingPrefix())
7896     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7897   if (!FS.hasValidLeadingZeros())
7898     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7899   if (!FS.hasValidPlusPrefix())
7900     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7901   if (!FS.hasValidSpacePrefix())
7902     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7903   if (!FS.hasValidAlternativeForm())
7904     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7905   if (!FS.hasValidLeftJustified())
7906     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7907 
7908   // Check that flags are not ignored by another flag
7909   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7910     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7911         startSpecifier, specifierLen);
7912   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7913     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7914             startSpecifier, specifierLen);
7915 
7916   // Check the length modifier is valid with the given conversion specifier.
7917   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7918                                  S.getLangOpts()))
7919     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7920                                 diag::warn_format_nonsensical_length);
7921   else if (!FS.hasStandardLengthModifier())
7922     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7923   else if (!FS.hasStandardLengthConversionCombination())
7924     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7925                                 diag::warn_format_non_standard_conversion_spec);
7926 
7927   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7928     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7929 
7930   // The remaining checks depend on the data arguments.
7931   if (HasVAListArg)
7932     return true;
7933 
7934   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7935     return false;
7936 
7937   const Expr *Arg = getDataArg(argIndex);
7938   if (!Arg)
7939     return true;
7940 
7941   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7942 }
7943 
7944 static bool requiresParensToAddCast(const Expr *E) {
7945   // FIXME: We should have a general way to reason about operator
7946   // precedence and whether parens are actually needed here.
7947   // Take care of a few common cases where they aren't.
7948   const Expr *Inside = E->IgnoreImpCasts();
7949   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7950     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7951 
7952   switch (Inside->getStmtClass()) {
7953   case Stmt::ArraySubscriptExprClass:
7954   case Stmt::CallExprClass:
7955   case Stmt::CharacterLiteralClass:
7956   case Stmt::CXXBoolLiteralExprClass:
7957   case Stmt::DeclRefExprClass:
7958   case Stmt::FloatingLiteralClass:
7959   case Stmt::IntegerLiteralClass:
7960   case Stmt::MemberExprClass:
7961   case Stmt::ObjCArrayLiteralClass:
7962   case Stmt::ObjCBoolLiteralExprClass:
7963   case Stmt::ObjCBoxedExprClass:
7964   case Stmt::ObjCDictionaryLiteralClass:
7965   case Stmt::ObjCEncodeExprClass:
7966   case Stmt::ObjCIvarRefExprClass:
7967   case Stmt::ObjCMessageExprClass:
7968   case Stmt::ObjCPropertyRefExprClass:
7969   case Stmt::ObjCStringLiteralClass:
7970   case Stmt::ObjCSubscriptRefExprClass:
7971   case Stmt::ParenExprClass:
7972   case Stmt::StringLiteralClass:
7973   case Stmt::UnaryOperatorClass:
7974     return false;
7975   default:
7976     return true;
7977   }
7978 }
7979 
7980 static std::pair<QualType, StringRef>
7981 shouldNotPrintDirectly(const ASTContext &Context,
7982                        QualType IntendedTy,
7983                        const Expr *E) {
7984   // Use a 'while' to peel off layers of typedefs.
7985   QualType TyTy = IntendedTy;
7986   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7987     StringRef Name = UserTy->getDecl()->getName();
7988     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7989       .Case("CFIndex", Context.getNSIntegerType())
7990       .Case("NSInteger", Context.getNSIntegerType())
7991       .Case("NSUInteger", Context.getNSUIntegerType())
7992       .Case("SInt32", Context.IntTy)
7993       .Case("UInt32", Context.UnsignedIntTy)
7994       .Default(QualType());
7995 
7996     if (!CastTy.isNull())
7997       return std::make_pair(CastTy, Name);
7998 
7999     TyTy = UserTy->desugar();
8000   }
8001 
8002   // Strip parens if necessary.
8003   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8004     return shouldNotPrintDirectly(Context,
8005                                   PE->getSubExpr()->getType(),
8006                                   PE->getSubExpr());
8007 
8008   // If this is a conditional expression, then its result type is constructed
8009   // via usual arithmetic conversions and thus there might be no necessary
8010   // typedef sugar there.  Recurse to operands to check for NSInteger &
8011   // Co. usage condition.
8012   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8013     QualType TrueTy, FalseTy;
8014     StringRef TrueName, FalseName;
8015 
8016     std::tie(TrueTy, TrueName) =
8017       shouldNotPrintDirectly(Context,
8018                              CO->getTrueExpr()->getType(),
8019                              CO->getTrueExpr());
8020     std::tie(FalseTy, FalseName) =
8021       shouldNotPrintDirectly(Context,
8022                              CO->getFalseExpr()->getType(),
8023                              CO->getFalseExpr());
8024 
8025     if (TrueTy == FalseTy)
8026       return std::make_pair(TrueTy, TrueName);
8027     else if (TrueTy.isNull())
8028       return std::make_pair(FalseTy, FalseName);
8029     else if (FalseTy.isNull())
8030       return std::make_pair(TrueTy, TrueName);
8031   }
8032 
8033   return std::make_pair(QualType(), StringRef());
8034 }
8035 
8036 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8037 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8038 /// type do not count.
8039 static bool
8040 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8041   QualType From = ICE->getSubExpr()->getType();
8042   QualType To = ICE->getType();
8043   // It's an integer promotion if the destination type is the promoted
8044   // source type.
8045   if (ICE->getCastKind() == CK_IntegralCast &&
8046       From->isPromotableIntegerType() &&
8047       S.Context.getPromotedIntegerType(From) == To)
8048     return true;
8049   // Look through vector types, since we do default argument promotion for
8050   // those in OpenCL.
8051   if (const auto *VecTy = From->getAs<ExtVectorType>())
8052     From = VecTy->getElementType();
8053   if (const auto *VecTy = To->getAs<ExtVectorType>())
8054     To = VecTy->getElementType();
8055   // It's a floating promotion if the source type is a lower rank.
8056   return ICE->getCastKind() == CK_FloatingCast &&
8057          S.Context.getFloatingTypeOrder(From, To) < 0;
8058 }
8059 
8060 bool
8061 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8062                                     const char *StartSpecifier,
8063                                     unsigned SpecifierLen,
8064                                     const Expr *E) {
8065   using namespace analyze_format_string;
8066   using namespace analyze_printf;
8067 
8068   // Now type check the data expression that matches the
8069   // format specifier.
8070   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8071   if (!AT.isValid())
8072     return true;
8073 
8074   QualType ExprTy = E->getType();
8075   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8076     ExprTy = TET->getUnderlyingExpr()->getType();
8077   }
8078 
8079   const analyze_printf::ArgType::MatchKind Match =
8080       AT.matchesType(S.Context, ExprTy);
8081   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
8082   if (Match == analyze_printf::ArgType::Match)
8083     return true;
8084 
8085   // Look through argument promotions for our error message's reported type.
8086   // This includes the integral and floating promotions, but excludes array
8087   // and function pointer decay (seeing that an argument intended to be a
8088   // string has type 'char [6]' is probably more confusing than 'char *') and
8089   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8090   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8091     if (isArithmeticArgumentPromotion(S, ICE)) {
8092       E = ICE->getSubExpr();
8093       ExprTy = E->getType();
8094 
8095       // Check if we didn't match because of an implicit cast from a 'char'
8096       // or 'short' to an 'int'.  This is done because printf is a varargs
8097       // function.
8098       if (ICE->getType() == S.Context.IntTy ||
8099           ICE->getType() == S.Context.UnsignedIntTy) {
8100         // All further checking is done on the subexpression.
8101         if (AT.matchesType(S.Context, ExprTy))
8102           return true;
8103       }
8104     }
8105   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8106     // Special case for 'a', which has type 'int' in C.
8107     // Note, however, that we do /not/ want to treat multibyte constants like
8108     // 'MooV' as characters! This form is deprecated but still exists.
8109     if (ExprTy == S.Context.IntTy)
8110       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8111         ExprTy = S.Context.CharTy;
8112   }
8113 
8114   // Look through enums to their underlying type.
8115   bool IsEnum = false;
8116   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8117     ExprTy = EnumTy->getDecl()->getIntegerType();
8118     IsEnum = true;
8119   }
8120 
8121   // %C in an Objective-C context prints a unichar, not a wchar_t.
8122   // If the argument is an integer of some kind, believe the %C and suggest
8123   // a cast instead of changing the conversion specifier.
8124   QualType IntendedTy = ExprTy;
8125   if (isObjCContext() &&
8126       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8127     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8128         !ExprTy->isCharType()) {
8129       // 'unichar' is defined as a typedef of unsigned short, but we should
8130       // prefer using the typedef if it is visible.
8131       IntendedTy = S.Context.UnsignedShortTy;
8132 
8133       // While we are here, check if the value is an IntegerLiteral that happens
8134       // to be within the valid range.
8135       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8136         const llvm::APInt &V = IL->getValue();
8137         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8138           return true;
8139       }
8140 
8141       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8142                           Sema::LookupOrdinaryName);
8143       if (S.LookupName(Result, S.getCurScope())) {
8144         NamedDecl *ND = Result.getFoundDecl();
8145         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8146           if (TD->getUnderlyingType() == IntendedTy)
8147             IntendedTy = S.Context.getTypedefType(TD);
8148       }
8149     }
8150   }
8151 
8152   // Special-case some of Darwin's platform-independence types by suggesting
8153   // casts to primitive types that are known to be large enough.
8154   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8155   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8156     QualType CastTy;
8157     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8158     if (!CastTy.isNull()) {
8159       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8160       // (long in ASTContext). Only complain to pedants.
8161       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8162           (AT.isSizeT() || AT.isPtrdiffT()) &&
8163           AT.matchesType(S.Context, CastTy))
8164         Pedantic = true;
8165       IntendedTy = CastTy;
8166       ShouldNotPrintDirectly = true;
8167     }
8168   }
8169 
8170   // We may be able to offer a FixItHint if it is a supported type.
8171   PrintfSpecifier fixedFS = FS;
8172   bool Success =
8173       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8174 
8175   if (Success) {
8176     // Get the fix string from the fixed format specifier
8177     SmallString<16> buf;
8178     llvm::raw_svector_ostream os(buf);
8179     fixedFS.toString(os);
8180 
8181     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8182 
8183     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8184       unsigned Diag =
8185           Pedantic
8186               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8187               : diag::warn_format_conversion_argument_type_mismatch;
8188       // In this case, the specifier is wrong and should be changed to match
8189       // the argument.
8190       EmitFormatDiagnostic(S.PDiag(Diag)
8191                                << AT.getRepresentativeTypeName(S.Context)
8192                                << IntendedTy << IsEnum << E->getSourceRange(),
8193                            E->getBeginLoc(),
8194                            /*IsStringLocation*/ false, SpecRange,
8195                            FixItHint::CreateReplacement(SpecRange, os.str()));
8196     } else {
8197       // The canonical type for formatting this value is different from the
8198       // actual type of the expression. (This occurs, for example, with Darwin's
8199       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8200       // should be printed as 'long' for 64-bit compatibility.)
8201       // Rather than emitting a normal format/argument mismatch, we want to
8202       // add a cast to the recommended type (and correct the format string
8203       // if necessary).
8204       SmallString<16> CastBuf;
8205       llvm::raw_svector_ostream CastFix(CastBuf);
8206       CastFix << "(";
8207       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8208       CastFix << ")";
8209 
8210       SmallVector<FixItHint,4> Hints;
8211       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8212         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8213 
8214       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8215         // If there's already a cast present, just replace it.
8216         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8217         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8218 
8219       } else if (!requiresParensToAddCast(E)) {
8220         // If the expression has high enough precedence,
8221         // just write the C-style cast.
8222         Hints.push_back(
8223             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8224       } else {
8225         // Otherwise, add parens around the expression as well as the cast.
8226         CastFix << "(";
8227         Hints.push_back(
8228             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8229 
8230         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8231         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8232       }
8233 
8234       if (ShouldNotPrintDirectly) {
8235         // The expression has a type that should not be printed directly.
8236         // We extract the name from the typedef because we don't want to show
8237         // the underlying type in the diagnostic.
8238         StringRef Name;
8239         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8240           Name = TypedefTy->getDecl()->getName();
8241         else
8242           Name = CastTyName;
8243         unsigned Diag = Pedantic
8244                             ? diag::warn_format_argument_needs_cast_pedantic
8245                             : diag::warn_format_argument_needs_cast;
8246         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8247                                            << E->getSourceRange(),
8248                              E->getBeginLoc(), /*IsStringLocation=*/false,
8249                              SpecRange, Hints);
8250       } else {
8251         // In this case, the expression could be printed using a different
8252         // specifier, but we've decided that the specifier is probably correct
8253         // and we should cast instead. Just use the normal warning message.
8254         EmitFormatDiagnostic(
8255             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8256                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8257                 << E->getSourceRange(),
8258             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8259       }
8260     }
8261   } else {
8262     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8263                                                    SpecifierLen);
8264     // Since the warning for passing non-POD types to variadic functions
8265     // was deferred until now, we emit a warning for non-POD
8266     // arguments here.
8267     switch (S.isValidVarArgType(ExprTy)) {
8268     case Sema::VAK_Valid:
8269     case Sema::VAK_ValidInCXX11: {
8270       unsigned Diag =
8271           Pedantic
8272               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8273               : diag::warn_format_conversion_argument_type_mismatch;
8274 
8275       EmitFormatDiagnostic(
8276           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8277                         << IsEnum << CSR << E->getSourceRange(),
8278           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8279       break;
8280     }
8281     case Sema::VAK_Undefined:
8282     case Sema::VAK_MSVCUndefined:
8283       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8284                                << S.getLangOpts().CPlusPlus11 << ExprTy
8285                                << CallType
8286                                << AT.getRepresentativeTypeName(S.Context) << CSR
8287                                << E->getSourceRange(),
8288                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8289       checkForCStrMembers(AT, E);
8290       break;
8291 
8292     case Sema::VAK_Invalid:
8293       if (ExprTy->isObjCObjectType())
8294         EmitFormatDiagnostic(
8295             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8296                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8297                 << AT.getRepresentativeTypeName(S.Context) << CSR
8298                 << E->getSourceRange(),
8299             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8300       else
8301         // FIXME: If this is an initializer list, suggest removing the braces
8302         // or inserting a cast to the target type.
8303         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8304             << isa<InitListExpr>(E) << ExprTy << CallType
8305             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8306       break;
8307     }
8308 
8309     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8310            "format string specifier index out of range");
8311     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8312   }
8313 
8314   return true;
8315 }
8316 
8317 //===--- CHECK: Scanf format string checking ------------------------------===//
8318 
8319 namespace {
8320 
8321 class CheckScanfHandler : public CheckFormatHandler {
8322 public:
8323   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8324                     const Expr *origFormatExpr, Sema::FormatStringType type,
8325                     unsigned firstDataArg, unsigned numDataArgs,
8326                     const char *beg, bool hasVAListArg,
8327                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8328                     bool inFunctionCall, Sema::VariadicCallType CallType,
8329                     llvm::SmallBitVector &CheckedVarArgs,
8330                     UncoveredArgHandler &UncoveredArg)
8331       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8332                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8333                            inFunctionCall, CallType, CheckedVarArgs,
8334                            UncoveredArg) {}
8335 
8336   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8337                             const char *startSpecifier,
8338                             unsigned specifierLen) override;
8339 
8340   bool HandleInvalidScanfConversionSpecifier(
8341           const analyze_scanf::ScanfSpecifier &FS,
8342           const char *startSpecifier,
8343           unsigned specifierLen) override;
8344 
8345   void HandleIncompleteScanList(const char *start, const char *end) override;
8346 };
8347 
8348 } // namespace
8349 
8350 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8351                                                  const char *end) {
8352   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8353                        getLocationOfByte(end), /*IsStringLocation*/true,
8354                        getSpecifierRange(start, end - start));
8355 }
8356 
8357 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8358                                         const analyze_scanf::ScanfSpecifier &FS,
8359                                         const char *startSpecifier,
8360                                         unsigned specifierLen) {
8361   const analyze_scanf::ScanfConversionSpecifier &CS =
8362     FS.getConversionSpecifier();
8363 
8364   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8365                                           getLocationOfByte(CS.getStart()),
8366                                           startSpecifier, specifierLen,
8367                                           CS.getStart(), CS.getLength());
8368 }
8369 
8370 bool CheckScanfHandler::HandleScanfSpecifier(
8371                                        const analyze_scanf::ScanfSpecifier &FS,
8372                                        const char *startSpecifier,
8373                                        unsigned specifierLen) {
8374   using namespace analyze_scanf;
8375   using namespace analyze_format_string;
8376 
8377   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8378 
8379   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8380   // be used to decide if we are using positional arguments consistently.
8381   if (FS.consumesDataArgument()) {
8382     if (atFirstArg) {
8383       atFirstArg = false;
8384       usesPositionalArgs = FS.usesPositionalArg();
8385     }
8386     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8387       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8388                                         startSpecifier, specifierLen);
8389       return false;
8390     }
8391   }
8392 
8393   // Check if the field with is non-zero.
8394   const OptionalAmount &Amt = FS.getFieldWidth();
8395   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8396     if (Amt.getConstantAmount() == 0) {
8397       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8398                                                    Amt.getConstantLength());
8399       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8400                            getLocationOfByte(Amt.getStart()),
8401                            /*IsStringLocation*/true, R,
8402                            FixItHint::CreateRemoval(R));
8403     }
8404   }
8405 
8406   if (!FS.consumesDataArgument()) {
8407     // FIXME: Technically specifying a precision or field width here
8408     // makes no sense.  Worth issuing a warning at some point.
8409     return true;
8410   }
8411 
8412   // Consume the argument.
8413   unsigned argIndex = FS.getArgIndex();
8414   if (argIndex < NumDataArgs) {
8415       // The check to see if the argIndex is valid will come later.
8416       // We set the bit here because we may exit early from this
8417       // function if we encounter some other error.
8418     CoveredArgs.set(argIndex);
8419   }
8420 
8421   // Check the length modifier is valid with the given conversion specifier.
8422   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8423                                  S.getLangOpts()))
8424     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8425                                 diag::warn_format_nonsensical_length);
8426   else if (!FS.hasStandardLengthModifier())
8427     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8428   else if (!FS.hasStandardLengthConversionCombination())
8429     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8430                                 diag::warn_format_non_standard_conversion_spec);
8431 
8432   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8433     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8434 
8435   // The remaining checks depend on the data arguments.
8436   if (HasVAListArg)
8437     return true;
8438 
8439   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8440     return false;
8441 
8442   // Check that the argument type matches the format specifier.
8443   const Expr *Ex = getDataArg(argIndex);
8444   if (!Ex)
8445     return true;
8446 
8447   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8448 
8449   if (!AT.isValid()) {
8450     return true;
8451   }
8452 
8453   analyze_format_string::ArgType::MatchKind Match =
8454       AT.matchesType(S.Context, Ex->getType());
8455   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8456   if (Match == analyze_format_string::ArgType::Match)
8457     return true;
8458 
8459   ScanfSpecifier fixedFS = FS;
8460   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8461                                  S.getLangOpts(), S.Context);
8462 
8463   unsigned Diag =
8464       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8465                : diag::warn_format_conversion_argument_type_mismatch;
8466 
8467   if (Success) {
8468     // Get the fix string from the fixed format specifier.
8469     SmallString<128> buf;
8470     llvm::raw_svector_ostream os(buf);
8471     fixedFS.toString(os);
8472 
8473     EmitFormatDiagnostic(
8474         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8475                       << Ex->getType() << false << Ex->getSourceRange(),
8476         Ex->getBeginLoc(),
8477         /*IsStringLocation*/ false,
8478         getSpecifierRange(startSpecifier, specifierLen),
8479         FixItHint::CreateReplacement(
8480             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8481   } else {
8482     EmitFormatDiagnostic(S.PDiag(Diag)
8483                              << AT.getRepresentativeTypeName(S.Context)
8484                              << Ex->getType() << false << Ex->getSourceRange(),
8485                          Ex->getBeginLoc(),
8486                          /*IsStringLocation*/ false,
8487                          getSpecifierRange(startSpecifier, specifierLen));
8488   }
8489 
8490   return true;
8491 }
8492 
8493 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8494                               const Expr *OrigFormatExpr,
8495                               ArrayRef<const Expr *> Args,
8496                               bool HasVAListArg, unsigned format_idx,
8497                               unsigned firstDataArg,
8498                               Sema::FormatStringType Type,
8499                               bool inFunctionCall,
8500                               Sema::VariadicCallType CallType,
8501                               llvm::SmallBitVector &CheckedVarArgs,
8502                               UncoveredArgHandler &UncoveredArg) {
8503   // CHECK: is the format string a wide literal?
8504   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8505     CheckFormatHandler::EmitFormatDiagnostic(
8506         S, inFunctionCall, Args[format_idx],
8507         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8508         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8509     return;
8510   }
8511 
8512   // Str - The format string.  NOTE: this is NOT null-terminated!
8513   StringRef StrRef = FExpr->getString();
8514   const char *Str = StrRef.data();
8515   // Account for cases where the string literal is truncated in a declaration.
8516   const ConstantArrayType *T =
8517     S.Context.getAsConstantArrayType(FExpr->getType());
8518   assert(T && "String literal not of constant array type!");
8519   size_t TypeSize = T->getSize().getZExtValue();
8520   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8521   const unsigned numDataArgs = Args.size() - firstDataArg;
8522 
8523   // Emit a warning if the string literal is truncated and does not contain an
8524   // embedded null character.
8525   if (TypeSize <= StrRef.size() &&
8526       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8527     CheckFormatHandler::EmitFormatDiagnostic(
8528         S, inFunctionCall, Args[format_idx],
8529         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8530         FExpr->getBeginLoc(),
8531         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8532     return;
8533   }
8534 
8535   // CHECK: empty format string?
8536   if (StrLen == 0 && numDataArgs > 0) {
8537     CheckFormatHandler::EmitFormatDiagnostic(
8538         S, inFunctionCall, Args[format_idx],
8539         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8540         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8541     return;
8542   }
8543 
8544   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8545       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8546       Type == Sema::FST_OSTrace) {
8547     CheckPrintfHandler H(
8548         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8549         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8550         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8551         CheckedVarArgs, UncoveredArg);
8552 
8553     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8554                                                   S.getLangOpts(),
8555                                                   S.Context.getTargetInfo(),
8556                                             Type == Sema::FST_FreeBSDKPrintf))
8557       H.DoneProcessing();
8558   } else if (Type == Sema::FST_Scanf) {
8559     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8560                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8561                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8562 
8563     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8564                                                  S.getLangOpts(),
8565                                                  S.Context.getTargetInfo()))
8566       H.DoneProcessing();
8567   } // TODO: handle other formats
8568 }
8569 
8570 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8571   // Str - The format string.  NOTE: this is NOT null-terminated!
8572   StringRef StrRef = FExpr->getString();
8573   const char *Str = StrRef.data();
8574   // Account for cases where the string literal is truncated in a declaration.
8575   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8576   assert(T && "String literal not of constant array type!");
8577   size_t TypeSize = T->getSize().getZExtValue();
8578   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8579   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8580                                                          getLangOpts(),
8581                                                          Context.getTargetInfo());
8582 }
8583 
8584 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8585 
8586 // Returns the related absolute value function that is larger, of 0 if one
8587 // does not exist.
8588 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8589   switch (AbsFunction) {
8590   default:
8591     return 0;
8592 
8593   case Builtin::BI__builtin_abs:
8594     return Builtin::BI__builtin_labs;
8595   case Builtin::BI__builtin_labs:
8596     return Builtin::BI__builtin_llabs;
8597   case Builtin::BI__builtin_llabs:
8598     return 0;
8599 
8600   case Builtin::BI__builtin_fabsf:
8601     return Builtin::BI__builtin_fabs;
8602   case Builtin::BI__builtin_fabs:
8603     return Builtin::BI__builtin_fabsl;
8604   case Builtin::BI__builtin_fabsl:
8605     return 0;
8606 
8607   case Builtin::BI__builtin_cabsf:
8608     return Builtin::BI__builtin_cabs;
8609   case Builtin::BI__builtin_cabs:
8610     return Builtin::BI__builtin_cabsl;
8611   case Builtin::BI__builtin_cabsl:
8612     return 0;
8613 
8614   case Builtin::BIabs:
8615     return Builtin::BIlabs;
8616   case Builtin::BIlabs:
8617     return Builtin::BIllabs;
8618   case Builtin::BIllabs:
8619     return 0;
8620 
8621   case Builtin::BIfabsf:
8622     return Builtin::BIfabs;
8623   case Builtin::BIfabs:
8624     return Builtin::BIfabsl;
8625   case Builtin::BIfabsl:
8626     return 0;
8627 
8628   case Builtin::BIcabsf:
8629    return Builtin::BIcabs;
8630   case Builtin::BIcabs:
8631     return Builtin::BIcabsl;
8632   case Builtin::BIcabsl:
8633     return 0;
8634   }
8635 }
8636 
8637 // Returns the argument type of the absolute value function.
8638 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8639                                              unsigned AbsType) {
8640   if (AbsType == 0)
8641     return QualType();
8642 
8643   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8644   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8645   if (Error != ASTContext::GE_None)
8646     return QualType();
8647 
8648   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8649   if (!FT)
8650     return QualType();
8651 
8652   if (FT->getNumParams() != 1)
8653     return QualType();
8654 
8655   return FT->getParamType(0);
8656 }
8657 
8658 // Returns the best absolute value function, or zero, based on type and
8659 // current absolute value function.
8660 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8661                                    unsigned AbsFunctionKind) {
8662   unsigned BestKind = 0;
8663   uint64_t ArgSize = Context.getTypeSize(ArgType);
8664   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8665        Kind = getLargerAbsoluteValueFunction(Kind)) {
8666     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8667     if (Context.getTypeSize(ParamType) >= ArgSize) {
8668       if (BestKind == 0)
8669         BestKind = Kind;
8670       else if (Context.hasSameType(ParamType, ArgType)) {
8671         BestKind = Kind;
8672         break;
8673       }
8674     }
8675   }
8676   return BestKind;
8677 }
8678 
8679 enum AbsoluteValueKind {
8680   AVK_Integer,
8681   AVK_Floating,
8682   AVK_Complex
8683 };
8684 
8685 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8686   if (T->isIntegralOrEnumerationType())
8687     return AVK_Integer;
8688   if (T->isRealFloatingType())
8689     return AVK_Floating;
8690   if (T->isAnyComplexType())
8691     return AVK_Complex;
8692 
8693   llvm_unreachable("Type not integer, floating, or complex");
8694 }
8695 
8696 // Changes the absolute value function to a different type.  Preserves whether
8697 // the function is a builtin.
8698 static unsigned changeAbsFunction(unsigned AbsKind,
8699                                   AbsoluteValueKind ValueKind) {
8700   switch (ValueKind) {
8701   case AVK_Integer:
8702     switch (AbsKind) {
8703     default:
8704       return 0;
8705     case Builtin::BI__builtin_fabsf:
8706     case Builtin::BI__builtin_fabs:
8707     case Builtin::BI__builtin_fabsl:
8708     case Builtin::BI__builtin_cabsf:
8709     case Builtin::BI__builtin_cabs:
8710     case Builtin::BI__builtin_cabsl:
8711       return Builtin::BI__builtin_abs;
8712     case Builtin::BIfabsf:
8713     case Builtin::BIfabs:
8714     case Builtin::BIfabsl:
8715     case Builtin::BIcabsf:
8716     case Builtin::BIcabs:
8717     case Builtin::BIcabsl:
8718       return Builtin::BIabs;
8719     }
8720   case AVK_Floating:
8721     switch (AbsKind) {
8722     default:
8723       return 0;
8724     case Builtin::BI__builtin_abs:
8725     case Builtin::BI__builtin_labs:
8726     case Builtin::BI__builtin_llabs:
8727     case Builtin::BI__builtin_cabsf:
8728     case Builtin::BI__builtin_cabs:
8729     case Builtin::BI__builtin_cabsl:
8730       return Builtin::BI__builtin_fabsf;
8731     case Builtin::BIabs:
8732     case Builtin::BIlabs:
8733     case Builtin::BIllabs:
8734     case Builtin::BIcabsf:
8735     case Builtin::BIcabs:
8736     case Builtin::BIcabsl:
8737       return Builtin::BIfabsf;
8738     }
8739   case AVK_Complex:
8740     switch (AbsKind) {
8741     default:
8742       return 0;
8743     case Builtin::BI__builtin_abs:
8744     case Builtin::BI__builtin_labs:
8745     case Builtin::BI__builtin_llabs:
8746     case Builtin::BI__builtin_fabsf:
8747     case Builtin::BI__builtin_fabs:
8748     case Builtin::BI__builtin_fabsl:
8749       return Builtin::BI__builtin_cabsf;
8750     case Builtin::BIabs:
8751     case Builtin::BIlabs:
8752     case Builtin::BIllabs:
8753     case Builtin::BIfabsf:
8754     case Builtin::BIfabs:
8755     case Builtin::BIfabsl:
8756       return Builtin::BIcabsf;
8757     }
8758   }
8759   llvm_unreachable("Unable to convert function");
8760 }
8761 
8762 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8763   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8764   if (!FnInfo)
8765     return 0;
8766 
8767   switch (FDecl->getBuiltinID()) {
8768   default:
8769     return 0;
8770   case Builtin::BI__builtin_abs:
8771   case Builtin::BI__builtin_fabs:
8772   case Builtin::BI__builtin_fabsf:
8773   case Builtin::BI__builtin_fabsl:
8774   case Builtin::BI__builtin_labs:
8775   case Builtin::BI__builtin_llabs:
8776   case Builtin::BI__builtin_cabs:
8777   case Builtin::BI__builtin_cabsf:
8778   case Builtin::BI__builtin_cabsl:
8779   case Builtin::BIabs:
8780   case Builtin::BIlabs:
8781   case Builtin::BIllabs:
8782   case Builtin::BIfabs:
8783   case Builtin::BIfabsf:
8784   case Builtin::BIfabsl:
8785   case Builtin::BIcabs:
8786   case Builtin::BIcabsf:
8787   case Builtin::BIcabsl:
8788     return FDecl->getBuiltinID();
8789   }
8790   llvm_unreachable("Unknown Builtin type");
8791 }
8792 
8793 // If the replacement is valid, emit a note with replacement function.
8794 // Additionally, suggest including the proper header if not already included.
8795 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8796                             unsigned AbsKind, QualType ArgType) {
8797   bool EmitHeaderHint = true;
8798   const char *HeaderName = nullptr;
8799   const char *FunctionName = nullptr;
8800   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8801     FunctionName = "std::abs";
8802     if (ArgType->isIntegralOrEnumerationType()) {
8803       HeaderName = "cstdlib";
8804     } else if (ArgType->isRealFloatingType()) {
8805       HeaderName = "cmath";
8806     } else {
8807       llvm_unreachable("Invalid Type");
8808     }
8809 
8810     // Lookup all std::abs
8811     if (NamespaceDecl *Std = S.getStdNamespace()) {
8812       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8813       R.suppressDiagnostics();
8814       S.LookupQualifiedName(R, Std);
8815 
8816       for (const auto *I : R) {
8817         const FunctionDecl *FDecl = nullptr;
8818         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8819           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8820         } else {
8821           FDecl = dyn_cast<FunctionDecl>(I);
8822         }
8823         if (!FDecl)
8824           continue;
8825 
8826         // Found std::abs(), check that they are the right ones.
8827         if (FDecl->getNumParams() != 1)
8828           continue;
8829 
8830         // Check that the parameter type can handle the argument.
8831         QualType ParamType = FDecl->getParamDecl(0)->getType();
8832         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8833             S.Context.getTypeSize(ArgType) <=
8834                 S.Context.getTypeSize(ParamType)) {
8835           // Found a function, don't need the header hint.
8836           EmitHeaderHint = false;
8837           break;
8838         }
8839       }
8840     }
8841   } else {
8842     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8843     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8844 
8845     if (HeaderName) {
8846       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8847       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8848       R.suppressDiagnostics();
8849       S.LookupName(R, S.getCurScope());
8850 
8851       if (R.isSingleResult()) {
8852         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8853         if (FD && FD->getBuiltinID() == AbsKind) {
8854           EmitHeaderHint = false;
8855         } else {
8856           return;
8857         }
8858       } else if (!R.empty()) {
8859         return;
8860       }
8861     }
8862   }
8863 
8864   S.Diag(Loc, diag::note_replace_abs_function)
8865       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8866 
8867   if (!HeaderName)
8868     return;
8869 
8870   if (!EmitHeaderHint)
8871     return;
8872 
8873   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8874                                                     << FunctionName;
8875 }
8876 
8877 template <std::size_t StrLen>
8878 static bool IsStdFunction(const FunctionDecl *FDecl,
8879                           const char (&Str)[StrLen]) {
8880   if (!FDecl)
8881     return false;
8882   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8883     return false;
8884   if (!FDecl->isInStdNamespace())
8885     return false;
8886 
8887   return true;
8888 }
8889 
8890 // Warn when using the wrong abs() function.
8891 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8892                                       const FunctionDecl *FDecl) {
8893   if (Call->getNumArgs() != 1)
8894     return;
8895 
8896   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8897   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8898   if (AbsKind == 0 && !IsStdAbs)
8899     return;
8900 
8901   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8902   QualType ParamType = Call->getArg(0)->getType();
8903 
8904   // Unsigned types cannot be negative.  Suggest removing the absolute value
8905   // function call.
8906   if (ArgType->isUnsignedIntegerType()) {
8907     const char *FunctionName =
8908         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8909     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8910     Diag(Call->getExprLoc(), diag::note_remove_abs)
8911         << FunctionName
8912         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8913     return;
8914   }
8915 
8916   // Taking the absolute value of a pointer is very suspicious, they probably
8917   // wanted to index into an array, dereference a pointer, call a function, etc.
8918   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8919     unsigned DiagType = 0;
8920     if (ArgType->isFunctionType())
8921       DiagType = 1;
8922     else if (ArgType->isArrayType())
8923       DiagType = 2;
8924 
8925     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8926     return;
8927   }
8928 
8929   // std::abs has overloads which prevent most of the absolute value problems
8930   // from occurring.
8931   if (IsStdAbs)
8932     return;
8933 
8934   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8935   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8936 
8937   // The argument and parameter are the same kind.  Check if they are the right
8938   // size.
8939   if (ArgValueKind == ParamValueKind) {
8940     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8941       return;
8942 
8943     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8944     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8945         << FDecl << ArgType << ParamType;
8946 
8947     if (NewAbsKind == 0)
8948       return;
8949 
8950     emitReplacement(*this, Call->getExprLoc(),
8951                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8952     return;
8953   }
8954 
8955   // ArgValueKind != ParamValueKind
8956   // The wrong type of absolute value function was used.  Attempt to find the
8957   // proper one.
8958   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8959   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8960   if (NewAbsKind == 0)
8961     return;
8962 
8963   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8964       << FDecl << ParamValueKind << ArgValueKind;
8965 
8966   emitReplacement(*this, Call->getExprLoc(),
8967                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8968 }
8969 
8970 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8971 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8972                                 const FunctionDecl *FDecl) {
8973   if (!Call || !FDecl) return;
8974 
8975   // Ignore template specializations and macros.
8976   if (inTemplateInstantiation()) return;
8977   if (Call->getExprLoc().isMacroID()) return;
8978 
8979   // Only care about the one template argument, two function parameter std::max
8980   if (Call->getNumArgs() != 2) return;
8981   if (!IsStdFunction(FDecl, "max")) return;
8982   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8983   if (!ArgList) return;
8984   if (ArgList->size() != 1) return;
8985 
8986   // Check that template type argument is unsigned integer.
8987   const auto& TA = ArgList->get(0);
8988   if (TA.getKind() != TemplateArgument::Type) return;
8989   QualType ArgType = TA.getAsType();
8990   if (!ArgType->isUnsignedIntegerType()) return;
8991 
8992   // See if either argument is a literal zero.
8993   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8994     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8995     if (!MTE) return false;
8996     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8997     if (!Num) return false;
8998     if (Num->getValue() != 0) return false;
8999     return true;
9000   };
9001 
9002   const Expr *FirstArg = Call->getArg(0);
9003   const Expr *SecondArg = Call->getArg(1);
9004   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9005   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9006 
9007   // Only warn when exactly one argument is zero.
9008   if (IsFirstArgZero == IsSecondArgZero) return;
9009 
9010   SourceRange FirstRange = FirstArg->getSourceRange();
9011   SourceRange SecondRange = SecondArg->getSourceRange();
9012 
9013   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9014 
9015   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9016       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9017 
9018   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9019   SourceRange RemovalRange;
9020   if (IsFirstArgZero) {
9021     RemovalRange = SourceRange(FirstRange.getBegin(),
9022                                SecondRange.getBegin().getLocWithOffset(-1));
9023   } else {
9024     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9025                                SecondRange.getEnd());
9026   }
9027 
9028   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9029         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9030         << FixItHint::CreateRemoval(RemovalRange);
9031 }
9032 
9033 //===--- CHECK: Standard memory functions ---------------------------------===//
9034 
9035 /// Takes the expression passed to the size_t parameter of functions
9036 /// such as memcmp, strncat, etc and warns if it's a comparison.
9037 ///
9038 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9039 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9040                                            IdentifierInfo *FnName,
9041                                            SourceLocation FnLoc,
9042                                            SourceLocation RParenLoc) {
9043   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9044   if (!Size)
9045     return false;
9046 
9047   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9048   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9049     return false;
9050 
9051   SourceRange SizeRange = Size->getSourceRange();
9052   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9053       << SizeRange << FnName;
9054   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9055       << FnName
9056       << FixItHint::CreateInsertion(
9057              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9058       << FixItHint::CreateRemoval(RParenLoc);
9059   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9060       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9061       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9062                                     ")");
9063 
9064   return true;
9065 }
9066 
9067 /// Determine whether the given type is or contains a dynamic class type
9068 /// (e.g., whether it has a vtable).
9069 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9070                                                      bool &IsContained) {
9071   // Look through array types while ignoring qualifiers.
9072   const Type *Ty = T->getBaseElementTypeUnsafe();
9073   IsContained = false;
9074 
9075   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9076   RD = RD ? RD->getDefinition() : nullptr;
9077   if (!RD || RD->isInvalidDecl())
9078     return nullptr;
9079 
9080   if (RD->isDynamicClass())
9081     return RD;
9082 
9083   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9084   // It's impossible for a class to transitively contain itself by value, so
9085   // infinite recursion is impossible.
9086   for (auto *FD : RD->fields()) {
9087     bool SubContained;
9088     if (const CXXRecordDecl *ContainedRD =
9089             getContainedDynamicClass(FD->getType(), SubContained)) {
9090       IsContained = true;
9091       return ContainedRD;
9092     }
9093   }
9094 
9095   return nullptr;
9096 }
9097 
9098 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9099   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9100     if (Unary->getKind() == UETT_SizeOf)
9101       return Unary;
9102   return nullptr;
9103 }
9104 
9105 /// If E is a sizeof expression, returns its argument expression,
9106 /// otherwise returns NULL.
9107 static const Expr *getSizeOfExprArg(const Expr *E) {
9108   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9109     if (!SizeOf->isArgumentType())
9110       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9111   return nullptr;
9112 }
9113 
9114 /// If E is a sizeof expression, returns its argument type.
9115 static QualType getSizeOfArgType(const Expr *E) {
9116   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9117     return SizeOf->getTypeOfArgument();
9118   return QualType();
9119 }
9120 
9121 namespace {
9122 
9123 struct SearchNonTrivialToInitializeField
9124     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9125   using Super =
9126       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9127 
9128   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9129 
9130   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9131                      SourceLocation SL) {
9132     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9133       asDerived().visitArray(PDIK, AT, SL);
9134       return;
9135     }
9136 
9137     Super::visitWithKind(PDIK, FT, SL);
9138   }
9139 
9140   void visitARCStrong(QualType FT, SourceLocation SL) {
9141     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9142   }
9143   void visitARCWeak(QualType FT, SourceLocation SL) {
9144     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9145   }
9146   void visitStruct(QualType FT, SourceLocation SL) {
9147     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9148       visit(FD->getType(), FD->getLocation());
9149   }
9150   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9151                   const ArrayType *AT, SourceLocation SL) {
9152     visit(getContext().getBaseElementType(AT), SL);
9153   }
9154   void visitTrivial(QualType FT, SourceLocation SL) {}
9155 
9156   static void diag(QualType RT, const Expr *E, Sema &S) {
9157     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9158   }
9159 
9160   ASTContext &getContext() { return S.getASTContext(); }
9161 
9162   const Expr *E;
9163   Sema &S;
9164 };
9165 
9166 struct SearchNonTrivialToCopyField
9167     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9168   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9169 
9170   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9171 
9172   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9173                      SourceLocation SL) {
9174     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9175       asDerived().visitArray(PCK, AT, SL);
9176       return;
9177     }
9178 
9179     Super::visitWithKind(PCK, FT, SL);
9180   }
9181 
9182   void visitARCStrong(QualType FT, SourceLocation SL) {
9183     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9184   }
9185   void visitARCWeak(QualType FT, SourceLocation SL) {
9186     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9187   }
9188   void visitStruct(QualType FT, SourceLocation SL) {
9189     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9190       visit(FD->getType(), FD->getLocation());
9191   }
9192   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9193                   SourceLocation SL) {
9194     visit(getContext().getBaseElementType(AT), SL);
9195   }
9196   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9197                 SourceLocation SL) {}
9198   void visitTrivial(QualType FT, SourceLocation SL) {}
9199   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9200 
9201   static void diag(QualType RT, const Expr *E, Sema &S) {
9202     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9203   }
9204 
9205   ASTContext &getContext() { return S.getASTContext(); }
9206 
9207   const Expr *E;
9208   Sema &S;
9209 };
9210 
9211 }
9212 
9213 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9214 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9215   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9216 
9217   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9218     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9219       return false;
9220 
9221     return doesExprLikelyComputeSize(BO->getLHS()) ||
9222            doesExprLikelyComputeSize(BO->getRHS());
9223   }
9224 
9225   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9226 }
9227 
9228 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9229 ///
9230 /// \code
9231 ///   #define MACRO 0
9232 ///   foo(MACRO);
9233 ///   foo(0);
9234 /// \endcode
9235 ///
9236 /// This should return true for the first call to foo, but not for the second
9237 /// (regardless of whether foo is a macro or function).
9238 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9239                                         SourceLocation CallLoc,
9240                                         SourceLocation ArgLoc) {
9241   if (!CallLoc.isMacroID())
9242     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9243 
9244   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9245          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9246 }
9247 
9248 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9249 /// last two arguments transposed.
9250 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9251   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9252     return;
9253 
9254   const Expr *SizeArg =
9255     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9256 
9257   auto isLiteralZero = [](const Expr *E) {
9258     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9259   };
9260 
9261   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9262   SourceLocation CallLoc = Call->getRParenLoc();
9263   SourceManager &SM = S.getSourceManager();
9264   if (isLiteralZero(SizeArg) &&
9265       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9266 
9267     SourceLocation DiagLoc = SizeArg->getExprLoc();
9268 
9269     // Some platforms #define bzero to __builtin_memset. See if this is the
9270     // case, and if so, emit a better diagnostic.
9271     if (BId == Builtin::BIbzero ||
9272         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9273                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9274       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9275       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9276     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9277       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9278       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9279     }
9280     return;
9281   }
9282 
9283   // If the second argument to a memset is a sizeof expression and the third
9284   // isn't, this is also likely an error. This should catch
9285   // 'memset(buf, sizeof(buf), 0xff)'.
9286   if (BId == Builtin::BImemset &&
9287       doesExprLikelyComputeSize(Call->getArg(1)) &&
9288       !doesExprLikelyComputeSize(Call->getArg(2))) {
9289     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9290     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9291     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9292     return;
9293   }
9294 }
9295 
9296 /// Check for dangerous or invalid arguments to memset().
9297 ///
9298 /// This issues warnings on known problematic, dangerous or unspecified
9299 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9300 /// function calls.
9301 ///
9302 /// \param Call The call expression to diagnose.
9303 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9304                                    unsigned BId,
9305                                    IdentifierInfo *FnName) {
9306   assert(BId != 0);
9307 
9308   // It is possible to have a non-standard definition of memset.  Validate
9309   // we have enough arguments, and if not, abort further checking.
9310   unsigned ExpectedNumArgs =
9311       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9312   if (Call->getNumArgs() < ExpectedNumArgs)
9313     return;
9314 
9315   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9316                       BId == Builtin::BIstrndup ? 1 : 2);
9317   unsigned LenArg =
9318       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9319   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9320 
9321   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9322                                      Call->getBeginLoc(), Call->getRParenLoc()))
9323     return;
9324 
9325   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9326   CheckMemaccessSize(*this, BId, Call);
9327 
9328   // We have special checking when the length is a sizeof expression.
9329   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9330   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9331   llvm::FoldingSetNodeID SizeOfArgID;
9332 
9333   // Although widely used, 'bzero' is not a standard function. Be more strict
9334   // with the argument types before allowing diagnostics and only allow the
9335   // form bzero(ptr, sizeof(...)).
9336   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9337   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9338     return;
9339 
9340   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9341     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9342     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9343 
9344     QualType DestTy = Dest->getType();
9345     QualType PointeeTy;
9346     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9347       PointeeTy = DestPtrTy->getPointeeType();
9348 
9349       // Never warn about void type pointers. This can be used to suppress
9350       // false positives.
9351       if (PointeeTy->isVoidType())
9352         continue;
9353 
9354       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9355       // actually comparing the expressions for equality. Because computing the
9356       // expression IDs can be expensive, we only do this if the diagnostic is
9357       // enabled.
9358       if (SizeOfArg &&
9359           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9360                            SizeOfArg->getExprLoc())) {
9361         // We only compute IDs for expressions if the warning is enabled, and
9362         // cache the sizeof arg's ID.
9363         if (SizeOfArgID == llvm::FoldingSetNodeID())
9364           SizeOfArg->Profile(SizeOfArgID, Context, true);
9365         llvm::FoldingSetNodeID DestID;
9366         Dest->Profile(DestID, Context, true);
9367         if (DestID == SizeOfArgID) {
9368           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9369           //       over sizeof(src) as well.
9370           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9371           StringRef ReadableName = FnName->getName();
9372 
9373           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9374             if (UnaryOp->getOpcode() == UO_AddrOf)
9375               ActionIdx = 1; // If its an address-of operator, just remove it.
9376           if (!PointeeTy->isIncompleteType() &&
9377               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9378             ActionIdx = 2; // If the pointee's size is sizeof(char),
9379                            // suggest an explicit length.
9380 
9381           // If the function is defined as a builtin macro, do not show macro
9382           // expansion.
9383           SourceLocation SL = SizeOfArg->getExprLoc();
9384           SourceRange DSR = Dest->getSourceRange();
9385           SourceRange SSR = SizeOfArg->getSourceRange();
9386           SourceManager &SM = getSourceManager();
9387 
9388           if (SM.isMacroArgExpansion(SL)) {
9389             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9390             SL = SM.getSpellingLoc(SL);
9391             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9392                              SM.getSpellingLoc(DSR.getEnd()));
9393             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9394                              SM.getSpellingLoc(SSR.getEnd()));
9395           }
9396 
9397           DiagRuntimeBehavior(SL, SizeOfArg,
9398                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9399                                 << ReadableName
9400                                 << PointeeTy
9401                                 << DestTy
9402                                 << DSR
9403                                 << SSR);
9404           DiagRuntimeBehavior(SL, SizeOfArg,
9405                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9406                                 << ActionIdx
9407                                 << SSR);
9408 
9409           break;
9410         }
9411       }
9412 
9413       // Also check for cases where the sizeof argument is the exact same
9414       // type as the memory argument, and where it points to a user-defined
9415       // record type.
9416       if (SizeOfArgTy != QualType()) {
9417         if (PointeeTy->isRecordType() &&
9418             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9419           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9420                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9421                                 << FnName << SizeOfArgTy << ArgIdx
9422                                 << PointeeTy << Dest->getSourceRange()
9423                                 << LenExpr->getSourceRange());
9424           break;
9425         }
9426       }
9427     } else if (DestTy->isArrayType()) {
9428       PointeeTy = DestTy;
9429     }
9430 
9431     if (PointeeTy == QualType())
9432       continue;
9433 
9434     // Always complain about dynamic classes.
9435     bool IsContained;
9436     if (const CXXRecordDecl *ContainedRD =
9437             getContainedDynamicClass(PointeeTy, IsContained)) {
9438 
9439       unsigned OperationType = 0;
9440       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9441       // "overwritten" if we're warning about the destination for any call
9442       // but memcmp; otherwise a verb appropriate to the call.
9443       if (ArgIdx != 0 || IsCmp) {
9444         if (BId == Builtin::BImemcpy)
9445           OperationType = 1;
9446         else if(BId == Builtin::BImemmove)
9447           OperationType = 2;
9448         else if (IsCmp)
9449           OperationType = 3;
9450       }
9451 
9452       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9453                           PDiag(diag::warn_dyn_class_memaccess)
9454                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9455                               << IsContained << ContainedRD << OperationType
9456                               << Call->getCallee()->getSourceRange());
9457     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9458              BId != Builtin::BImemset)
9459       DiagRuntimeBehavior(
9460         Dest->getExprLoc(), Dest,
9461         PDiag(diag::warn_arc_object_memaccess)
9462           << ArgIdx << FnName << PointeeTy
9463           << Call->getCallee()->getSourceRange());
9464     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9465       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9466           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9467         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9468                             PDiag(diag::warn_cstruct_memaccess)
9469                                 << ArgIdx << FnName << PointeeTy << 0);
9470         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9471       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9472                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9473         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9474                             PDiag(diag::warn_cstruct_memaccess)
9475                                 << ArgIdx << FnName << PointeeTy << 1);
9476         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9477       } else {
9478         continue;
9479       }
9480     } else
9481       continue;
9482 
9483     DiagRuntimeBehavior(
9484       Dest->getExprLoc(), Dest,
9485       PDiag(diag::note_bad_memaccess_silence)
9486         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9487     break;
9488   }
9489 }
9490 
9491 // A little helper routine: ignore addition and subtraction of integer literals.
9492 // This intentionally does not ignore all integer constant expressions because
9493 // we don't want to remove sizeof().
9494 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9495   Ex = Ex->IgnoreParenCasts();
9496 
9497   while (true) {
9498     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9499     if (!BO || !BO->isAdditiveOp())
9500       break;
9501 
9502     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9503     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9504 
9505     if (isa<IntegerLiteral>(RHS))
9506       Ex = LHS;
9507     else if (isa<IntegerLiteral>(LHS))
9508       Ex = RHS;
9509     else
9510       break;
9511   }
9512 
9513   return Ex;
9514 }
9515 
9516 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9517                                                       ASTContext &Context) {
9518   // Only handle constant-sized or VLAs, but not flexible members.
9519   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9520     // Only issue the FIXIT for arrays of size > 1.
9521     if (CAT->getSize().getSExtValue() <= 1)
9522       return false;
9523   } else if (!Ty->isVariableArrayType()) {
9524     return false;
9525   }
9526   return true;
9527 }
9528 
9529 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9530 // be the size of the source, instead of the destination.
9531 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9532                                     IdentifierInfo *FnName) {
9533 
9534   // Don't crash if the user has the wrong number of arguments
9535   unsigned NumArgs = Call->getNumArgs();
9536   if ((NumArgs != 3) && (NumArgs != 4))
9537     return;
9538 
9539   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9540   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9541   const Expr *CompareWithSrc = nullptr;
9542 
9543   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9544                                      Call->getBeginLoc(), Call->getRParenLoc()))
9545     return;
9546 
9547   // Look for 'strlcpy(dst, x, sizeof(x))'
9548   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9549     CompareWithSrc = Ex;
9550   else {
9551     // Look for 'strlcpy(dst, x, strlen(x))'
9552     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9553       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9554           SizeCall->getNumArgs() == 1)
9555         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9556     }
9557   }
9558 
9559   if (!CompareWithSrc)
9560     return;
9561 
9562   // Determine if the argument to sizeof/strlen is equal to the source
9563   // argument.  In principle there's all kinds of things you could do
9564   // here, for instance creating an == expression and evaluating it with
9565   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9566   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9567   if (!SrcArgDRE)
9568     return;
9569 
9570   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9571   if (!CompareWithSrcDRE ||
9572       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9573     return;
9574 
9575   const Expr *OriginalSizeArg = Call->getArg(2);
9576   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9577       << OriginalSizeArg->getSourceRange() << FnName;
9578 
9579   // Output a FIXIT hint if the destination is an array (rather than a
9580   // pointer to an array).  This could be enhanced to handle some
9581   // pointers if we know the actual size, like if DstArg is 'array+2'
9582   // we could say 'sizeof(array)-2'.
9583   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9584   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9585     return;
9586 
9587   SmallString<128> sizeString;
9588   llvm::raw_svector_ostream OS(sizeString);
9589   OS << "sizeof(";
9590   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9591   OS << ")";
9592 
9593   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9594       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9595                                       OS.str());
9596 }
9597 
9598 /// Check if two expressions refer to the same declaration.
9599 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9600   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9601     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9602       return D1->getDecl() == D2->getDecl();
9603   return false;
9604 }
9605 
9606 static const Expr *getStrlenExprArg(const Expr *E) {
9607   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9608     const FunctionDecl *FD = CE->getDirectCallee();
9609     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9610       return nullptr;
9611     return CE->getArg(0)->IgnoreParenCasts();
9612   }
9613   return nullptr;
9614 }
9615 
9616 // Warn on anti-patterns as the 'size' argument to strncat.
9617 // The correct size argument should look like following:
9618 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9619 void Sema::CheckStrncatArguments(const CallExpr *CE,
9620                                  IdentifierInfo *FnName) {
9621   // Don't crash if the user has the wrong number of arguments.
9622   if (CE->getNumArgs() < 3)
9623     return;
9624   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9625   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9626   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9627 
9628   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9629                                      CE->getRParenLoc()))
9630     return;
9631 
9632   // Identify common expressions, which are wrongly used as the size argument
9633   // to strncat and may lead to buffer overflows.
9634   unsigned PatternType = 0;
9635   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9636     // - sizeof(dst)
9637     if (referToTheSameDecl(SizeOfArg, DstArg))
9638       PatternType = 1;
9639     // - sizeof(src)
9640     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9641       PatternType = 2;
9642   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9643     if (BE->getOpcode() == BO_Sub) {
9644       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9645       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9646       // - sizeof(dst) - strlen(dst)
9647       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9648           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9649         PatternType = 1;
9650       // - sizeof(src) - (anything)
9651       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9652         PatternType = 2;
9653     }
9654   }
9655 
9656   if (PatternType == 0)
9657     return;
9658 
9659   // Generate the diagnostic.
9660   SourceLocation SL = LenArg->getBeginLoc();
9661   SourceRange SR = LenArg->getSourceRange();
9662   SourceManager &SM = getSourceManager();
9663 
9664   // If the function is defined as a builtin macro, do not show macro expansion.
9665   if (SM.isMacroArgExpansion(SL)) {
9666     SL = SM.getSpellingLoc(SL);
9667     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9668                      SM.getSpellingLoc(SR.getEnd()));
9669   }
9670 
9671   // Check if the destination is an array (rather than a pointer to an array).
9672   QualType DstTy = DstArg->getType();
9673   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9674                                                                     Context);
9675   if (!isKnownSizeArray) {
9676     if (PatternType == 1)
9677       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9678     else
9679       Diag(SL, diag::warn_strncat_src_size) << SR;
9680     return;
9681   }
9682 
9683   if (PatternType == 1)
9684     Diag(SL, diag::warn_strncat_large_size) << SR;
9685   else
9686     Diag(SL, diag::warn_strncat_src_size) << SR;
9687 
9688   SmallString<128> sizeString;
9689   llvm::raw_svector_ostream OS(sizeString);
9690   OS << "sizeof(";
9691   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9692   OS << ") - ";
9693   OS << "strlen(";
9694   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9695   OS << ") - 1";
9696 
9697   Diag(SL, diag::note_strncat_wrong_size)
9698     << FixItHint::CreateReplacement(SR, OS.str());
9699 }
9700 
9701 void
9702 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9703                          SourceLocation ReturnLoc,
9704                          bool isObjCMethod,
9705                          const AttrVec *Attrs,
9706                          const FunctionDecl *FD) {
9707   // Check if the return value is null but should not be.
9708   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9709        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9710       CheckNonNullExpr(*this, RetValExp))
9711     Diag(ReturnLoc, diag::warn_null_ret)
9712       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9713 
9714   // C++11 [basic.stc.dynamic.allocation]p4:
9715   //   If an allocation function declared with a non-throwing
9716   //   exception-specification fails to allocate storage, it shall return
9717   //   a null pointer. Any other allocation function that fails to allocate
9718   //   storage shall indicate failure only by throwing an exception [...]
9719   if (FD) {
9720     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9721     if (Op == OO_New || Op == OO_Array_New) {
9722       const FunctionProtoType *Proto
9723         = FD->getType()->castAs<FunctionProtoType>();
9724       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9725           CheckNonNullExpr(*this, RetValExp))
9726         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9727           << FD << getLangOpts().CPlusPlus11;
9728     }
9729   }
9730 }
9731 
9732 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9733 
9734 /// Check for comparisons of floating point operands using != and ==.
9735 /// Issue a warning if these are no self-comparisons, as they are not likely
9736 /// to do what the programmer intended.
9737 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9738   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9739   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9740 
9741   // Special case: check for x == x (which is OK).
9742   // Do not emit warnings for such cases.
9743   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9744     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9745       if (DRL->getDecl() == DRR->getDecl())
9746         return;
9747 
9748   // Special case: check for comparisons against literals that can be exactly
9749   //  represented by APFloat.  In such cases, do not emit a warning.  This
9750   //  is a heuristic: often comparison against such literals are used to
9751   //  detect if a value in a variable has not changed.  This clearly can
9752   //  lead to false negatives.
9753   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9754     if (FLL->isExact())
9755       return;
9756   } else
9757     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9758       if (FLR->isExact())
9759         return;
9760 
9761   // Check for comparisons with builtin types.
9762   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9763     if (CL->getBuiltinCallee())
9764       return;
9765 
9766   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9767     if (CR->getBuiltinCallee())
9768       return;
9769 
9770   // Emit the diagnostic.
9771   Diag(Loc, diag::warn_floatingpoint_eq)
9772     << LHS->getSourceRange() << RHS->getSourceRange();
9773 }
9774 
9775 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9776 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9777 
9778 namespace {
9779 
9780 /// Structure recording the 'active' range of an integer-valued
9781 /// expression.
9782 struct IntRange {
9783   /// The number of bits active in the int.
9784   unsigned Width;
9785 
9786   /// True if the int is known not to have negative values.
9787   bool NonNegative;
9788 
9789   IntRange(unsigned Width, bool NonNegative)
9790       : Width(Width), NonNegative(NonNegative) {}
9791 
9792   /// Returns the range of the bool type.
9793   static IntRange forBoolType() {
9794     return IntRange(1, true);
9795   }
9796 
9797   /// Returns the range of an opaque value of the given integral type.
9798   static IntRange forValueOfType(ASTContext &C, QualType T) {
9799     return forValueOfCanonicalType(C,
9800                           T->getCanonicalTypeInternal().getTypePtr());
9801   }
9802 
9803   /// Returns the range of an opaque value of a canonical integral type.
9804   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9805     assert(T->isCanonicalUnqualified());
9806 
9807     if (const VectorType *VT = dyn_cast<VectorType>(T))
9808       T = VT->getElementType().getTypePtr();
9809     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9810       T = CT->getElementType().getTypePtr();
9811     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9812       T = AT->getValueType().getTypePtr();
9813 
9814     if (!C.getLangOpts().CPlusPlus) {
9815       // For enum types in C code, use the underlying datatype.
9816       if (const EnumType *ET = dyn_cast<EnumType>(T))
9817         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9818     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9819       // For enum types in C++, use the known bit width of the enumerators.
9820       EnumDecl *Enum = ET->getDecl();
9821       // In C++11, enums can have a fixed underlying type. Use this type to
9822       // compute the range.
9823       if (Enum->isFixed()) {
9824         return IntRange(C.getIntWidth(QualType(T, 0)),
9825                         !ET->isSignedIntegerOrEnumerationType());
9826       }
9827 
9828       unsigned NumPositive = Enum->getNumPositiveBits();
9829       unsigned NumNegative = Enum->getNumNegativeBits();
9830 
9831       if (NumNegative == 0)
9832         return IntRange(NumPositive, true/*NonNegative*/);
9833       else
9834         return IntRange(std::max(NumPositive + 1, NumNegative),
9835                         false/*NonNegative*/);
9836     }
9837 
9838     const BuiltinType *BT = cast<BuiltinType>(T);
9839     assert(BT->isInteger());
9840 
9841     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9842   }
9843 
9844   /// Returns the "target" range of a canonical integral type, i.e.
9845   /// the range of values expressible in the type.
9846   ///
9847   /// This matches forValueOfCanonicalType except that enums have the
9848   /// full range of their type, not the range of their enumerators.
9849   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9850     assert(T->isCanonicalUnqualified());
9851 
9852     if (const VectorType *VT = dyn_cast<VectorType>(T))
9853       T = VT->getElementType().getTypePtr();
9854     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9855       T = CT->getElementType().getTypePtr();
9856     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9857       T = AT->getValueType().getTypePtr();
9858     if (const EnumType *ET = dyn_cast<EnumType>(T))
9859       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9860 
9861     const BuiltinType *BT = cast<BuiltinType>(T);
9862     assert(BT->isInteger());
9863 
9864     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9865   }
9866 
9867   /// Returns the supremum of two ranges: i.e. their conservative merge.
9868   static IntRange join(IntRange L, IntRange R) {
9869     return IntRange(std::max(L.Width, R.Width),
9870                     L.NonNegative && R.NonNegative);
9871   }
9872 
9873   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9874   static IntRange meet(IntRange L, IntRange R) {
9875     return IntRange(std::min(L.Width, R.Width),
9876                     L.NonNegative || R.NonNegative);
9877   }
9878 };
9879 
9880 } // namespace
9881 
9882 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9883                               unsigned MaxWidth) {
9884   if (value.isSigned() && value.isNegative())
9885     return IntRange(value.getMinSignedBits(), false);
9886 
9887   if (value.getBitWidth() > MaxWidth)
9888     value = value.trunc(MaxWidth);
9889 
9890   // isNonNegative() just checks the sign bit without considering
9891   // signedness.
9892   return IntRange(value.getActiveBits(), true);
9893 }
9894 
9895 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9896                               unsigned MaxWidth) {
9897   if (result.isInt())
9898     return GetValueRange(C, result.getInt(), MaxWidth);
9899 
9900   if (result.isVector()) {
9901     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9902     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9903       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9904       R = IntRange::join(R, El);
9905     }
9906     return R;
9907   }
9908 
9909   if (result.isComplexInt()) {
9910     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9911     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9912     return IntRange::join(R, I);
9913   }
9914 
9915   // This can happen with lossless casts to intptr_t of "based" lvalues.
9916   // Assume it might use arbitrary bits.
9917   // FIXME: The only reason we need to pass the type in here is to get
9918   // the sign right on this one case.  It would be nice if APValue
9919   // preserved this.
9920   assert(result.isLValue() || result.isAddrLabelDiff());
9921   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9922 }
9923 
9924 static QualType GetExprType(const Expr *E) {
9925   QualType Ty = E->getType();
9926   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9927     Ty = AtomicRHS->getValueType();
9928   return Ty;
9929 }
9930 
9931 /// Pseudo-evaluate the given integer expression, estimating the
9932 /// range of values it might take.
9933 ///
9934 /// \param MaxWidth - the width to which the value will be truncated
9935 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
9936                              bool InConstantContext) {
9937   E = E->IgnoreParens();
9938 
9939   // Try a full evaluation first.
9940   Expr::EvalResult result;
9941   if (E->EvaluateAsRValue(result, C, InConstantContext))
9942     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9943 
9944   // I think we only want to look through implicit casts here; if the
9945   // user has an explicit widening cast, we should treat the value as
9946   // being of the new, wider type.
9947   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9948     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9949       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
9950 
9951     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9952 
9953     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9954                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9955 
9956     // Assume that non-integer casts can span the full range of the type.
9957     if (!isIntegerCast)
9958       return OutputTypeRange;
9959 
9960     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
9961                                      std::min(MaxWidth, OutputTypeRange.Width),
9962                                      InConstantContext);
9963 
9964     // Bail out if the subexpr's range is as wide as the cast type.
9965     if (SubRange.Width >= OutputTypeRange.Width)
9966       return OutputTypeRange;
9967 
9968     // Otherwise, we take the smaller width, and we're non-negative if
9969     // either the output type or the subexpr is.
9970     return IntRange(SubRange.Width,
9971                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9972   }
9973 
9974   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9975     // If we can fold the condition, just take that operand.
9976     bool CondResult;
9977     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9978       return GetExprRange(C,
9979                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
9980                           MaxWidth, InConstantContext);
9981 
9982     // Otherwise, conservatively merge.
9983     IntRange L =
9984         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
9985     IntRange R =
9986         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
9987     return IntRange::join(L, R);
9988   }
9989 
9990   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9991     switch (BO->getOpcode()) {
9992     case BO_Cmp:
9993       llvm_unreachable("builtin <=> should have class type");
9994 
9995     // Boolean-valued operations are single-bit and positive.
9996     case BO_LAnd:
9997     case BO_LOr:
9998     case BO_LT:
9999     case BO_GT:
10000     case BO_LE:
10001     case BO_GE:
10002     case BO_EQ:
10003     case BO_NE:
10004       return IntRange::forBoolType();
10005 
10006     // The type of the assignments is the type of the LHS, so the RHS
10007     // is not necessarily the same type.
10008     case BO_MulAssign:
10009     case BO_DivAssign:
10010     case BO_RemAssign:
10011     case BO_AddAssign:
10012     case BO_SubAssign:
10013     case BO_XorAssign:
10014     case BO_OrAssign:
10015       // TODO: bitfields?
10016       return IntRange::forValueOfType(C, GetExprType(E));
10017 
10018     // Simple assignments just pass through the RHS, which will have
10019     // been coerced to the LHS type.
10020     case BO_Assign:
10021       // TODO: bitfields?
10022       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10023 
10024     // Operations with opaque sources are black-listed.
10025     case BO_PtrMemD:
10026     case BO_PtrMemI:
10027       return IntRange::forValueOfType(C, GetExprType(E));
10028 
10029     // Bitwise-and uses the *infinum* of the two source ranges.
10030     case BO_And:
10031     case BO_AndAssign:
10032       return IntRange::meet(
10033           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10034           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10035 
10036     // Left shift gets black-listed based on a judgement call.
10037     case BO_Shl:
10038       // ...except that we want to treat '1 << (blah)' as logically
10039       // positive.  It's an important idiom.
10040       if (IntegerLiteral *I
10041             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10042         if (I->getValue() == 1) {
10043           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10044           return IntRange(R.Width, /*NonNegative*/ true);
10045         }
10046       }
10047       LLVM_FALLTHROUGH;
10048 
10049     case BO_ShlAssign:
10050       return IntRange::forValueOfType(C, GetExprType(E));
10051 
10052     // Right shift by a constant can narrow its left argument.
10053     case BO_Shr:
10054     case BO_ShrAssign: {
10055       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10056 
10057       // If the shift amount is a positive constant, drop the width by
10058       // that much.
10059       llvm::APSInt shift;
10060       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10061           shift.isNonNegative()) {
10062         unsigned zext = shift.getZExtValue();
10063         if (zext >= L.Width)
10064           L.Width = (L.NonNegative ? 0 : 1);
10065         else
10066           L.Width -= zext;
10067       }
10068 
10069       return L;
10070     }
10071 
10072     // Comma acts as its right operand.
10073     case BO_Comma:
10074       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10075 
10076     // Black-list pointer subtractions.
10077     case BO_Sub:
10078       if (BO->getLHS()->getType()->isPointerType())
10079         return IntRange::forValueOfType(C, GetExprType(E));
10080       break;
10081 
10082     // The width of a division result is mostly determined by the size
10083     // of the LHS.
10084     case BO_Div: {
10085       // Don't 'pre-truncate' the operands.
10086       unsigned opWidth = C.getIntWidth(GetExprType(E));
10087       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10088 
10089       // If the divisor is constant, use that.
10090       llvm::APSInt divisor;
10091       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10092         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10093         if (log2 >= L.Width)
10094           L.Width = (L.NonNegative ? 0 : 1);
10095         else
10096           L.Width = std::min(L.Width - log2, MaxWidth);
10097         return L;
10098       }
10099 
10100       // Otherwise, just use the LHS's width.
10101       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10102       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10103     }
10104 
10105     // The result of a remainder can't be larger than the result of
10106     // either side.
10107     case BO_Rem: {
10108       // Don't 'pre-truncate' the operands.
10109       unsigned opWidth = C.getIntWidth(GetExprType(E));
10110       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10111       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10112 
10113       IntRange meet = IntRange::meet(L, R);
10114       meet.Width = std::min(meet.Width, MaxWidth);
10115       return meet;
10116     }
10117 
10118     // The default behavior is okay for these.
10119     case BO_Mul:
10120     case BO_Add:
10121     case BO_Xor:
10122     case BO_Or:
10123       break;
10124     }
10125 
10126     // The default case is to treat the operation as if it were closed
10127     // on the narrowest type that encompasses both operands.
10128     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10129     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10130     return IntRange::join(L, R);
10131   }
10132 
10133   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10134     switch (UO->getOpcode()) {
10135     // Boolean-valued operations are white-listed.
10136     case UO_LNot:
10137       return IntRange::forBoolType();
10138 
10139     // Operations with opaque sources are black-listed.
10140     case UO_Deref:
10141     case UO_AddrOf: // should be impossible
10142       return IntRange::forValueOfType(C, GetExprType(E));
10143 
10144     default:
10145       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10146     }
10147   }
10148 
10149   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10150     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10151 
10152   if (const auto *BitField = E->getSourceBitField())
10153     return IntRange(BitField->getBitWidthValue(C),
10154                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10155 
10156   return IntRange::forValueOfType(C, GetExprType(E));
10157 }
10158 
10159 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10160                              bool InConstantContext) {
10161   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10162 }
10163 
10164 /// Checks whether the given value, which currently has the given
10165 /// source semantics, has the same value when coerced through the
10166 /// target semantics.
10167 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10168                                  const llvm::fltSemantics &Src,
10169                                  const llvm::fltSemantics &Tgt) {
10170   llvm::APFloat truncated = value;
10171 
10172   bool ignored;
10173   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10174   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10175 
10176   return truncated.bitwiseIsEqual(value);
10177 }
10178 
10179 /// Checks whether the given value, which currently has the given
10180 /// source semantics, has the same value when coerced through the
10181 /// target semantics.
10182 ///
10183 /// The value might be a vector of floats (or a complex number).
10184 static bool IsSameFloatAfterCast(const APValue &value,
10185                                  const llvm::fltSemantics &Src,
10186                                  const llvm::fltSemantics &Tgt) {
10187   if (value.isFloat())
10188     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10189 
10190   if (value.isVector()) {
10191     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10192       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10193         return false;
10194     return true;
10195   }
10196 
10197   assert(value.isComplexFloat());
10198   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10199           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10200 }
10201 
10202 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
10203 
10204 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10205   // Suppress cases where we are comparing against an enum constant.
10206   if (const DeclRefExpr *DR =
10207       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10208     if (isa<EnumConstantDecl>(DR->getDecl()))
10209       return true;
10210 
10211   // Suppress cases where the value is expanded from a macro, unless that macro
10212   // is how a language represents a boolean literal. This is the case in both C
10213   // and Objective-C.
10214   SourceLocation BeginLoc = E->getBeginLoc();
10215   if (BeginLoc.isMacroID()) {
10216     StringRef MacroName = Lexer::getImmediateMacroName(
10217         BeginLoc, S.getSourceManager(), S.getLangOpts());
10218     return MacroName != "YES" && MacroName != "NO" &&
10219            MacroName != "true" && MacroName != "false";
10220   }
10221 
10222   return false;
10223 }
10224 
10225 static bool isKnownToHaveUnsignedValue(Expr *E) {
10226   return E->getType()->isIntegerType() &&
10227          (!E->getType()->isSignedIntegerType() ||
10228           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10229 }
10230 
10231 namespace {
10232 /// The promoted range of values of a type. In general this has the
10233 /// following structure:
10234 ///
10235 ///     |-----------| . . . |-----------|
10236 ///     ^           ^       ^           ^
10237 ///    Min       HoleMin  HoleMax      Max
10238 ///
10239 /// ... where there is only a hole if a signed type is promoted to unsigned
10240 /// (in which case Min and Max are the smallest and largest representable
10241 /// values).
10242 struct PromotedRange {
10243   // Min, or HoleMax if there is a hole.
10244   llvm::APSInt PromotedMin;
10245   // Max, or HoleMin if there is a hole.
10246   llvm::APSInt PromotedMax;
10247 
10248   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10249     if (R.Width == 0)
10250       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10251     else if (R.Width >= BitWidth && !Unsigned) {
10252       // Promotion made the type *narrower*. This happens when promoting
10253       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10254       // Treat all values of 'signed int' as being in range for now.
10255       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10256       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10257     } else {
10258       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10259                         .extOrTrunc(BitWidth);
10260       PromotedMin.setIsUnsigned(Unsigned);
10261 
10262       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10263                         .extOrTrunc(BitWidth);
10264       PromotedMax.setIsUnsigned(Unsigned);
10265     }
10266   }
10267 
10268   // Determine whether this range is contiguous (has no hole).
10269   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10270 
10271   // Where a constant value is within the range.
10272   enum ComparisonResult {
10273     LT = 0x1,
10274     LE = 0x2,
10275     GT = 0x4,
10276     GE = 0x8,
10277     EQ = 0x10,
10278     NE = 0x20,
10279     InRangeFlag = 0x40,
10280 
10281     Less = LE | LT | NE,
10282     Min = LE | InRangeFlag,
10283     InRange = InRangeFlag,
10284     Max = GE | InRangeFlag,
10285     Greater = GE | GT | NE,
10286 
10287     OnlyValue = LE | GE | EQ | InRangeFlag,
10288     InHole = NE
10289   };
10290 
10291   ComparisonResult compare(const llvm::APSInt &Value) const {
10292     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10293            Value.isUnsigned() == PromotedMin.isUnsigned());
10294     if (!isContiguous()) {
10295       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10296       if (Value.isMinValue()) return Min;
10297       if (Value.isMaxValue()) return Max;
10298       if (Value >= PromotedMin) return InRange;
10299       if (Value <= PromotedMax) return InRange;
10300       return InHole;
10301     }
10302 
10303     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10304     case -1: return Less;
10305     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10306     case 1:
10307       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10308       case -1: return InRange;
10309       case 0: return Max;
10310       case 1: return Greater;
10311       }
10312     }
10313 
10314     llvm_unreachable("impossible compare result");
10315   }
10316 
10317   static llvm::Optional<StringRef>
10318   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10319     if (Op == BO_Cmp) {
10320       ComparisonResult LTFlag = LT, GTFlag = GT;
10321       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10322 
10323       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10324       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10325       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10326       return llvm::None;
10327     }
10328 
10329     ComparisonResult TrueFlag, FalseFlag;
10330     if (Op == BO_EQ) {
10331       TrueFlag = EQ;
10332       FalseFlag = NE;
10333     } else if (Op == BO_NE) {
10334       TrueFlag = NE;
10335       FalseFlag = EQ;
10336     } else {
10337       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10338         TrueFlag = LT;
10339         FalseFlag = GE;
10340       } else {
10341         TrueFlag = GT;
10342         FalseFlag = LE;
10343       }
10344       if (Op == BO_GE || Op == BO_LE)
10345         std::swap(TrueFlag, FalseFlag);
10346     }
10347     if (R & TrueFlag)
10348       return StringRef("true");
10349     if (R & FalseFlag)
10350       return StringRef("false");
10351     return llvm::None;
10352   }
10353 };
10354 }
10355 
10356 static bool HasEnumType(Expr *E) {
10357   // Strip off implicit integral promotions.
10358   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10359     if (ICE->getCastKind() != CK_IntegralCast &&
10360         ICE->getCastKind() != CK_NoOp)
10361       break;
10362     E = ICE->getSubExpr();
10363   }
10364 
10365   return E->getType()->isEnumeralType();
10366 }
10367 
10368 static int classifyConstantValue(Expr *Constant) {
10369   // The values of this enumeration are used in the diagnostics
10370   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10371   enum ConstantValueKind {
10372     Miscellaneous = 0,
10373     LiteralTrue,
10374     LiteralFalse
10375   };
10376   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10377     return BL->getValue() ? ConstantValueKind::LiteralTrue
10378                           : ConstantValueKind::LiteralFalse;
10379   return ConstantValueKind::Miscellaneous;
10380 }
10381 
10382 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10383                                         Expr *Constant, Expr *Other,
10384                                         const llvm::APSInt &Value,
10385                                         bool RhsConstant) {
10386   if (S.inTemplateInstantiation())
10387     return false;
10388 
10389   Expr *OriginalOther = Other;
10390 
10391   Constant = Constant->IgnoreParenImpCasts();
10392   Other = Other->IgnoreParenImpCasts();
10393 
10394   // Suppress warnings on tautological comparisons between values of the same
10395   // enumeration type. There are only two ways we could warn on this:
10396   //  - If the constant is outside the range of representable values of
10397   //    the enumeration. In such a case, we should warn about the cast
10398   //    to enumeration type, not about the comparison.
10399   //  - If the constant is the maximum / minimum in-range value. For an
10400   //    enumeratin type, such comparisons can be meaningful and useful.
10401   if (Constant->getType()->isEnumeralType() &&
10402       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10403     return false;
10404 
10405   // TODO: Investigate using GetExprRange() to get tighter bounds
10406   // on the bit ranges.
10407   QualType OtherT = Other->getType();
10408   if (const auto *AT = OtherT->getAs<AtomicType>())
10409     OtherT = AT->getValueType();
10410   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10411 
10412   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10413   // (Namely, macOS).
10414   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10415                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10416                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10417 
10418   // Whether we're treating Other as being a bool because of the form of
10419   // expression despite it having another type (typically 'int' in C).
10420   bool OtherIsBooleanDespiteType =
10421       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10422   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10423     OtherRange = IntRange::forBoolType();
10424 
10425   // Determine the promoted range of the other type and see if a comparison of
10426   // the constant against that range is tautological.
10427   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10428                                    Value.isUnsigned());
10429   auto Cmp = OtherPromotedRange.compare(Value);
10430   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10431   if (!Result)
10432     return false;
10433 
10434   // Suppress the diagnostic for an in-range comparison if the constant comes
10435   // from a macro or enumerator. We don't want to diagnose
10436   //
10437   //   some_long_value <= INT_MAX
10438   //
10439   // when sizeof(int) == sizeof(long).
10440   bool InRange = Cmp & PromotedRange::InRangeFlag;
10441   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10442     return false;
10443 
10444   // If this is a comparison to an enum constant, include that
10445   // constant in the diagnostic.
10446   const EnumConstantDecl *ED = nullptr;
10447   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10448     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10449 
10450   // Should be enough for uint128 (39 decimal digits)
10451   SmallString<64> PrettySourceValue;
10452   llvm::raw_svector_ostream OS(PrettySourceValue);
10453   if (ED) {
10454     OS << '\'' << *ED << "' (" << Value << ")";
10455   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10456                Constant->IgnoreParenImpCasts())) {
10457     OS << (BL->getValue() ? "YES" : "NO");
10458   } else {
10459     OS << Value;
10460   }
10461 
10462   if (IsObjCSignedCharBool) {
10463     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10464                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10465                               << OS.str() << *Result);
10466     return true;
10467   }
10468 
10469   // FIXME: We use a somewhat different formatting for the in-range cases and
10470   // cases involving boolean values for historical reasons. We should pick a
10471   // consistent way of presenting these diagnostics.
10472   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10473 
10474     S.DiagRuntimeBehavior(
10475         E->getOperatorLoc(), E,
10476         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10477                          : diag::warn_tautological_bool_compare)
10478             << OS.str() << classifyConstantValue(Constant) << OtherT
10479             << OtherIsBooleanDespiteType << *Result
10480             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10481   } else {
10482     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10483                         ? (HasEnumType(OriginalOther)
10484                                ? diag::warn_unsigned_enum_always_true_comparison
10485                                : diag::warn_unsigned_always_true_comparison)
10486                         : diag::warn_tautological_constant_compare;
10487 
10488     S.Diag(E->getOperatorLoc(), Diag)
10489         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10490         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10491   }
10492 
10493   return true;
10494 }
10495 
10496 /// Analyze the operands of the given comparison.  Implements the
10497 /// fallback case from AnalyzeComparison.
10498 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10499   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10500   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10501 }
10502 
10503 /// Implements -Wsign-compare.
10504 ///
10505 /// \param E the binary operator to check for warnings
10506 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10507   // The type the comparison is being performed in.
10508   QualType T = E->getLHS()->getType();
10509 
10510   // Only analyze comparison operators where both sides have been converted to
10511   // the same type.
10512   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10513     return AnalyzeImpConvsInComparison(S, E);
10514 
10515   // Don't analyze value-dependent comparisons directly.
10516   if (E->isValueDependent())
10517     return AnalyzeImpConvsInComparison(S, E);
10518 
10519   Expr *LHS = E->getLHS();
10520   Expr *RHS = E->getRHS();
10521 
10522   if (T->isIntegralType(S.Context)) {
10523     llvm::APSInt RHSValue;
10524     llvm::APSInt LHSValue;
10525 
10526     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10527     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10528 
10529     // We don't care about expressions whose result is a constant.
10530     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10531       return AnalyzeImpConvsInComparison(S, E);
10532 
10533     // We only care about expressions where just one side is literal
10534     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10535       // Is the constant on the RHS or LHS?
10536       const bool RhsConstant = IsRHSIntegralLiteral;
10537       Expr *Const = RhsConstant ? RHS : LHS;
10538       Expr *Other = RhsConstant ? LHS : RHS;
10539       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10540 
10541       // Check whether an integer constant comparison results in a value
10542       // of 'true' or 'false'.
10543       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10544         return AnalyzeImpConvsInComparison(S, E);
10545     }
10546   }
10547 
10548   if (!T->hasUnsignedIntegerRepresentation()) {
10549     // We don't do anything special if this isn't an unsigned integral
10550     // comparison:  we're only interested in integral comparisons, and
10551     // signed comparisons only happen in cases we don't care to warn about.
10552     return AnalyzeImpConvsInComparison(S, E);
10553   }
10554 
10555   LHS = LHS->IgnoreParenImpCasts();
10556   RHS = RHS->IgnoreParenImpCasts();
10557 
10558   if (!S.getLangOpts().CPlusPlus) {
10559     // Avoid warning about comparison of integers with different signs when
10560     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10561     // the type of `E`.
10562     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10563       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10564     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10565       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10566   }
10567 
10568   // Check to see if one of the (unmodified) operands is of different
10569   // signedness.
10570   Expr *signedOperand, *unsignedOperand;
10571   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10572     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10573            "unsigned comparison between two signed integer expressions?");
10574     signedOperand = LHS;
10575     unsignedOperand = RHS;
10576   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10577     signedOperand = RHS;
10578     unsignedOperand = LHS;
10579   } else {
10580     return AnalyzeImpConvsInComparison(S, E);
10581   }
10582 
10583   // Otherwise, calculate the effective range of the signed operand.
10584   IntRange signedRange =
10585       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10586 
10587   // Go ahead and analyze implicit conversions in the operands.  Note
10588   // that we skip the implicit conversions on both sides.
10589   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10590   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10591 
10592   // If the signed range is non-negative, -Wsign-compare won't fire.
10593   if (signedRange.NonNegative)
10594     return;
10595 
10596   // For (in)equality comparisons, if the unsigned operand is a
10597   // constant which cannot collide with a overflowed signed operand,
10598   // then reinterpreting the signed operand as unsigned will not
10599   // change the result of the comparison.
10600   if (E->isEqualityOp()) {
10601     unsigned comparisonWidth = S.Context.getIntWidth(T);
10602     IntRange unsignedRange =
10603         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10604 
10605     // We should never be unable to prove that the unsigned operand is
10606     // non-negative.
10607     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10608 
10609     if (unsignedRange.Width < comparisonWidth)
10610       return;
10611   }
10612 
10613   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10614                         S.PDiag(diag::warn_mixed_sign_comparison)
10615                             << LHS->getType() << RHS->getType()
10616                             << LHS->getSourceRange() << RHS->getSourceRange());
10617 }
10618 
10619 /// Analyzes an attempt to assign the given value to a bitfield.
10620 ///
10621 /// Returns true if there was something fishy about the attempt.
10622 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10623                                       SourceLocation InitLoc) {
10624   assert(Bitfield->isBitField());
10625   if (Bitfield->isInvalidDecl())
10626     return false;
10627 
10628   // White-list bool bitfields.
10629   QualType BitfieldType = Bitfield->getType();
10630   if (BitfieldType->isBooleanType())
10631      return false;
10632 
10633   if (BitfieldType->isEnumeralType()) {
10634     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10635     // If the underlying enum type was not explicitly specified as an unsigned
10636     // type and the enum contain only positive values, MSVC++ will cause an
10637     // inconsistency by storing this as a signed type.
10638     if (S.getLangOpts().CPlusPlus11 &&
10639         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10640         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10641         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10642       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10643         << BitfieldEnumDecl->getNameAsString();
10644     }
10645   }
10646 
10647   if (Bitfield->getType()->isBooleanType())
10648     return false;
10649 
10650   // Ignore value- or type-dependent expressions.
10651   if (Bitfield->getBitWidth()->isValueDependent() ||
10652       Bitfield->getBitWidth()->isTypeDependent() ||
10653       Init->isValueDependent() ||
10654       Init->isTypeDependent())
10655     return false;
10656 
10657   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10658   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10659 
10660   Expr::EvalResult Result;
10661   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10662                                    Expr::SE_AllowSideEffects)) {
10663     // The RHS is not constant.  If the RHS has an enum type, make sure the
10664     // bitfield is wide enough to hold all the values of the enum without
10665     // truncation.
10666     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10667       EnumDecl *ED = EnumTy->getDecl();
10668       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10669 
10670       // Enum types are implicitly signed on Windows, so check if there are any
10671       // negative enumerators to see if the enum was intended to be signed or
10672       // not.
10673       bool SignedEnum = ED->getNumNegativeBits() > 0;
10674 
10675       // Check for surprising sign changes when assigning enum values to a
10676       // bitfield of different signedness.  If the bitfield is signed and we
10677       // have exactly the right number of bits to store this unsigned enum,
10678       // suggest changing the enum to an unsigned type. This typically happens
10679       // on Windows where unfixed enums always use an underlying type of 'int'.
10680       unsigned DiagID = 0;
10681       if (SignedEnum && !SignedBitfield) {
10682         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10683       } else if (SignedBitfield && !SignedEnum &&
10684                  ED->getNumPositiveBits() == FieldWidth) {
10685         DiagID = diag::warn_signed_bitfield_enum_conversion;
10686       }
10687 
10688       if (DiagID) {
10689         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10690         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10691         SourceRange TypeRange =
10692             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10693         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10694             << SignedEnum << TypeRange;
10695       }
10696 
10697       // Compute the required bitwidth. If the enum has negative values, we need
10698       // one more bit than the normal number of positive bits to represent the
10699       // sign bit.
10700       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10701                                                   ED->getNumNegativeBits())
10702                                        : ED->getNumPositiveBits();
10703 
10704       // Check the bitwidth.
10705       if (BitsNeeded > FieldWidth) {
10706         Expr *WidthExpr = Bitfield->getBitWidth();
10707         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10708             << Bitfield << ED;
10709         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10710             << BitsNeeded << ED << WidthExpr->getSourceRange();
10711       }
10712     }
10713 
10714     return false;
10715   }
10716 
10717   llvm::APSInt Value = Result.Val.getInt();
10718 
10719   unsigned OriginalWidth = Value.getBitWidth();
10720 
10721   if (!Value.isSigned() || Value.isNegative())
10722     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10723       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10724         OriginalWidth = Value.getMinSignedBits();
10725 
10726   if (OriginalWidth <= FieldWidth)
10727     return false;
10728 
10729   // Compute the value which the bitfield will contain.
10730   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10731   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10732 
10733   // Check whether the stored value is equal to the original value.
10734   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10735   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10736     return false;
10737 
10738   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10739   // therefore don't strictly fit into a signed bitfield of width 1.
10740   if (FieldWidth == 1 && Value == 1)
10741     return false;
10742 
10743   std::string PrettyValue = Value.toString(10);
10744   std::string PrettyTrunc = TruncatedValue.toString(10);
10745 
10746   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10747     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10748     << Init->getSourceRange();
10749 
10750   return true;
10751 }
10752 
10753 /// Analyze the given simple or compound assignment for warning-worthy
10754 /// operations.
10755 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10756   // Just recurse on the LHS.
10757   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10758 
10759   // We want to recurse on the RHS as normal unless we're assigning to
10760   // a bitfield.
10761   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10762     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10763                                   E->getOperatorLoc())) {
10764       // Recurse, ignoring any implicit conversions on the RHS.
10765       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10766                                         E->getOperatorLoc());
10767     }
10768   }
10769 
10770   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10771 
10772   // Diagnose implicitly sequentially-consistent atomic assignment.
10773   if (E->getLHS()->getType()->isAtomicType())
10774     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10775 }
10776 
10777 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10778 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10779                             SourceLocation CContext, unsigned diag,
10780                             bool pruneControlFlow = false) {
10781   if (pruneControlFlow) {
10782     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10783                           S.PDiag(diag)
10784                               << SourceType << T << E->getSourceRange()
10785                               << SourceRange(CContext));
10786     return;
10787   }
10788   S.Diag(E->getExprLoc(), diag)
10789     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10790 }
10791 
10792 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10793 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10794                             SourceLocation CContext,
10795                             unsigned diag, bool pruneControlFlow = false) {
10796   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10797 }
10798 
10799 /// Diagnose an implicit cast from a floating point value to an integer value.
10800 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10801                                     SourceLocation CContext) {
10802   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10803   const bool PruneWarnings = S.inTemplateInstantiation();
10804 
10805   Expr *InnerE = E->IgnoreParenImpCasts();
10806   // We also want to warn on, e.g., "int i = -1.234"
10807   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10808     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10809       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10810 
10811   const bool IsLiteral =
10812       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10813 
10814   llvm::APFloat Value(0.0);
10815   bool IsConstant =
10816     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10817   if (!IsConstant) {
10818     return DiagnoseImpCast(S, E, T, CContext,
10819                            diag::warn_impcast_float_integer, PruneWarnings);
10820   }
10821 
10822   bool isExact = false;
10823 
10824   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10825                             T->hasUnsignedIntegerRepresentation());
10826   llvm::APFloat::opStatus Result = Value.convertToInteger(
10827       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10828 
10829   if (Result == llvm::APFloat::opOK && isExact) {
10830     if (IsLiteral) return;
10831     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10832                            PruneWarnings);
10833   }
10834 
10835   // Conversion of a floating-point value to a non-bool integer where the
10836   // integral part cannot be represented by the integer type is undefined.
10837   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10838     return DiagnoseImpCast(
10839         S, E, T, CContext,
10840         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10841                   : diag::warn_impcast_float_to_integer_out_of_range,
10842         PruneWarnings);
10843 
10844   unsigned DiagID = 0;
10845   if (IsLiteral) {
10846     // Warn on floating point literal to integer.
10847     DiagID = diag::warn_impcast_literal_float_to_integer;
10848   } else if (IntegerValue == 0) {
10849     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10850       return DiagnoseImpCast(S, E, T, CContext,
10851                              diag::warn_impcast_float_integer, PruneWarnings);
10852     }
10853     // Warn on non-zero to zero conversion.
10854     DiagID = diag::warn_impcast_float_to_integer_zero;
10855   } else {
10856     if (IntegerValue.isUnsigned()) {
10857       if (!IntegerValue.isMaxValue()) {
10858         return DiagnoseImpCast(S, E, T, CContext,
10859                                diag::warn_impcast_float_integer, PruneWarnings);
10860       }
10861     } else {  // IntegerValue.isSigned()
10862       if (!IntegerValue.isMaxSignedValue() &&
10863           !IntegerValue.isMinSignedValue()) {
10864         return DiagnoseImpCast(S, E, T, CContext,
10865                                diag::warn_impcast_float_integer, PruneWarnings);
10866       }
10867     }
10868     // Warn on evaluatable floating point expression to integer conversion.
10869     DiagID = diag::warn_impcast_float_to_integer;
10870   }
10871 
10872   // FIXME: Force the precision of the source value down so we don't print
10873   // digits which are usually useless (we don't really care here if we
10874   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10875   // would automatically print the shortest representation, but it's a bit
10876   // tricky to implement.
10877   SmallString<16> PrettySourceValue;
10878   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10879   precision = (precision * 59 + 195) / 196;
10880   Value.toString(PrettySourceValue, precision);
10881 
10882   SmallString<16> PrettyTargetValue;
10883   if (IsBool)
10884     PrettyTargetValue = Value.isZero() ? "false" : "true";
10885   else
10886     IntegerValue.toString(PrettyTargetValue);
10887 
10888   if (PruneWarnings) {
10889     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10890                           S.PDiag(DiagID)
10891                               << E->getType() << T.getUnqualifiedType()
10892                               << PrettySourceValue << PrettyTargetValue
10893                               << E->getSourceRange() << SourceRange(CContext));
10894   } else {
10895     S.Diag(E->getExprLoc(), DiagID)
10896         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10897         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10898   }
10899 }
10900 
10901 /// Analyze the given compound assignment for the possible losing of
10902 /// floating-point precision.
10903 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10904   assert(isa<CompoundAssignOperator>(E) &&
10905          "Must be compound assignment operation");
10906   // Recurse on the LHS and RHS in here
10907   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10908   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10909 
10910   if (E->getLHS()->getType()->isAtomicType())
10911     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10912 
10913   // Now check the outermost expression
10914   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10915   const auto *RBT = cast<CompoundAssignOperator>(E)
10916                         ->getComputationResultType()
10917                         ->getAs<BuiltinType>();
10918 
10919   // The below checks assume source is floating point.
10920   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10921 
10922   // If source is floating point but target is an integer.
10923   if (ResultBT->isInteger())
10924     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10925                            E->getExprLoc(), diag::warn_impcast_float_integer);
10926 
10927   if (!ResultBT->isFloatingPoint())
10928     return;
10929 
10930   // If both source and target are floating points, warn about losing precision.
10931   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10932       QualType(ResultBT, 0), QualType(RBT, 0));
10933   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10934     // warn about dropping FP rank.
10935     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10936                     diag::warn_impcast_float_result_precision);
10937 }
10938 
10939 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10940                                       IntRange Range) {
10941   if (!Range.Width) return "0";
10942 
10943   llvm::APSInt ValueInRange = Value;
10944   ValueInRange.setIsSigned(!Range.NonNegative);
10945   ValueInRange = ValueInRange.trunc(Range.Width);
10946   return ValueInRange.toString(10);
10947 }
10948 
10949 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10950   if (!isa<ImplicitCastExpr>(Ex))
10951     return false;
10952 
10953   Expr *InnerE = Ex->IgnoreParenImpCasts();
10954   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10955   const Type *Source =
10956     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10957   if (Target->isDependentType())
10958     return false;
10959 
10960   const BuiltinType *FloatCandidateBT =
10961     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10962   const Type *BoolCandidateType = ToBool ? Target : Source;
10963 
10964   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10965           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10966 }
10967 
10968 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10969                                              SourceLocation CC) {
10970   unsigned NumArgs = TheCall->getNumArgs();
10971   for (unsigned i = 0; i < NumArgs; ++i) {
10972     Expr *CurrA = TheCall->getArg(i);
10973     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10974       continue;
10975 
10976     bool IsSwapped = ((i > 0) &&
10977         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10978     IsSwapped |= ((i < (NumArgs - 1)) &&
10979         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10980     if (IsSwapped) {
10981       // Warn on this floating-point to bool conversion.
10982       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10983                       CurrA->getType(), CC,
10984                       diag::warn_impcast_floating_point_to_bool);
10985     }
10986   }
10987 }
10988 
10989 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10990                                    SourceLocation CC) {
10991   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10992                         E->getExprLoc()))
10993     return;
10994 
10995   // Don't warn on functions which have return type nullptr_t.
10996   if (isa<CallExpr>(E))
10997     return;
10998 
10999   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11000   const Expr::NullPointerConstantKind NullKind =
11001       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11002   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11003     return;
11004 
11005   // Return if target type is a safe conversion.
11006   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11007       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11008     return;
11009 
11010   SourceLocation Loc = E->getSourceRange().getBegin();
11011 
11012   // Venture through the macro stacks to get to the source of macro arguments.
11013   // The new location is a better location than the complete location that was
11014   // passed in.
11015   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11016   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11017 
11018   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11019   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11020     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11021         Loc, S.SourceMgr, S.getLangOpts());
11022     if (MacroName == "NULL")
11023       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11024   }
11025 
11026   // Only warn if the null and context location are in the same macro expansion.
11027   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11028     return;
11029 
11030   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11031       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11032       << FixItHint::CreateReplacement(Loc,
11033                                       S.getFixItZeroLiteralForType(T, Loc));
11034 }
11035 
11036 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11037                                   ObjCArrayLiteral *ArrayLiteral);
11038 
11039 static void
11040 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11041                            ObjCDictionaryLiteral *DictionaryLiteral);
11042 
11043 /// Check a single element within a collection literal against the
11044 /// target element type.
11045 static void checkObjCCollectionLiteralElement(Sema &S,
11046                                               QualType TargetElementType,
11047                                               Expr *Element,
11048                                               unsigned ElementKind) {
11049   // Skip a bitcast to 'id' or qualified 'id'.
11050   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11051     if (ICE->getCastKind() == CK_BitCast &&
11052         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11053       Element = ICE->getSubExpr();
11054   }
11055 
11056   QualType ElementType = Element->getType();
11057   ExprResult ElementResult(Element);
11058   if (ElementType->getAs<ObjCObjectPointerType>() &&
11059       S.CheckSingleAssignmentConstraints(TargetElementType,
11060                                          ElementResult,
11061                                          false, false)
11062         != Sema::Compatible) {
11063     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11064         << ElementType << ElementKind << TargetElementType
11065         << Element->getSourceRange();
11066   }
11067 
11068   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11069     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11070   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11071     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11072 }
11073 
11074 /// Check an Objective-C array literal being converted to the given
11075 /// target type.
11076 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11077                                   ObjCArrayLiteral *ArrayLiteral) {
11078   if (!S.NSArrayDecl)
11079     return;
11080 
11081   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11082   if (!TargetObjCPtr)
11083     return;
11084 
11085   if (TargetObjCPtr->isUnspecialized() ||
11086       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11087         != S.NSArrayDecl->getCanonicalDecl())
11088     return;
11089 
11090   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11091   if (TypeArgs.size() != 1)
11092     return;
11093 
11094   QualType TargetElementType = TypeArgs[0];
11095   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11096     checkObjCCollectionLiteralElement(S, TargetElementType,
11097                                       ArrayLiteral->getElement(I),
11098                                       0);
11099   }
11100 }
11101 
11102 /// Check an Objective-C dictionary literal being converted to the given
11103 /// target type.
11104 static void
11105 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11106                            ObjCDictionaryLiteral *DictionaryLiteral) {
11107   if (!S.NSDictionaryDecl)
11108     return;
11109 
11110   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11111   if (!TargetObjCPtr)
11112     return;
11113 
11114   if (TargetObjCPtr->isUnspecialized() ||
11115       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11116         != S.NSDictionaryDecl->getCanonicalDecl())
11117     return;
11118 
11119   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11120   if (TypeArgs.size() != 2)
11121     return;
11122 
11123   QualType TargetKeyType = TypeArgs[0];
11124   QualType TargetObjectType = TypeArgs[1];
11125   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11126     auto Element = DictionaryLiteral->getKeyValueElement(I);
11127     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11128     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11129   }
11130 }
11131 
11132 // Helper function to filter out cases for constant width constant conversion.
11133 // Don't warn on char array initialization or for non-decimal values.
11134 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11135                                           SourceLocation CC) {
11136   // If initializing from a constant, and the constant starts with '0',
11137   // then it is a binary, octal, or hexadecimal.  Allow these constants
11138   // to fill all the bits, even if there is a sign change.
11139   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11140     const char FirstLiteralCharacter =
11141         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11142     if (FirstLiteralCharacter == '0')
11143       return false;
11144   }
11145 
11146   // If the CC location points to a '{', and the type is char, then assume
11147   // assume it is an array initialization.
11148   if (CC.isValid() && T->isCharType()) {
11149     const char FirstContextCharacter =
11150         S.getSourceManager().getCharacterData(CC)[0];
11151     if (FirstContextCharacter == '{')
11152       return false;
11153   }
11154 
11155   return true;
11156 }
11157 
11158 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11159   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11160          S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11161 }
11162 
11163 static void
11164 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
11165                         bool *ICContext = nullptr) {
11166   if (E->isTypeDependent() || E->isValueDependent()) return;
11167 
11168   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11169   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11170   if (Source == Target) return;
11171   if (Target->isDependentType()) return;
11172 
11173   // If the conversion context location is invalid don't complain. We also
11174   // don't want to emit a warning if the issue occurs from the expansion of
11175   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11176   // delay this check as long as possible. Once we detect we are in that
11177   // scenario, we just return.
11178   if (CC.isInvalid())
11179     return;
11180 
11181   if (Source->isAtomicType())
11182     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11183 
11184   // Diagnose implicit casts to bool.
11185   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11186     if (isa<StringLiteral>(E))
11187       // Warn on string literal to bool.  Checks for string literals in logical
11188       // and expressions, for instance, assert(0 && "error here"), are
11189       // prevented by a check in AnalyzeImplicitConversions().
11190       return DiagnoseImpCast(S, E, T, CC,
11191                              diag::warn_impcast_string_literal_to_bool);
11192     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11193         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11194       // This covers the literal expressions that evaluate to Objective-C
11195       // objects.
11196       return DiagnoseImpCast(S, E, T, CC,
11197                              diag::warn_impcast_objective_c_literal_to_bool);
11198     }
11199     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11200       // Warn on pointer to bool conversion that is always true.
11201       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11202                                      SourceRange(CC));
11203     }
11204   }
11205 
11206   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11207   // is a typedef for signed char (macOS), then that constant value has to be 1
11208   // or 0.
11209   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11210     Expr::EvalResult Result;
11211     if (E->EvaluateAsInt(Result, S.getASTContext(),
11212                          Expr::SE_AllowSideEffects) &&
11213         Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11214       auto Builder = S.Diag(CC, diag::warn_impcast_constant_int_to_objc_bool)
11215                      << Result.Val.getInt().toString(10);
11216       Expr *Ignored = E->IgnoreImplicit();
11217       bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11218                          isa<BinaryOperator>(Ignored) ||
11219                          isa<CXXOperatorCallExpr>(Ignored);
11220       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
11221       if (NeedsParens)
11222         Builder << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
11223                 << FixItHint::CreateInsertion(EndLoc, ")");
11224       Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11225       return;
11226     }
11227   }
11228 
11229   // Check implicit casts from Objective-C collection literals to specialized
11230   // collection types, e.g., NSArray<NSString *> *.
11231   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11232     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11233   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11234     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11235 
11236   // Strip vector types.
11237   if (isa<VectorType>(Source)) {
11238     if (!isa<VectorType>(Target)) {
11239       if (S.SourceMgr.isInSystemMacro(CC))
11240         return;
11241       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11242     }
11243 
11244     // If the vector cast is cast between two vectors of the same size, it is
11245     // a bitcast, not a conversion.
11246     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11247       return;
11248 
11249     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11250     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11251   }
11252   if (auto VecTy = dyn_cast<VectorType>(Target))
11253     Target = VecTy->getElementType().getTypePtr();
11254 
11255   // Strip complex types.
11256   if (isa<ComplexType>(Source)) {
11257     if (!isa<ComplexType>(Target)) {
11258       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11259         return;
11260 
11261       return DiagnoseImpCast(S, E, T, CC,
11262                              S.getLangOpts().CPlusPlus
11263                                  ? diag::err_impcast_complex_scalar
11264                                  : diag::warn_impcast_complex_scalar);
11265     }
11266 
11267     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11268     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11269   }
11270 
11271   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11272   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11273 
11274   // If the source is floating point...
11275   if (SourceBT && SourceBT->isFloatingPoint()) {
11276     // ...and the target is floating point...
11277     if (TargetBT && TargetBT->isFloatingPoint()) {
11278       // ...then warn if we're dropping FP rank.
11279 
11280       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11281           QualType(SourceBT, 0), QualType(TargetBT, 0));
11282       if (Order > 0) {
11283         // Don't warn about float constants that are precisely
11284         // representable in the target type.
11285         Expr::EvalResult result;
11286         if (E->EvaluateAsRValue(result, S.Context)) {
11287           // Value might be a float, a float vector, or a float complex.
11288           if (IsSameFloatAfterCast(result.Val,
11289                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11290                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11291             return;
11292         }
11293 
11294         if (S.SourceMgr.isInSystemMacro(CC))
11295           return;
11296 
11297         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11298       }
11299       // ... or possibly if we're increasing rank, too
11300       else if (Order < 0) {
11301         if (S.SourceMgr.isInSystemMacro(CC))
11302           return;
11303 
11304         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11305       }
11306       return;
11307     }
11308 
11309     // If the target is integral, always warn.
11310     if (TargetBT && TargetBT->isInteger()) {
11311       if (S.SourceMgr.isInSystemMacro(CC))
11312         return;
11313 
11314       DiagnoseFloatingImpCast(S, E, T, CC);
11315     }
11316 
11317     // Detect the case where a call result is converted from floating-point to
11318     // to bool, and the final argument to the call is converted from bool, to
11319     // discover this typo:
11320     //
11321     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11322     //
11323     // FIXME: This is an incredibly special case; is there some more general
11324     // way to detect this class of misplaced-parentheses bug?
11325     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11326       // Check last argument of function call to see if it is an
11327       // implicit cast from a type matching the type the result
11328       // is being cast to.
11329       CallExpr *CEx = cast<CallExpr>(E);
11330       if (unsigned NumArgs = CEx->getNumArgs()) {
11331         Expr *LastA = CEx->getArg(NumArgs - 1);
11332         Expr *InnerE = LastA->IgnoreParenImpCasts();
11333         if (isa<ImplicitCastExpr>(LastA) &&
11334             InnerE->getType()->isBooleanType()) {
11335           // Warn on this floating-point to bool conversion
11336           DiagnoseImpCast(S, E, T, CC,
11337                           diag::warn_impcast_floating_point_to_bool);
11338         }
11339       }
11340     }
11341     return;
11342   }
11343 
11344   // Valid casts involving fixed point types should be accounted for here.
11345   if (Source->isFixedPointType()) {
11346     if (Target->isUnsaturatedFixedPointType()) {
11347       Expr::EvalResult Result;
11348       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11349                                   S.isConstantEvaluated())) {
11350         APFixedPoint Value = Result.Val.getFixedPoint();
11351         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11352         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11353         if (Value > MaxVal || Value < MinVal) {
11354           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11355                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11356                                     << Value.toString() << T
11357                                     << E->getSourceRange()
11358                                     << clang::SourceRange(CC));
11359           return;
11360         }
11361       }
11362     } else if (Target->isIntegerType()) {
11363       Expr::EvalResult Result;
11364       if (!S.isConstantEvaluated() &&
11365           E->EvaluateAsFixedPoint(Result, S.Context,
11366                                   Expr::SE_AllowSideEffects)) {
11367         APFixedPoint FXResult = Result.Val.getFixedPoint();
11368 
11369         bool Overflowed;
11370         llvm::APSInt IntResult = FXResult.convertToInt(
11371             S.Context.getIntWidth(T),
11372             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11373 
11374         if (Overflowed) {
11375           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11376                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11377                                     << FXResult.toString() << T
11378                                     << E->getSourceRange()
11379                                     << clang::SourceRange(CC));
11380           return;
11381         }
11382       }
11383     }
11384   } else if (Target->isUnsaturatedFixedPointType()) {
11385     if (Source->isIntegerType()) {
11386       Expr::EvalResult Result;
11387       if (!S.isConstantEvaluated() &&
11388           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11389         llvm::APSInt Value = Result.Val.getInt();
11390 
11391         bool Overflowed;
11392         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11393             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11394 
11395         if (Overflowed) {
11396           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11397                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11398                                     << Value.toString(/*Radix=*/10) << T
11399                                     << E->getSourceRange()
11400                                     << clang::SourceRange(CC));
11401           return;
11402         }
11403       }
11404     }
11405   }
11406 
11407   DiagnoseNullConversion(S, E, T, CC);
11408 
11409   S.DiscardMisalignedMemberAddress(Target, E);
11410 
11411   if (!Source->isIntegerType() || !Target->isIntegerType())
11412     return;
11413 
11414   // TODO: remove this early return once the false positives for constant->bool
11415   // in templates, macros, etc, are reduced or removed.
11416   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11417     return;
11418 
11419   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11420   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11421 
11422   if (SourceRange.Width > TargetRange.Width) {
11423     // If the source is a constant, use a default-on diagnostic.
11424     // TODO: this should happen for bitfield stores, too.
11425     Expr::EvalResult Result;
11426     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11427                          S.isConstantEvaluated())) {
11428       llvm::APSInt Value(32);
11429       Value = Result.Val.getInt();
11430 
11431       if (S.SourceMgr.isInSystemMacro(CC))
11432         return;
11433 
11434       std::string PrettySourceValue = Value.toString(10);
11435       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11436 
11437       S.DiagRuntimeBehavior(
11438           E->getExprLoc(), E,
11439           S.PDiag(diag::warn_impcast_integer_precision_constant)
11440               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11441               << E->getSourceRange() << clang::SourceRange(CC));
11442       return;
11443     }
11444 
11445     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11446     if (S.SourceMgr.isInSystemMacro(CC))
11447       return;
11448 
11449     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11450       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11451                              /* pruneControlFlow */ true);
11452     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11453   }
11454 
11455   if (TargetRange.Width > SourceRange.Width) {
11456     if (auto *UO = dyn_cast<UnaryOperator>(E))
11457       if (UO->getOpcode() == UO_Minus)
11458         if (Source->isUnsignedIntegerType()) {
11459           if (Target->isUnsignedIntegerType())
11460             return DiagnoseImpCast(S, E, T, CC,
11461                                    diag::warn_impcast_high_order_zero_bits);
11462           if (Target->isSignedIntegerType())
11463             return DiagnoseImpCast(S, E, T, CC,
11464                                    diag::warn_impcast_nonnegative_result);
11465         }
11466   }
11467 
11468   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11469       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11470     // Warn when doing a signed to signed conversion, warn if the positive
11471     // source value is exactly the width of the target type, which will
11472     // cause a negative value to be stored.
11473 
11474     Expr::EvalResult Result;
11475     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11476         !S.SourceMgr.isInSystemMacro(CC)) {
11477       llvm::APSInt Value = Result.Val.getInt();
11478       if (isSameWidthConstantConversion(S, E, T, CC)) {
11479         std::string PrettySourceValue = Value.toString(10);
11480         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11481 
11482         S.DiagRuntimeBehavior(
11483             E->getExprLoc(), E,
11484             S.PDiag(diag::warn_impcast_integer_precision_constant)
11485                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11486                 << E->getSourceRange() << clang::SourceRange(CC));
11487         return;
11488       }
11489     }
11490 
11491     // Fall through for non-constants to give a sign conversion warning.
11492   }
11493 
11494   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11495       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11496        SourceRange.Width == TargetRange.Width)) {
11497     if (S.SourceMgr.isInSystemMacro(CC))
11498       return;
11499 
11500     unsigned DiagID = diag::warn_impcast_integer_sign;
11501 
11502     // Traditionally, gcc has warned about this under -Wsign-compare.
11503     // We also want to warn about it in -Wconversion.
11504     // So if -Wconversion is off, use a completely identical diagnostic
11505     // in the sign-compare group.
11506     // The conditional-checking code will
11507     if (ICContext) {
11508       DiagID = diag::warn_impcast_integer_sign_conditional;
11509       *ICContext = true;
11510     }
11511 
11512     return DiagnoseImpCast(S, E, T, CC, DiagID);
11513   }
11514 
11515   // Diagnose conversions between different enumeration types.
11516   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11517   // type, to give us better diagnostics.
11518   QualType SourceType = E->getType();
11519   if (!S.getLangOpts().CPlusPlus) {
11520     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11521       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11522         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11523         SourceType = S.Context.getTypeDeclType(Enum);
11524         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11525       }
11526   }
11527 
11528   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11529     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11530       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11531           TargetEnum->getDecl()->hasNameForLinkage() &&
11532           SourceEnum != TargetEnum) {
11533         if (S.SourceMgr.isInSystemMacro(CC))
11534           return;
11535 
11536         return DiagnoseImpCast(S, E, SourceType, T, CC,
11537                                diag::warn_impcast_different_enum_types);
11538       }
11539 }
11540 
11541 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11542                                      SourceLocation CC, QualType T);
11543 
11544 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11545                                     SourceLocation CC, bool &ICContext) {
11546   E = E->IgnoreParenImpCasts();
11547 
11548   if (isa<ConditionalOperator>(E))
11549     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11550 
11551   AnalyzeImplicitConversions(S, E, CC);
11552   if (E->getType() != T)
11553     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11554 }
11555 
11556 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11557                                      SourceLocation CC, QualType T) {
11558   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11559 
11560   bool Suspicious = false;
11561   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11562   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11563 
11564   // If -Wconversion would have warned about either of the candidates
11565   // for a signedness conversion to the context type...
11566   if (!Suspicious) return;
11567 
11568   // ...but it's currently ignored...
11569   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11570     return;
11571 
11572   // ...then check whether it would have warned about either of the
11573   // candidates for a signedness conversion to the condition type.
11574   if (E->getType() == T) return;
11575 
11576   Suspicious = false;
11577   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11578                           E->getType(), CC, &Suspicious);
11579   if (!Suspicious)
11580     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11581                             E->getType(), CC, &Suspicious);
11582 }
11583 
11584 /// Check conversion of given expression to boolean.
11585 /// Input argument E is a logical expression.
11586 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11587   if (S.getLangOpts().Bool)
11588     return;
11589   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11590     return;
11591   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11592 }
11593 
11594 /// AnalyzeImplicitConversions - Find and report any interesting
11595 /// implicit conversions in the given expression.  There are a couple
11596 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11597 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11598                                        SourceLocation CC) {
11599   QualType T = OrigE->getType();
11600   Expr *E = OrigE->IgnoreParenImpCasts();
11601 
11602   if (E->isTypeDependent() || E->isValueDependent())
11603     return;
11604 
11605   // For conditional operators, we analyze the arguments as if they
11606   // were being fed directly into the output.
11607   if (isa<ConditionalOperator>(E)) {
11608     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11609     CheckConditionalOperator(S, CO, CC, T);
11610     return;
11611   }
11612 
11613   // Check implicit argument conversions for function calls.
11614   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11615     CheckImplicitArgumentConversions(S, Call, CC);
11616 
11617   // Go ahead and check any implicit conversions we might have skipped.
11618   // The non-canonical typecheck is just an optimization;
11619   // CheckImplicitConversion will filter out dead implicit conversions.
11620   if (E->getType() != T)
11621     CheckImplicitConversion(S, E, T, CC);
11622 
11623   // Now continue drilling into this expression.
11624 
11625   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11626     // The bound subexpressions in a PseudoObjectExpr are not reachable
11627     // as transitive children.
11628     // FIXME: Use a more uniform representation for this.
11629     for (auto *SE : POE->semantics())
11630       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11631         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11632   }
11633 
11634   // Skip past explicit casts.
11635   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11636     E = CE->getSubExpr()->IgnoreParenImpCasts();
11637     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11638       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11639     return AnalyzeImplicitConversions(S, E, CC);
11640   }
11641 
11642   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11643     // Do a somewhat different check with comparison operators.
11644     if (BO->isComparisonOp())
11645       return AnalyzeComparison(S, BO);
11646 
11647     // And with simple assignments.
11648     if (BO->getOpcode() == BO_Assign)
11649       return AnalyzeAssignment(S, BO);
11650     // And with compound assignments.
11651     if (BO->isAssignmentOp())
11652       return AnalyzeCompoundAssignment(S, BO);
11653   }
11654 
11655   // These break the otherwise-useful invariant below.  Fortunately,
11656   // we don't really need to recurse into them, because any internal
11657   // expressions should have been analyzed already when they were
11658   // built into statements.
11659   if (isa<StmtExpr>(E)) return;
11660 
11661   // Don't descend into unevaluated contexts.
11662   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11663 
11664   // Now just recurse over the expression's children.
11665   CC = E->getExprLoc();
11666   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11667   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11668   for (Stmt *SubStmt : E->children()) {
11669     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11670     if (!ChildExpr)
11671       continue;
11672 
11673     if (IsLogicalAndOperator &&
11674         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11675       // Ignore checking string literals that are in logical and operators.
11676       // This is a common pattern for asserts.
11677       continue;
11678     AnalyzeImplicitConversions(S, ChildExpr, CC);
11679   }
11680 
11681   if (BO && BO->isLogicalOp()) {
11682     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11683     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11684       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11685 
11686     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11687     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11688       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11689   }
11690 
11691   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11692     if (U->getOpcode() == UO_LNot) {
11693       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11694     } else if (U->getOpcode() != UO_AddrOf) {
11695       if (U->getSubExpr()->getType()->isAtomicType())
11696         S.Diag(U->getSubExpr()->getBeginLoc(),
11697                diag::warn_atomic_implicit_seq_cst);
11698     }
11699   }
11700 }
11701 
11702 /// Diagnose integer type and any valid implicit conversion to it.
11703 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11704   // Taking into account implicit conversions,
11705   // allow any integer.
11706   if (!E->getType()->isIntegerType()) {
11707     S.Diag(E->getBeginLoc(),
11708            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11709     return true;
11710   }
11711   // Potentially emit standard warnings for implicit conversions if enabled
11712   // using -Wconversion.
11713   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11714   return false;
11715 }
11716 
11717 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11718 // Returns true when emitting a warning about taking the address of a reference.
11719 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11720                               const PartialDiagnostic &PD) {
11721   E = E->IgnoreParenImpCasts();
11722 
11723   const FunctionDecl *FD = nullptr;
11724 
11725   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11726     if (!DRE->getDecl()->getType()->isReferenceType())
11727       return false;
11728   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11729     if (!M->getMemberDecl()->getType()->isReferenceType())
11730       return false;
11731   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11732     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11733       return false;
11734     FD = Call->getDirectCallee();
11735   } else {
11736     return false;
11737   }
11738 
11739   SemaRef.Diag(E->getExprLoc(), PD);
11740 
11741   // If possible, point to location of function.
11742   if (FD) {
11743     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11744   }
11745 
11746   return true;
11747 }
11748 
11749 // Returns true if the SourceLocation is expanded from any macro body.
11750 // Returns false if the SourceLocation is invalid, is from not in a macro
11751 // expansion, or is from expanded from a top-level macro argument.
11752 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11753   if (Loc.isInvalid())
11754     return false;
11755 
11756   while (Loc.isMacroID()) {
11757     if (SM.isMacroBodyExpansion(Loc))
11758       return true;
11759     Loc = SM.getImmediateMacroCallerLoc(Loc);
11760   }
11761 
11762   return false;
11763 }
11764 
11765 /// Diagnose pointers that are always non-null.
11766 /// \param E the expression containing the pointer
11767 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11768 /// compared to a null pointer
11769 /// \param IsEqual True when the comparison is equal to a null pointer
11770 /// \param Range Extra SourceRange to highlight in the diagnostic
11771 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11772                                         Expr::NullPointerConstantKind NullKind,
11773                                         bool IsEqual, SourceRange Range) {
11774   if (!E)
11775     return;
11776 
11777   // Don't warn inside macros.
11778   if (E->getExprLoc().isMacroID()) {
11779     const SourceManager &SM = getSourceManager();
11780     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11781         IsInAnyMacroBody(SM, Range.getBegin()))
11782       return;
11783   }
11784   E = E->IgnoreImpCasts();
11785 
11786   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11787 
11788   if (isa<CXXThisExpr>(E)) {
11789     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11790                                 : diag::warn_this_bool_conversion;
11791     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11792     return;
11793   }
11794 
11795   bool IsAddressOf = false;
11796 
11797   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11798     if (UO->getOpcode() != UO_AddrOf)
11799       return;
11800     IsAddressOf = true;
11801     E = UO->getSubExpr();
11802   }
11803 
11804   if (IsAddressOf) {
11805     unsigned DiagID = IsCompare
11806                           ? diag::warn_address_of_reference_null_compare
11807                           : diag::warn_address_of_reference_bool_conversion;
11808     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11809                                          << IsEqual;
11810     if (CheckForReference(*this, E, PD)) {
11811       return;
11812     }
11813   }
11814 
11815   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11816     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11817     std::string Str;
11818     llvm::raw_string_ostream S(Str);
11819     E->printPretty(S, nullptr, getPrintingPolicy());
11820     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11821                                 : diag::warn_cast_nonnull_to_bool;
11822     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11823       << E->getSourceRange() << Range << IsEqual;
11824     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11825   };
11826 
11827   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11828   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11829     if (auto *Callee = Call->getDirectCallee()) {
11830       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11831         ComplainAboutNonnullParamOrCall(A);
11832         return;
11833       }
11834     }
11835   }
11836 
11837   // Expect to find a single Decl.  Skip anything more complicated.
11838   ValueDecl *D = nullptr;
11839   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11840     D = R->getDecl();
11841   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11842     D = M->getMemberDecl();
11843   }
11844 
11845   // Weak Decls can be null.
11846   if (!D || D->isWeak())
11847     return;
11848 
11849   // Check for parameter decl with nonnull attribute
11850   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11851     if (getCurFunction() &&
11852         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11853       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11854         ComplainAboutNonnullParamOrCall(A);
11855         return;
11856       }
11857 
11858       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11859         // Skip function template not specialized yet.
11860         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11861           return;
11862         auto ParamIter = llvm::find(FD->parameters(), PV);
11863         assert(ParamIter != FD->param_end());
11864         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11865 
11866         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11867           if (!NonNull->args_size()) {
11868               ComplainAboutNonnullParamOrCall(NonNull);
11869               return;
11870           }
11871 
11872           for (const ParamIdx &ArgNo : NonNull->args()) {
11873             if (ArgNo.getASTIndex() == ParamNo) {
11874               ComplainAboutNonnullParamOrCall(NonNull);
11875               return;
11876             }
11877           }
11878         }
11879       }
11880     }
11881   }
11882 
11883   QualType T = D->getType();
11884   const bool IsArray = T->isArrayType();
11885   const bool IsFunction = T->isFunctionType();
11886 
11887   // Address of function is used to silence the function warning.
11888   if (IsAddressOf && IsFunction) {
11889     return;
11890   }
11891 
11892   // Found nothing.
11893   if (!IsAddressOf && !IsFunction && !IsArray)
11894     return;
11895 
11896   // Pretty print the expression for the diagnostic.
11897   std::string Str;
11898   llvm::raw_string_ostream S(Str);
11899   E->printPretty(S, nullptr, getPrintingPolicy());
11900 
11901   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11902                               : diag::warn_impcast_pointer_to_bool;
11903   enum {
11904     AddressOf,
11905     FunctionPointer,
11906     ArrayPointer
11907   } DiagType;
11908   if (IsAddressOf)
11909     DiagType = AddressOf;
11910   else if (IsFunction)
11911     DiagType = FunctionPointer;
11912   else if (IsArray)
11913     DiagType = ArrayPointer;
11914   else
11915     llvm_unreachable("Could not determine diagnostic.");
11916   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11917                                 << Range << IsEqual;
11918 
11919   if (!IsFunction)
11920     return;
11921 
11922   // Suggest '&' to silence the function warning.
11923   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11924       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11925 
11926   // Check to see if '()' fixit should be emitted.
11927   QualType ReturnType;
11928   UnresolvedSet<4> NonTemplateOverloads;
11929   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11930   if (ReturnType.isNull())
11931     return;
11932 
11933   if (IsCompare) {
11934     // There are two cases here.  If there is null constant, the only suggest
11935     // for a pointer return type.  If the null is 0, then suggest if the return
11936     // type is a pointer or an integer type.
11937     if (!ReturnType->isPointerType()) {
11938       if (NullKind == Expr::NPCK_ZeroExpression ||
11939           NullKind == Expr::NPCK_ZeroLiteral) {
11940         if (!ReturnType->isIntegerType())
11941           return;
11942       } else {
11943         return;
11944       }
11945     }
11946   } else { // !IsCompare
11947     // For function to bool, only suggest if the function pointer has bool
11948     // return type.
11949     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11950       return;
11951   }
11952   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11953       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11954 }
11955 
11956 /// Diagnoses "dangerous" implicit conversions within the given
11957 /// expression (which is a full expression).  Implements -Wconversion
11958 /// and -Wsign-compare.
11959 ///
11960 /// \param CC the "context" location of the implicit conversion, i.e.
11961 ///   the most location of the syntactic entity requiring the implicit
11962 ///   conversion
11963 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11964   // Don't diagnose in unevaluated contexts.
11965   if (isUnevaluatedContext())
11966     return;
11967 
11968   // Don't diagnose for value- or type-dependent expressions.
11969   if (E->isTypeDependent() || E->isValueDependent())
11970     return;
11971 
11972   // Check for array bounds violations in cases where the check isn't triggered
11973   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11974   // ArraySubscriptExpr is on the RHS of a variable initialization.
11975   CheckArrayAccess(E);
11976 
11977   // This is not the right CC for (e.g.) a variable initialization.
11978   AnalyzeImplicitConversions(*this, E, CC);
11979 }
11980 
11981 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11982 /// Input argument E is a logical expression.
11983 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11984   ::CheckBoolLikeConversion(*this, E, CC);
11985 }
11986 
11987 /// Diagnose when expression is an integer constant expression and its evaluation
11988 /// results in integer overflow
11989 void Sema::CheckForIntOverflow (Expr *E) {
11990   // Use a work list to deal with nested struct initializers.
11991   SmallVector<Expr *, 2> Exprs(1, E);
11992 
11993   do {
11994     Expr *OriginalE = Exprs.pop_back_val();
11995     Expr *E = OriginalE->IgnoreParenCasts();
11996 
11997     if (isa<BinaryOperator>(E)) {
11998       E->EvaluateForOverflow(Context);
11999       continue;
12000     }
12001 
12002     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12003       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12004     else if (isa<ObjCBoxedExpr>(OriginalE))
12005       E->EvaluateForOverflow(Context);
12006     else if (auto Call = dyn_cast<CallExpr>(E))
12007       Exprs.append(Call->arg_begin(), Call->arg_end());
12008     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12009       Exprs.append(Message->arg_begin(), Message->arg_end());
12010   } while (!Exprs.empty());
12011 }
12012 
12013 namespace {
12014 
12015 /// Visitor for expressions which looks for unsequenced operations on the
12016 /// same object.
12017 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
12018   using Base = EvaluatedExprVisitor<SequenceChecker>;
12019 
12020   /// A tree of sequenced regions within an expression. Two regions are
12021   /// unsequenced if one is an ancestor or a descendent of the other. When we
12022   /// finish processing an expression with sequencing, such as a comma
12023   /// expression, we fold its tree nodes into its parent, since they are
12024   /// unsequenced with respect to nodes we will visit later.
12025   class SequenceTree {
12026     struct Value {
12027       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12028       unsigned Parent : 31;
12029       unsigned Merged : 1;
12030     };
12031     SmallVector<Value, 8> Values;
12032 
12033   public:
12034     /// A region within an expression which may be sequenced with respect
12035     /// to some other region.
12036     class Seq {
12037       friend class SequenceTree;
12038 
12039       unsigned Index;
12040 
12041       explicit Seq(unsigned N) : Index(N) {}
12042 
12043     public:
12044       Seq() : Index(0) {}
12045     };
12046 
12047     SequenceTree() { Values.push_back(Value(0)); }
12048     Seq root() const { return Seq(0); }
12049 
12050     /// Create a new sequence of operations, which is an unsequenced
12051     /// subset of \p Parent. This sequence of operations is sequenced with
12052     /// respect to other children of \p Parent.
12053     Seq allocate(Seq Parent) {
12054       Values.push_back(Value(Parent.Index));
12055       return Seq(Values.size() - 1);
12056     }
12057 
12058     /// Merge a sequence of operations into its parent.
12059     void merge(Seq S) {
12060       Values[S.Index].Merged = true;
12061     }
12062 
12063     /// Determine whether two operations are unsequenced. This operation
12064     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12065     /// should have been merged into its parent as appropriate.
12066     bool isUnsequenced(Seq Cur, Seq Old) {
12067       unsigned C = representative(Cur.Index);
12068       unsigned Target = representative(Old.Index);
12069       while (C >= Target) {
12070         if (C == Target)
12071           return true;
12072         C = Values[C].Parent;
12073       }
12074       return false;
12075     }
12076 
12077   private:
12078     /// Pick a representative for a sequence.
12079     unsigned representative(unsigned K) {
12080       if (Values[K].Merged)
12081         // Perform path compression as we go.
12082         return Values[K].Parent = representative(Values[K].Parent);
12083       return K;
12084     }
12085   };
12086 
12087   /// An object for which we can track unsequenced uses.
12088   using Object = NamedDecl *;
12089 
12090   /// Different flavors of object usage which we track. We only track the
12091   /// least-sequenced usage of each kind.
12092   enum UsageKind {
12093     /// A read of an object. Multiple unsequenced reads are OK.
12094     UK_Use,
12095 
12096     /// A modification of an object which is sequenced before the value
12097     /// computation of the expression, such as ++n in C++.
12098     UK_ModAsValue,
12099 
12100     /// A modification of an object which is not sequenced before the value
12101     /// computation of the expression, such as n++.
12102     UK_ModAsSideEffect,
12103 
12104     UK_Count = UK_ModAsSideEffect + 1
12105   };
12106 
12107   struct Usage {
12108     Expr *Use;
12109     SequenceTree::Seq Seq;
12110 
12111     Usage() : Use(nullptr), Seq() {}
12112   };
12113 
12114   struct UsageInfo {
12115     Usage Uses[UK_Count];
12116 
12117     /// Have we issued a diagnostic for this variable already?
12118     bool Diagnosed;
12119 
12120     UsageInfo() : Uses(), Diagnosed(false) {}
12121   };
12122   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12123 
12124   Sema &SemaRef;
12125 
12126   /// Sequenced regions within the expression.
12127   SequenceTree Tree;
12128 
12129   /// Declaration modifications and references which we have seen.
12130   UsageInfoMap UsageMap;
12131 
12132   /// The region we are currently within.
12133   SequenceTree::Seq Region;
12134 
12135   /// Filled in with declarations which were modified as a side-effect
12136   /// (that is, post-increment operations).
12137   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12138 
12139   /// Expressions to check later. We defer checking these to reduce
12140   /// stack usage.
12141   SmallVectorImpl<Expr *> &WorkList;
12142 
12143   /// RAII object wrapping the visitation of a sequenced subexpression of an
12144   /// expression. At the end of this process, the side-effects of the evaluation
12145   /// become sequenced with respect to the value computation of the result, so
12146   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12147   /// UK_ModAsValue.
12148   struct SequencedSubexpression {
12149     SequencedSubexpression(SequenceChecker &Self)
12150       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12151       Self.ModAsSideEffect = &ModAsSideEffect;
12152     }
12153 
12154     ~SequencedSubexpression() {
12155       for (auto &M : llvm::reverse(ModAsSideEffect)) {
12156         UsageInfo &U = Self.UsageMap[M.first];
12157         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12158         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12159         SideEffectUsage = M.second;
12160       }
12161       Self.ModAsSideEffect = OldModAsSideEffect;
12162     }
12163 
12164     SequenceChecker &Self;
12165     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12166     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12167   };
12168 
12169   /// RAII object wrapping the visitation of a subexpression which we might
12170   /// choose to evaluate as a constant. If any subexpression is evaluated and
12171   /// found to be non-constant, this allows us to suppress the evaluation of
12172   /// the outer expression.
12173   class EvaluationTracker {
12174   public:
12175     EvaluationTracker(SequenceChecker &Self)
12176         : Self(Self), Prev(Self.EvalTracker) {
12177       Self.EvalTracker = this;
12178     }
12179 
12180     ~EvaluationTracker() {
12181       Self.EvalTracker = Prev;
12182       if (Prev)
12183         Prev->EvalOK &= EvalOK;
12184     }
12185 
12186     bool evaluate(const Expr *E, bool &Result) {
12187       if (!EvalOK || E->isValueDependent())
12188         return false;
12189       EvalOK = E->EvaluateAsBooleanCondition(
12190           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12191       return EvalOK;
12192     }
12193 
12194   private:
12195     SequenceChecker &Self;
12196     EvaluationTracker *Prev;
12197     bool EvalOK = true;
12198   } *EvalTracker = nullptr;
12199 
12200   /// Find the object which is produced by the specified expression,
12201   /// if any.
12202   Object getObject(Expr *E, bool Mod) const {
12203     E = E->IgnoreParenCasts();
12204     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12205       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12206         return getObject(UO->getSubExpr(), Mod);
12207     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12208       if (BO->getOpcode() == BO_Comma)
12209         return getObject(BO->getRHS(), Mod);
12210       if (Mod && BO->isAssignmentOp())
12211         return getObject(BO->getLHS(), Mod);
12212     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12213       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12214       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12215         return ME->getMemberDecl();
12216     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12217       // FIXME: If this is a reference, map through to its value.
12218       return DRE->getDecl();
12219     return nullptr;
12220   }
12221 
12222   /// Note that an object was modified or used by an expression.
12223   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12224     Usage &U = UI.Uses[UK];
12225     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12226       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12227         ModAsSideEffect->push_back(std::make_pair(O, U));
12228       U.Use = Ref;
12229       U.Seq = Region;
12230     }
12231   }
12232 
12233   /// Check whether a modification or use conflicts with a prior usage.
12234   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12235                   bool IsModMod) {
12236     if (UI.Diagnosed)
12237       return;
12238 
12239     const Usage &U = UI.Uses[OtherKind];
12240     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12241       return;
12242 
12243     Expr *Mod = U.Use;
12244     Expr *ModOrUse = Ref;
12245     if (OtherKind == UK_Use)
12246       std::swap(Mod, ModOrUse);
12247 
12248     SemaRef.DiagRuntimeBehavior(
12249         Mod->getExprLoc(), {Mod, ModOrUse},
12250         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12251                                : diag::warn_unsequenced_mod_use)
12252             << O << SourceRange(ModOrUse->getExprLoc()));
12253     UI.Diagnosed = true;
12254   }
12255 
12256   void notePreUse(Object O, Expr *Use) {
12257     UsageInfo &U = UsageMap[O];
12258     // Uses conflict with other modifications.
12259     checkUsage(O, U, Use, UK_ModAsValue, false);
12260   }
12261 
12262   void notePostUse(Object O, Expr *Use) {
12263     UsageInfo &U = UsageMap[O];
12264     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12265     addUsage(U, O, Use, UK_Use);
12266   }
12267 
12268   void notePreMod(Object O, Expr *Mod) {
12269     UsageInfo &U = UsageMap[O];
12270     // Modifications conflict with other modifications and with uses.
12271     checkUsage(O, U, Mod, UK_ModAsValue, true);
12272     checkUsage(O, U, Mod, UK_Use, false);
12273   }
12274 
12275   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12276     UsageInfo &U = UsageMap[O];
12277     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12278     addUsage(U, O, Use, UK);
12279   }
12280 
12281 public:
12282   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12283       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12284     Visit(E);
12285   }
12286 
12287   void VisitStmt(Stmt *S) {
12288     // Skip all statements which aren't expressions for now.
12289   }
12290 
12291   void VisitExpr(Expr *E) {
12292     // By default, just recurse to evaluated subexpressions.
12293     Base::VisitStmt(E);
12294   }
12295 
12296   void VisitCastExpr(CastExpr *E) {
12297     Object O = Object();
12298     if (E->getCastKind() == CK_LValueToRValue)
12299       O = getObject(E->getSubExpr(), false);
12300 
12301     if (O)
12302       notePreUse(O, E);
12303     VisitExpr(E);
12304     if (O)
12305       notePostUse(O, E);
12306   }
12307 
12308   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12309     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12310     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12311     SequenceTree::Seq OldRegion = Region;
12312 
12313     {
12314       SequencedSubexpression SeqBefore(*this);
12315       Region = BeforeRegion;
12316       Visit(SequencedBefore);
12317     }
12318 
12319     Region = AfterRegion;
12320     Visit(SequencedAfter);
12321 
12322     Region = OldRegion;
12323 
12324     Tree.merge(BeforeRegion);
12325     Tree.merge(AfterRegion);
12326   }
12327 
12328   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12329     // C++17 [expr.sub]p1:
12330     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12331     //   expression E1 is sequenced before the expression E2.
12332     if (SemaRef.getLangOpts().CPlusPlus17)
12333       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12334     else
12335       Base::VisitStmt(ASE);
12336   }
12337 
12338   void VisitBinComma(BinaryOperator *BO) {
12339     // C++11 [expr.comma]p1:
12340     //   Every value computation and side effect associated with the left
12341     //   expression is sequenced before every value computation and side
12342     //   effect associated with the right expression.
12343     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12344   }
12345 
12346   void VisitBinAssign(BinaryOperator *BO) {
12347     // The modification is sequenced after the value computation of the LHS
12348     // and RHS, so check it before inspecting the operands and update the
12349     // map afterwards.
12350     Object O = getObject(BO->getLHS(), true);
12351     if (!O)
12352       return VisitExpr(BO);
12353 
12354     notePreMod(O, BO);
12355 
12356     // C++11 [expr.ass]p7:
12357     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12358     //   only once.
12359     //
12360     // Therefore, for a compound assignment operator, O is considered used
12361     // everywhere except within the evaluation of E1 itself.
12362     if (isa<CompoundAssignOperator>(BO))
12363       notePreUse(O, BO);
12364 
12365     Visit(BO->getLHS());
12366 
12367     if (isa<CompoundAssignOperator>(BO))
12368       notePostUse(O, BO);
12369 
12370     Visit(BO->getRHS());
12371 
12372     // C++11 [expr.ass]p1:
12373     //   the assignment is sequenced [...] before the value computation of the
12374     //   assignment expression.
12375     // C11 6.5.16/3 has no such rule.
12376     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12377                                                        : UK_ModAsSideEffect);
12378   }
12379 
12380   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12381     VisitBinAssign(CAO);
12382   }
12383 
12384   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12385   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12386   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12387     Object O = getObject(UO->getSubExpr(), true);
12388     if (!O)
12389       return VisitExpr(UO);
12390 
12391     notePreMod(O, UO);
12392     Visit(UO->getSubExpr());
12393     // C++11 [expr.pre.incr]p1:
12394     //   the expression ++x is equivalent to x+=1
12395     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12396                                                        : UK_ModAsSideEffect);
12397   }
12398 
12399   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12400   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12401   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12402     Object O = getObject(UO->getSubExpr(), true);
12403     if (!O)
12404       return VisitExpr(UO);
12405 
12406     notePreMod(O, UO);
12407     Visit(UO->getSubExpr());
12408     notePostMod(O, UO, UK_ModAsSideEffect);
12409   }
12410 
12411   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12412   void VisitBinLOr(BinaryOperator *BO) {
12413     // The side-effects of the LHS of an '&&' are sequenced before the
12414     // value computation of the RHS, and hence before the value computation
12415     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12416     // as if they were unconditionally sequenced.
12417     EvaluationTracker Eval(*this);
12418     {
12419       SequencedSubexpression Sequenced(*this);
12420       Visit(BO->getLHS());
12421     }
12422 
12423     bool Result;
12424     if (Eval.evaluate(BO->getLHS(), Result)) {
12425       if (!Result)
12426         Visit(BO->getRHS());
12427     } else {
12428       // Check for unsequenced operations in the RHS, treating it as an
12429       // entirely separate evaluation.
12430       //
12431       // FIXME: If there are operations in the RHS which are unsequenced
12432       // with respect to operations outside the RHS, and those operations
12433       // are unconditionally evaluated, diagnose them.
12434       WorkList.push_back(BO->getRHS());
12435     }
12436   }
12437   void VisitBinLAnd(BinaryOperator *BO) {
12438     EvaluationTracker Eval(*this);
12439     {
12440       SequencedSubexpression Sequenced(*this);
12441       Visit(BO->getLHS());
12442     }
12443 
12444     bool Result;
12445     if (Eval.evaluate(BO->getLHS(), Result)) {
12446       if (Result)
12447         Visit(BO->getRHS());
12448     } else {
12449       WorkList.push_back(BO->getRHS());
12450     }
12451   }
12452 
12453   // Only visit the condition, unless we can be sure which subexpression will
12454   // be chosen.
12455   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12456     EvaluationTracker Eval(*this);
12457     {
12458       SequencedSubexpression Sequenced(*this);
12459       Visit(CO->getCond());
12460     }
12461 
12462     bool Result;
12463     if (Eval.evaluate(CO->getCond(), Result))
12464       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12465     else {
12466       WorkList.push_back(CO->getTrueExpr());
12467       WorkList.push_back(CO->getFalseExpr());
12468     }
12469   }
12470 
12471   void VisitCallExpr(CallExpr *CE) {
12472     // C++11 [intro.execution]p15:
12473     //   When calling a function [...], every value computation and side effect
12474     //   associated with any argument expression, or with the postfix expression
12475     //   designating the called function, is sequenced before execution of every
12476     //   expression or statement in the body of the function [and thus before
12477     //   the value computation of its result].
12478     SequencedSubexpression Sequenced(*this);
12479     Base::VisitCallExpr(CE);
12480 
12481     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12482   }
12483 
12484   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12485     // This is a call, so all subexpressions are sequenced before the result.
12486     SequencedSubexpression Sequenced(*this);
12487 
12488     if (!CCE->isListInitialization())
12489       return VisitExpr(CCE);
12490 
12491     // In C++11, list initializations are sequenced.
12492     SmallVector<SequenceTree::Seq, 32> Elts;
12493     SequenceTree::Seq Parent = Region;
12494     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12495                                         E = CCE->arg_end();
12496          I != E; ++I) {
12497       Region = Tree.allocate(Parent);
12498       Elts.push_back(Region);
12499       Visit(*I);
12500     }
12501 
12502     // Forget that the initializers are sequenced.
12503     Region = Parent;
12504     for (unsigned I = 0; I < Elts.size(); ++I)
12505       Tree.merge(Elts[I]);
12506   }
12507 
12508   void VisitInitListExpr(InitListExpr *ILE) {
12509     if (!SemaRef.getLangOpts().CPlusPlus11)
12510       return VisitExpr(ILE);
12511 
12512     // In C++11, list initializations are sequenced.
12513     SmallVector<SequenceTree::Seq, 32> Elts;
12514     SequenceTree::Seq Parent = Region;
12515     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12516       Expr *E = ILE->getInit(I);
12517       if (!E) continue;
12518       Region = Tree.allocate(Parent);
12519       Elts.push_back(Region);
12520       Visit(E);
12521     }
12522 
12523     // Forget that the initializers are sequenced.
12524     Region = Parent;
12525     for (unsigned I = 0; I < Elts.size(); ++I)
12526       Tree.merge(Elts[I]);
12527   }
12528 };
12529 
12530 } // namespace
12531 
12532 void Sema::CheckUnsequencedOperations(Expr *E) {
12533   SmallVector<Expr *, 8> WorkList;
12534   WorkList.push_back(E);
12535   while (!WorkList.empty()) {
12536     Expr *Item = WorkList.pop_back_val();
12537     SequenceChecker(*this, Item, WorkList);
12538   }
12539 }
12540 
12541 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12542                               bool IsConstexpr) {
12543   llvm::SaveAndRestore<bool> ConstantContext(
12544       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12545   CheckImplicitConversions(E, CheckLoc);
12546   if (!E->isInstantiationDependent())
12547     CheckUnsequencedOperations(E);
12548   if (!IsConstexpr && !E->isValueDependent())
12549     CheckForIntOverflow(E);
12550   DiagnoseMisalignedMembers();
12551 }
12552 
12553 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12554                                        FieldDecl *BitField,
12555                                        Expr *Init) {
12556   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12557 }
12558 
12559 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12560                                          SourceLocation Loc) {
12561   if (!PType->isVariablyModifiedType())
12562     return;
12563   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12564     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12565     return;
12566   }
12567   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12568     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12569     return;
12570   }
12571   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12572     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12573     return;
12574   }
12575 
12576   const ArrayType *AT = S.Context.getAsArrayType(PType);
12577   if (!AT)
12578     return;
12579 
12580   if (AT->getSizeModifier() != ArrayType::Star) {
12581     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12582     return;
12583   }
12584 
12585   S.Diag(Loc, diag::err_array_star_in_function_definition);
12586 }
12587 
12588 /// CheckParmsForFunctionDef - Check that the parameters of the given
12589 /// function are appropriate for the definition of a function. This
12590 /// takes care of any checks that cannot be performed on the
12591 /// declaration itself, e.g., that the types of each of the function
12592 /// parameters are complete.
12593 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12594                                     bool CheckParameterNames) {
12595   bool HasInvalidParm = false;
12596   for (ParmVarDecl *Param : Parameters) {
12597     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12598     // function declarator that is part of a function definition of
12599     // that function shall not have incomplete type.
12600     //
12601     // This is also C++ [dcl.fct]p6.
12602     if (!Param->isInvalidDecl() &&
12603         RequireCompleteType(Param->getLocation(), Param->getType(),
12604                             diag::err_typecheck_decl_incomplete_type)) {
12605       Param->setInvalidDecl();
12606       HasInvalidParm = true;
12607     }
12608 
12609     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12610     // declaration of each parameter shall include an identifier.
12611     if (CheckParameterNames &&
12612         Param->getIdentifier() == nullptr &&
12613         !Param->isImplicit() &&
12614         !getLangOpts().CPlusPlus)
12615       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12616 
12617     // C99 6.7.5.3p12:
12618     //   If the function declarator is not part of a definition of that
12619     //   function, parameters may have incomplete type and may use the [*]
12620     //   notation in their sequences of declarator specifiers to specify
12621     //   variable length array types.
12622     QualType PType = Param->getOriginalType();
12623     // FIXME: This diagnostic should point the '[*]' if source-location
12624     // information is added for it.
12625     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12626 
12627     // If the parameter is a c++ class type and it has to be destructed in the
12628     // callee function, declare the destructor so that it can be called by the
12629     // callee function. Do not perform any direct access check on the dtor here.
12630     if (!Param->isInvalidDecl()) {
12631       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12632         if (!ClassDecl->isInvalidDecl() &&
12633             !ClassDecl->hasIrrelevantDestructor() &&
12634             !ClassDecl->isDependentContext() &&
12635             ClassDecl->isParamDestroyedInCallee()) {
12636           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12637           MarkFunctionReferenced(Param->getLocation(), Destructor);
12638           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12639         }
12640       }
12641     }
12642 
12643     // Parameters with the pass_object_size attribute only need to be marked
12644     // constant at function definitions. Because we lack information about
12645     // whether we're on a declaration or definition when we're instantiating the
12646     // attribute, we need to check for constness here.
12647     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12648       if (!Param->getType().isConstQualified())
12649         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12650             << Attr->getSpelling() << 1;
12651 
12652     // Check for parameter names shadowing fields from the class.
12653     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12654       // The owning context for the parameter should be the function, but we
12655       // want to see if this function's declaration context is a record.
12656       DeclContext *DC = Param->getDeclContext();
12657       if (DC && DC->isFunctionOrMethod()) {
12658         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12659           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12660                                      RD, /*DeclIsField*/ false);
12661       }
12662     }
12663   }
12664 
12665   return HasInvalidParm;
12666 }
12667 
12668 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12669 /// or MemberExpr.
12670 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12671                               ASTContext &Context) {
12672   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12673     return Context.getDeclAlign(DRE->getDecl());
12674 
12675   if (const auto *ME = dyn_cast<MemberExpr>(E))
12676     return Context.getDeclAlign(ME->getMemberDecl());
12677 
12678   return TypeAlign;
12679 }
12680 
12681 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12682 /// pointer cast increases the alignment requirements.
12683 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12684   // This is actually a lot of work to potentially be doing on every
12685   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12686   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12687     return;
12688 
12689   // Ignore dependent types.
12690   if (T->isDependentType() || Op->getType()->isDependentType())
12691     return;
12692 
12693   // Require that the destination be a pointer type.
12694   const PointerType *DestPtr = T->getAs<PointerType>();
12695   if (!DestPtr) return;
12696 
12697   // If the destination has alignment 1, we're done.
12698   QualType DestPointee = DestPtr->getPointeeType();
12699   if (DestPointee->isIncompleteType()) return;
12700   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12701   if (DestAlign.isOne()) return;
12702 
12703   // Require that the source be a pointer type.
12704   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12705   if (!SrcPtr) return;
12706   QualType SrcPointee = SrcPtr->getPointeeType();
12707 
12708   // Whitelist casts from cv void*.  We already implicitly
12709   // whitelisted casts to cv void*, since they have alignment 1.
12710   // Also whitelist casts involving incomplete types, which implicitly
12711   // includes 'void'.
12712   if (SrcPointee->isIncompleteType()) return;
12713 
12714   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12715 
12716   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12717     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12718       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12719   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12720     if (UO->getOpcode() == UO_AddrOf)
12721       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12722   }
12723 
12724   if (SrcAlign >= DestAlign) return;
12725 
12726   Diag(TRange.getBegin(), diag::warn_cast_align)
12727     << Op->getType() << T
12728     << static_cast<unsigned>(SrcAlign.getQuantity())
12729     << static_cast<unsigned>(DestAlign.getQuantity())
12730     << TRange << Op->getSourceRange();
12731 }
12732 
12733 /// Check whether this array fits the idiom of a size-one tail padded
12734 /// array member of a struct.
12735 ///
12736 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12737 /// commonly used to emulate flexible arrays in C89 code.
12738 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12739                                     const NamedDecl *ND) {
12740   if (Size != 1 || !ND) return false;
12741 
12742   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12743   if (!FD) return false;
12744 
12745   // Don't consider sizes resulting from macro expansions or template argument
12746   // substitution to form C89 tail-padded arrays.
12747 
12748   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12749   while (TInfo) {
12750     TypeLoc TL = TInfo->getTypeLoc();
12751     // Look through typedefs.
12752     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12753       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12754       TInfo = TDL->getTypeSourceInfo();
12755       continue;
12756     }
12757     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12758       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12759       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12760         return false;
12761     }
12762     break;
12763   }
12764 
12765   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12766   if (!RD) return false;
12767   if (RD->isUnion()) return false;
12768   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12769     if (!CRD->isStandardLayout()) return false;
12770   }
12771 
12772   // See if this is the last field decl in the record.
12773   const Decl *D = FD;
12774   while ((D = D->getNextDeclInContext()))
12775     if (isa<FieldDecl>(D))
12776       return false;
12777   return true;
12778 }
12779 
12780 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12781                             const ArraySubscriptExpr *ASE,
12782                             bool AllowOnePastEnd, bool IndexNegated) {
12783   // Already diagnosed by the constant evaluator.
12784   if (isConstantEvaluated())
12785     return;
12786 
12787   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12788   if (IndexExpr->isValueDependent())
12789     return;
12790 
12791   const Type *EffectiveType =
12792       BaseExpr->getType()->getPointeeOrArrayElementType();
12793   BaseExpr = BaseExpr->IgnoreParenCasts();
12794   const ConstantArrayType *ArrayTy =
12795       Context.getAsConstantArrayType(BaseExpr->getType());
12796 
12797   if (!ArrayTy)
12798     return;
12799 
12800   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12801   if (EffectiveType->isDependentType() || BaseType->isDependentType())
12802     return;
12803 
12804   Expr::EvalResult Result;
12805   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12806     return;
12807 
12808   llvm::APSInt index = Result.Val.getInt();
12809   if (IndexNegated)
12810     index = -index;
12811 
12812   const NamedDecl *ND = nullptr;
12813   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12814     ND = DRE->getDecl();
12815   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12816     ND = ME->getMemberDecl();
12817 
12818   if (index.isUnsigned() || !index.isNegative()) {
12819     // It is possible that the type of the base expression after
12820     // IgnoreParenCasts is incomplete, even though the type of the base
12821     // expression before IgnoreParenCasts is complete (see PR39746 for an
12822     // example). In this case we have no information about whether the array
12823     // access exceeds the array bounds. However we can still diagnose an array
12824     // access which precedes the array bounds.
12825     if (BaseType->isIncompleteType())
12826       return;
12827 
12828     llvm::APInt size = ArrayTy->getSize();
12829     if (!size.isStrictlyPositive())
12830       return;
12831 
12832     if (BaseType != EffectiveType) {
12833       // Make sure we're comparing apples to apples when comparing index to size
12834       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12835       uint64_t array_typesize = Context.getTypeSize(BaseType);
12836       // Handle ptrarith_typesize being zero, such as when casting to void*
12837       if (!ptrarith_typesize) ptrarith_typesize = 1;
12838       if (ptrarith_typesize != array_typesize) {
12839         // There's a cast to a different size type involved
12840         uint64_t ratio = array_typesize / ptrarith_typesize;
12841         // TODO: Be smarter about handling cases where array_typesize is not a
12842         // multiple of ptrarith_typesize
12843         if (ptrarith_typesize * ratio == array_typesize)
12844           size *= llvm::APInt(size.getBitWidth(), ratio);
12845       }
12846     }
12847 
12848     if (size.getBitWidth() > index.getBitWidth())
12849       index = index.zext(size.getBitWidth());
12850     else if (size.getBitWidth() < index.getBitWidth())
12851       size = size.zext(index.getBitWidth());
12852 
12853     // For array subscripting the index must be less than size, but for pointer
12854     // arithmetic also allow the index (offset) to be equal to size since
12855     // computing the next address after the end of the array is legal and
12856     // commonly done e.g. in C++ iterators and range-based for loops.
12857     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12858       return;
12859 
12860     // Also don't warn for arrays of size 1 which are members of some
12861     // structure. These are often used to approximate flexible arrays in C89
12862     // code.
12863     if (IsTailPaddedMemberArray(*this, size, ND))
12864       return;
12865 
12866     // Suppress the warning if the subscript expression (as identified by the
12867     // ']' location) and the index expression are both from macro expansions
12868     // within a system header.
12869     if (ASE) {
12870       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12871           ASE->getRBracketLoc());
12872       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12873         SourceLocation IndexLoc =
12874             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12875         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12876           return;
12877       }
12878     }
12879 
12880     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12881     if (ASE)
12882       DiagID = diag::warn_array_index_exceeds_bounds;
12883 
12884     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12885                         PDiag(DiagID) << index.toString(10, true)
12886                                       << size.toString(10, true)
12887                                       << (unsigned)size.getLimitedValue(~0U)
12888                                       << IndexExpr->getSourceRange());
12889   } else {
12890     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12891     if (!ASE) {
12892       DiagID = diag::warn_ptr_arith_precedes_bounds;
12893       if (index.isNegative()) index = -index;
12894     }
12895 
12896     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12897                         PDiag(DiagID) << index.toString(10, true)
12898                                       << IndexExpr->getSourceRange());
12899   }
12900 
12901   if (!ND) {
12902     // Try harder to find a NamedDecl to point at in the note.
12903     while (const ArraySubscriptExpr *ASE =
12904            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12905       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12906     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12907       ND = DRE->getDecl();
12908     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12909       ND = ME->getMemberDecl();
12910   }
12911 
12912   if (ND)
12913     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12914                         PDiag(diag::note_array_index_out_of_bounds)
12915                             << ND->getDeclName());
12916 }
12917 
12918 void Sema::CheckArrayAccess(const Expr *expr) {
12919   int AllowOnePastEnd = 0;
12920   while (expr) {
12921     expr = expr->IgnoreParenImpCasts();
12922     switch (expr->getStmtClass()) {
12923       case Stmt::ArraySubscriptExprClass: {
12924         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12925         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12926                          AllowOnePastEnd > 0);
12927         expr = ASE->getBase();
12928         break;
12929       }
12930       case Stmt::MemberExprClass: {
12931         expr = cast<MemberExpr>(expr)->getBase();
12932         break;
12933       }
12934       case Stmt::OMPArraySectionExprClass: {
12935         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12936         if (ASE->getLowerBound())
12937           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12938                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12939         return;
12940       }
12941       case Stmt::UnaryOperatorClass: {
12942         // Only unwrap the * and & unary operators
12943         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12944         expr = UO->getSubExpr();
12945         switch (UO->getOpcode()) {
12946           case UO_AddrOf:
12947             AllowOnePastEnd++;
12948             break;
12949           case UO_Deref:
12950             AllowOnePastEnd--;
12951             break;
12952           default:
12953             return;
12954         }
12955         break;
12956       }
12957       case Stmt::ConditionalOperatorClass: {
12958         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12959         if (const Expr *lhs = cond->getLHS())
12960           CheckArrayAccess(lhs);
12961         if (const Expr *rhs = cond->getRHS())
12962           CheckArrayAccess(rhs);
12963         return;
12964       }
12965       case Stmt::CXXOperatorCallExprClass: {
12966         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12967         for (const auto *Arg : OCE->arguments())
12968           CheckArrayAccess(Arg);
12969         return;
12970       }
12971       default:
12972         return;
12973     }
12974   }
12975 }
12976 
12977 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12978 
12979 namespace {
12980 
12981 struct RetainCycleOwner {
12982   VarDecl *Variable = nullptr;
12983   SourceRange Range;
12984   SourceLocation Loc;
12985   bool Indirect = false;
12986 
12987   RetainCycleOwner() = default;
12988 
12989   void setLocsFrom(Expr *e) {
12990     Loc = e->getExprLoc();
12991     Range = e->getSourceRange();
12992   }
12993 };
12994 
12995 } // namespace
12996 
12997 /// Consider whether capturing the given variable can possibly lead to
12998 /// a retain cycle.
12999 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13000   // In ARC, it's captured strongly iff the variable has __strong
13001   // lifetime.  In MRR, it's captured strongly if the variable is
13002   // __block and has an appropriate type.
13003   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13004     return false;
13005 
13006   owner.Variable = var;
13007   if (ref)
13008     owner.setLocsFrom(ref);
13009   return true;
13010 }
13011 
13012 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13013   while (true) {
13014     e = e->IgnoreParens();
13015     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13016       switch (cast->getCastKind()) {
13017       case CK_BitCast:
13018       case CK_LValueBitCast:
13019       case CK_LValueToRValue:
13020       case CK_ARCReclaimReturnedObject:
13021         e = cast->getSubExpr();
13022         continue;
13023 
13024       default:
13025         return false;
13026       }
13027     }
13028 
13029     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13030       ObjCIvarDecl *ivar = ref->getDecl();
13031       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13032         return false;
13033 
13034       // Try to find a retain cycle in the base.
13035       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13036         return false;
13037 
13038       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13039       owner.Indirect = true;
13040       return true;
13041     }
13042 
13043     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13044       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13045       if (!var) return false;
13046       return considerVariable(var, ref, owner);
13047     }
13048 
13049     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13050       if (member->isArrow()) return false;
13051 
13052       // Don't count this as an indirect ownership.
13053       e = member->getBase();
13054       continue;
13055     }
13056 
13057     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13058       // Only pay attention to pseudo-objects on property references.
13059       ObjCPropertyRefExpr *pre
13060         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13061                                               ->IgnoreParens());
13062       if (!pre) return false;
13063       if (pre->isImplicitProperty()) return false;
13064       ObjCPropertyDecl *property = pre->getExplicitProperty();
13065       if (!property->isRetaining() &&
13066           !(property->getPropertyIvarDecl() &&
13067             property->getPropertyIvarDecl()->getType()
13068               .getObjCLifetime() == Qualifiers::OCL_Strong))
13069           return false;
13070 
13071       owner.Indirect = true;
13072       if (pre->isSuperReceiver()) {
13073         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13074         if (!owner.Variable)
13075           return false;
13076         owner.Loc = pre->getLocation();
13077         owner.Range = pre->getSourceRange();
13078         return true;
13079       }
13080       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13081                               ->getSourceExpr());
13082       continue;
13083     }
13084 
13085     // Array ivars?
13086 
13087     return false;
13088   }
13089 }
13090 
13091 namespace {
13092 
13093   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13094     ASTContext &Context;
13095     VarDecl *Variable;
13096     Expr *Capturer = nullptr;
13097     bool VarWillBeReased = false;
13098 
13099     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13100         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13101           Context(Context), Variable(variable) {}
13102 
13103     void VisitDeclRefExpr(DeclRefExpr *ref) {
13104       if (ref->getDecl() == Variable && !Capturer)
13105         Capturer = ref;
13106     }
13107 
13108     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13109       if (Capturer) return;
13110       Visit(ref->getBase());
13111       if (Capturer && ref->isFreeIvar())
13112         Capturer = ref;
13113     }
13114 
13115     void VisitBlockExpr(BlockExpr *block) {
13116       // Look inside nested blocks
13117       if (block->getBlockDecl()->capturesVariable(Variable))
13118         Visit(block->getBlockDecl()->getBody());
13119     }
13120 
13121     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13122       if (Capturer) return;
13123       if (OVE->getSourceExpr())
13124         Visit(OVE->getSourceExpr());
13125     }
13126 
13127     void VisitBinaryOperator(BinaryOperator *BinOp) {
13128       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13129         return;
13130       Expr *LHS = BinOp->getLHS();
13131       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13132         if (DRE->getDecl() != Variable)
13133           return;
13134         if (Expr *RHS = BinOp->getRHS()) {
13135           RHS = RHS->IgnoreParenCasts();
13136           llvm::APSInt Value;
13137           VarWillBeReased =
13138             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13139         }
13140       }
13141     }
13142   };
13143 
13144 } // namespace
13145 
13146 /// Check whether the given argument is a block which captures a
13147 /// variable.
13148 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13149   assert(owner.Variable && owner.Loc.isValid());
13150 
13151   e = e->IgnoreParenCasts();
13152 
13153   // Look through [^{...} copy] and Block_copy(^{...}).
13154   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13155     Selector Cmd = ME->getSelector();
13156     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13157       e = ME->getInstanceReceiver();
13158       if (!e)
13159         return nullptr;
13160       e = e->IgnoreParenCasts();
13161     }
13162   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13163     if (CE->getNumArgs() == 1) {
13164       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13165       if (Fn) {
13166         const IdentifierInfo *FnI = Fn->getIdentifier();
13167         if (FnI && FnI->isStr("_Block_copy")) {
13168           e = CE->getArg(0)->IgnoreParenCasts();
13169         }
13170       }
13171     }
13172   }
13173 
13174   BlockExpr *block = dyn_cast<BlockExpr>(e);
13175   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13176     return nullptr;
13177 
13178   FindCaptureVisitor visitor(S.Context, owner.Variable);
13179   visitor.Visit(block->getBlockDecl()->getBody());
13180   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13181 }
13182 
13183 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13184                                 RetainCycleOwner &owner) {
13185   assert(capturer);
13186   assert(owner.Variable && owner.Loc.isValid());
13187 
13188   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13189     << owner.Variable << capturer->getSourceRange();
13190   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13191     << owner.Indirect << owner.Range;
13192 }
13193 
13194 /// Check for a keyword selector that starts with the word 'add' or
13195 /// 'set'.
13196 static bool isSetterLikeSelector(Selector sel) {
13197   if (sel.isUnarySelector()) return false;
13198 
13199   StringRef str = sel.getNameForSlot(0);
13200   while (!str.empty() && str.front() == '_') str = str.substr(1);
13201   if (str.startswith("set"))
13202     str = str.substr(3);
13203   else if (str.startswith("add")) {
13204     // Specially whitelist 'addOperationWithBlock:'.
13205     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13206       return false;
13207     str = str.substr(3);
13208   }
13209   else
13210     return false;
13211 
13212   if (str.empty()) return true;
13213   return !isLowercase(str.front());
13214 }
13215 
13216 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13217                                                     ObjCMessageExpr *Message) {
13218   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13219                                                 Message->getReceiverInterface(),
13220                                                 NSAPI::ClassId_NSMutableArray);
13221   if (!IsMutableArray) {
13222     return None;
13223   }
13224 
13225   Selector Sel = Message->getSelector();
13226 
13227   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13228     S.NSAPIObj->getNSArrayMethodKind(Sel);
13229   if (!MKOpt) {
13230     return None;
13231   }
13232 
13233   NSAPI::NSArrayMethodKind MK = *MKOpt;
13234 
13235   switch (MK) {
13236     case NSAPI::NSMutableArr_addObject:
13237     case NSAPI::NSMutableArr_insertObjectAtIndex:
13238     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13239       return 0;
13240     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13241       return 1;
13242 
13243     default:
13244       return None;
13245   }
13246 
13247   return None;
13248 }
13249 
13250 static
13251 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13252                                                   ObjCMessageExpr *Message) {
13253   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13254                                             Message->getReceiverInterface(),
13255                                             NSAPI::ClassId_NSMutableDictionary);
13256   if (!IsMutableDictionary) {
13257     return None;
13258   }
13259 
13260   Selector Sel = Message->getSelector();
13261 
13262   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13263     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13264   if (!MKOpt) {
13265     return None;
13266   }
13267 
13268   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13269 
13270   switch (MK) {
13271     case NSAPI::NSMutableDict_setObjectForKey:
13272     case NSAPI::NSMutableDict_setValueForKey:
13273     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13274       return 0;
13275 
13276     default:
13277       return None;
13278   }
13279 
13280   return None;
13281 }
13282 
13283 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13284   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13285                                                 Message->getReceiverInterface(),
13286                                                 NSAPI::ClassId_NSMutableSet);
13287 
13288   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13289                                             Message->getReceiverInterface(),
13290                                             NSAPI::ClassId_NSMutableOrderedSet);
13291   if (!IsMutableSet && !IsMutableOrderedSet) {
13292     return None;
13293   }
13294 
13295   Selector Sel = Message->getSelector();
13296 
13297   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13298   if (!MKOpt) {
13299     return None;
13300   }
13301 
13302   NSAPI::NSSetMethodKind MK = *MKOpt;
13303 
13304   switch (MK) {
13305     case NSAPI::NSMutableSet_addObject:
13306     case NSAPI::NSOrderedSet_setObjectAtIndex:
13307     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13308     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13309       return 0;
13310     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13311       return 1;
13312   }
13313 
13314   return None;
13315 }
13316 
13317 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13318   if (!Message->isInstanceMessage()) {
13319     return;
13320   }
13321 
13322   Optional<int> ArgOpt;
13323 
13324   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13325       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13326       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13327     return;
13328   }
13329 
13330   int ArgIndex = *ArgOpt;
13331 
13332   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13333   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13334     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13335   }
13336 
13337   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13338     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13339       if (ArgRE->isObjCSelfExpr()) {
13340         Diag(Message->getSourceRange().getBegin(),
13341              diag::warn_objc_circular_container)
13342           << ArgRE->getDecl() << StringRef("'super'");
13343       }
13344     }
13345   } else {
13346     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13347 
13348     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13349       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13350     }
13351 
13352     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13353       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13354         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13355           ValueDecl *Decl = ReceiverRE->getDecl();
13356           Diag(Message->getSourceRange().getBegin(),
13357                diag::warn_objc_circular_container)
13358             << Decl << Decl;
13359           if (!ArgRE->isObjCSelfExpr()) {
13360             Diag(Decl->getLocation(),
13361                  diag::note_objc_circular_container_declared_here)
13362               << Decl;
13363           }
13364         }
13365       }
13366     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13367       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13368         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13369           ObjCIvarDecl *Decl = IvarRE->getDecl();
13370           Diag(Message->getSourceRange().getBegin(),
13371                diag::warn_objc_circular_container)
13372             << Decl << Decl;
13373           Diag(Decl->getLocation(),
13374                diag::note_objc_circular_container_declared_here)
13375             << Decl;
13376         }
13377       }
13378     }
13379   }
13380 }
13381 
13382 /// Check a message send to see if it's likely to cause a retain cycle.
13383 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13384   // Only check instance methods whose selector looks like a setter.
13385   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13386     return;
13387 
13388   // Try to find a variable that the receiver is strongly owned by.
13389   RetainCycleOwner owner;
13390   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13391     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13392       return;
13393   } else {
13394     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13395     owner.Variable = getCurMethodDecl()->getSelfDecl();
13396     owner.Loc = msg->getSuperLoc();
13397     owner.Range = msg->getSuperLoc();
13398   }
13399 
13400   // Check whether the receiver is captured by any of the arguments.
13401   const ObjCMethodDecl *MD = msg->getMethodDecl();
13402   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13403     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13404       // noescape blocks should not be retained by the method.
13405       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13406         continue;
13407       return diagnoseRetainCycle(*this, capturer, owner);
13408     }
13409   }
13410 }
13411 
13412 /// Check a property assign to see if it's likely to cause a retain cycle.
13413 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13414   RetainCycleOwner owner;
13415   if (!findRetainCycleOwner(*this, receiver, owner))
13416     return;
13417 
13418   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13419     diagnoseRetainCycle(*this, capturer, owner);
13420 }
13421 
13422 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13423   RetainCycleOwner Owner;
13424   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13425     return;
13426 
13427   // Because we don't have an expression for the variable, we have to set the
13428   // location explicitly here.
13429   Owner.Loc = Var->getLocation();
13430   Owner.Range = Var->getSourceRange();
13431 
13432   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13433     diagnoseRetainCycle(*this, Capturer, Owner);
13434 }
13435 
13436 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13437                                      Expr *RHS, bool isProperty) {
13438   // Check if RHS is an Objective-C object literal, which also can get
13439   // immediately zapped in a weak reference.  Note that we explicitly
13440   // allow ObjCStringLiterals, since those are designed to never really die.
13441   RHS = RHS->IgnoreParenImpCasts();
13442 
13443   // This enum needs to match with the 'select' in
13444   // warn_objc_arc_literal_assign (off-by-1).
13445   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13446   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13447     return false;
13448 
13449   S.Diag(Loc, diag::warn_arc_literal_assign)
13450     << (unsigned) Kind
13451     << (isProperty ? 0 : 1)
13452     << RHS->getSourceRange();
13453 
13454   return true;
13455 }
13456 
13457 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13458                                     Qualifiers::ObjCLifetime LT,
13459                                     Expr *RHS, bool isProperty) {
13460   // Strip off any implicit cast added to get to the one ARC-specific.
13461   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13462     if (cast->getCastKind() == CK_ARCConsumeObject) {
13463       S.Diag(Loc, diag::warn_arc_retained_assign)
13464         << (LT == Qualifiers::OCL_ExplicitNone)
13465         << (isProperty ? 0 : 1)
13466         << RHS->getSourceRange();
13467       return true;
13468     }
13469     RHS = cast->getSubExpr();
13470   }
13471 
13472   if (LT == Qualifiers::OCL_Weak &&
13473       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13474     return true;
13475 
13476   return false;
13477 }
13478 
13479 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13480                               QualType LHS, Expr *RHS) {
13481   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13482 
13483   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13484     return false;
13485 
13486   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13487     return true;
13488 
13489   return false;
13490 }
13491 
13492 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13493                               Expr *LHS, Expr *RHS) {
13494   QualType LHSType;
13495   // PropertyRef on LHS type need be directly obtained from
13496   // its declaration as it has a PseudoType.
13497   ObjCPropertyRefExpr *PRE
13498     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13499   if (PRE && !PRE->isImplicitProperty()) {
13500     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13501     if (PD)
13502       LHSType = PD->getType();
13503   }
13504 
13505   if (LHSType.isNull())
13506     LHSType = LHS->getType();
13507 
13508   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13509 
13510   if (LT == Qualifiers::OCL_Weak) {
13511     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13512       getCurFunction()->markSafeWeakUse(LHS);
13513   }
13514 
13515   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13516     return;
13517 
13518   // FIXME. Check for other life times.
13519   if (LT != Qualifiers::OCL_None)
13520     return;
13521 
13522   if (PRE) {
13523     if (PRE->isImplicitProperty())
13524       return;
13525     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13526     if (!PD)
13527       return;
13528 
13529     unsigned Attributes = PD->getPropertyAttributes();
13530     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13531       // when 'assign' attribute was not explicitly specified
13532       // by user, ignore it and rely on property type itself
13533       // for lifetime info.
13534       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13535       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13536           LHSType->isObjCRetainableType())
13537         return;
13538 
13539       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13540         if (cast->getCastKind() == CK_ARCConsumeObject) {
13541           Diag(Loc, diag::warn_arc_retained_property_assign)
13542           << RHS->getSourceRange();
13543           return;
13544         }
13545         RHS = cast->getSubExpr();
13546       }
13547     }
13548     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13549       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13550         return;
13551     }
13552   }
13553 }
13554 
13555 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13556 
13557 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13558                                         SourceLocation StmtLoc,
13559                                         const NullStmt *Body) {
13560   // Do not warn if the body is a macro that expands to nothing, e.g:
13561   //
13562   // #define CALL(x)
13563   // if (condition)
13564   //   CALL(0);
13565   if (Body->hasLeadingEmptyMacro())
13566     return false;
13567 
13568   // Get line numbers of statement and body.
13569   bool StmtLineInvalid;
13570   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13571                                                       &StmtLineInvalid);
13572   if (StmtLineInvalid)
13573     return false;
13574 
13575   bool BodyLineInvalid;
13576   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13577                                                       &BodyLineInvalid);
13578   if (BodyLineInvalid)
13579     return false;
13580 
13581   // Warn if null statement and body are on the same line.
13582   if (StmtLine != BodyLine)
13583     return false;
13584 
13585   return true;
13586 }
13587 
13588 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13589                                  const Stmt *Body,
13590                                  unsigned DiagID) {
13591   // Since this is a syntactic check, don't emit diagnostic for template
13592   // instantiations, this just adds noise.
13593   if (CurrentInstantiationScope)
13594     return;
13595 
13596   // The body should be a null statement.
13597   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13598   if (!NBody)
13599     return;
13600 
13601   // Do the usual checks.
13602   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13603     return;
13604 
13605   Diag(NBody->getSemiLoc(), DiagID);
13606   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13607 }
13608 
13609 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13610                                  const Stmt *PossibleBody) {
13611   assert(!CurrentInstantiationScope); // Ensured by caller
13612 
13613   SourceLocation StmtLoc;
13614   const Stmt *Body;
13615   unsigned DiagID;
13616   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13617     StmtLoc = FS->getRParenLoc();
13618     Body = FS->getBody();
13619     DiagID = diag::warn_empty_for_body;
13620   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13621     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13622     Body = WS->getBody();
13623     DiagID = diag::warn_empty_while_body;
13624   } else
13625     return; // Neither `for' nor `while'.
13626 
13627   // The body should be a null statement.
13628   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13629   if (!NBody)
13630     return;
13631 
13632   // Skip expensive checks if diagnostic is disabled.
13633   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13634     return;
13635 
13636   // Do the usual checks.
13637   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13638     return;
13639 
13640   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13641   // noise level low, emit diagnostics only if for/while is followed by a
13642   // CompoundStmt, e.g.:
13643   //    for (int i = 0; i < n; i++);
13644   //    {
13645   //      a(i);
13646   //    }
13647   // or if for/while is followed by a statement with more indentation
13648   // than for/while itself:
13649   //    for (int i = 0; i < n; i++);
13650   //      a(i);
13651   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13652   if (!ProbableTypo) {
13653     bool BodyColInvalid;
13654     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13655         PossibleBody->getBeginLoc(), &BodyColInvalid);
13656     if (BodyColInvalid)
13657       return;
13658 
13659     bool StmtColInvalid;
13660     unsigned StmtCol =
13661         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13662     if (StmtColInvalid)
13663       return;
13664 
13665     if (BodyCol > StmtCol)
13666       ProbableTypo = true;
13667   }
13668 
13669   if (ProbableTypo) {
13670     Diag(NBody->getSemiLoc(), DiagID);
13671     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13672   }
13673 }
13674 
13675 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13676 
13677 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13678 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13679                              SourceLocation OpLoc) {
13680   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13681     return;
13682 
13683   if (inTemplateInstantiation())
13684     return;
13685 
13686   // Strip parens and casts away.
13687   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13688   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13689 
13690   // Check for a call expression
13691   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13692   if (!CE || CE->getNumArgs() != 1)
13693     return;
13694 
13695   // Check for a call to std::move
13696   if (!CE->isCallToStdMove())
13697     return;
13698 
13699   // Get argument from std::move
13700   RHSExpr = CE->getArg(0);
13701 
13702   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13703   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13704 
13705   // Two DeclRefExpr's, check that the decls are the same.
13706   if (LHSDeclRef && RHSDeclRef) {
13707     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13708       return;
13709     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13710         RHSDeclRef->getDecl()->getCanonicalDecl())
13711       return;
13712 
13713     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13714                                         << LHSExpr->getSourceRange()
13715                                         << RHSExpr->getSourceRange();
13716     return;
13717   }
13718 
13719   // Member variables require a different approach to check for self moves.
13720   // MemberExpr's are the same if every nested MemberExpr refers to the same
13721   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13722   // the base Expr's are CXXThisExpr's.
13723   const Expr *LHSBase = LHSExpr;
13724   const Expr *RHSBase = RHSExpr;
13725   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13726   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13727   if (!LHSME || !RHSME)
13728     return;
13729 
13730   while (LHSME && RHSME) {
13731     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13732         RHSME->getMemberDecl()->getCanonicalDecl())
13733       return;
13734 
13735     LHSBase = LHSME->getBase();
13736     RHSBase = RHSME->getBase();
13737     LHSME = dyn_cast<MemberExpr>(LHSBase);
13738     RHSME = dyn_cast<MemberExpr>(RHSBase);
13739   }
13740 
13741   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13742   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13743   if (LHSDeclRef && RHSDeclRef) {
13744     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13745       return;
13746     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13747         RHSDeclRef->getDecl()->getCanonicalDecl())
13748       return;
13749 
13750     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13751                                         << LHSExpr->getSourceRange()
13752                                         << RHSExpr->getSourceRange();
13753     return;
13754   }
13755 
13756   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13757     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13758                                         << LHSExpr->getSourceRange()
13759                                         << RHSExpr->getSourceRange();
13760 }
13761 
13762 //===--- Layout compatibility ----------------------------------------------//
13763 
13764 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13765 
13766 /// Check if two enumeration types are layout-compatible.
13767 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13768   // C++11 [dcl.enum] p8:
13769   // Two enumeration types are layout-compatible if they have the same
13770   // underlying type.
13771   return ED1->isComplete() && ED2->isComplete() &&
13772          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13773 }
13774 
13775 /// Check if two fields are layout-compatible.
13776 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13777                                FieldDecl *Field2) {
13778   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13779     return false;
13780 
13781   if (Field1->isBitField() != Field2->isBitField())
13782     return false;
13783 
13784   if (Field1->isBitField()) {
13785     // Make sure that the bit-fields are the same length.
13786     unsigned Bits1 = Field1->getBitWidthValue(C);
13787     unsigned Bits2 = Field2->getBitWidthValue(C);
13788 
13789     if (Bits1 != Bits2)
13790       return false;
13791   }
13792 
13793   return true;
13794 }
13795 
13796 /// Check if two standard-layout structs are layout-compatible.
13797 /// (C++11 [class.mem] p17)
13798 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13799                                      RecordDecl *RD2) {
13800   // If both records are C++ classes, check that base classes match.
13801   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13802     // If one of records is a CXXRecordDecl we are in C++ mode,
13803     // thus the other one is a CXXRecordDecl, too.
13804     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13805     // Check number of base classes.
13806     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13807       return false;
13808 
13809     // Check the base classes.
13810     for (CXXRecordDecl::base_class_const_iterator
13811                Base1 = D1CXX->bases_begin(),
13812            BaseEnd1 = D1CXX->bases_end(),
13813               Base2 = D2CXX->bases_begin();
13814          Base1 != BaseEnd1;
13815          ++Base1, ++Base2) {
13816       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13817         return false;
13818     }
13819   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13820     // If only RD2 is a C++ class, it should have zero base classes.
13821     if (D2CXX->getNumBases() > 0)
13822       return false;
13823   }
13824 
13825   // Check the fields.
13826   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13827                              Field2End = RD2->field_end(),
13828                              Field1 = RD1->field_begin(),
13829                              Field1End = RD1->field_end();
13830   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13831     if (!isLayoutCompatible(C, *Field1, *Field2))
13832       return false;
13833   }
13834   if (Field1 != Field1End || Field2 != Field2End)
13835     return false;
13836 
13837   return true;
13838 }
13839 
13840 /// Check if two standard-layout unions are layout-compatible.
13841 /// (C++11 [class.mem] p18)
13842 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13843                                     RecordDecl *RD2) {
13844   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13845   for (auto *Field2 : RD2->fields())
13846     UnmatchedFields.insert(Field2);
13847 
13848   for (auto *Field1 : RD1->fields()) {
13849     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13850         I = UnmatchedFields.begin(),
13851         E = UnmatchedFields.end();
13852 
13853     for ( ; I != E; ++I) {
13854       if (isLayoutCompatible(C, Field1, *I)) {
13855         bool Result = UnmatchedFields.erase(*I);
13856         (void) Result;
13857         assert(Result);
13858         break;
13859       }
13860     }
13861     if (I == E)
13862       return false;
13863   }
13864 
13865   return UnmatchedFields.empty();
13866 }
13867 
13868 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13869                                RecordDecl *RD2) {
13870   if (RD1->isUnion() != RD2->isUnion())
13871     return false;
13872 
13873   if (RD1->isUnion())
13874     return isLayoutCompatibleUnion(C, RD1, RD2);
13875   else
13876     return isLayoutCompatibleStruct(C, RD1, RD2);
13877 }
13878 
13879 /// Check if two types are layout-compatible in C++11 sense.
13880 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13881   if (T1.isNull() || T2.isNull())
13882     return false;
13883 
13884   // C++11 [basic.types] p11:
13885   // If two types T1 and T2 are the same type, then T1 and T2 are
13886   // layout-compatible types.
13887   if (C.hasSameType(T1, T2))
13888     return true;
13889 
13890   T1 = T1.getCanonicalType().getUnqualifiedType();
13891   T2 = T2.getCanonicalType().getUnqualifiedType();
13892 
13893   const Type::TypeClass TC1 = T1->getTypeClass();
13894   const Type::TypeClass TC2 = T2->getTypeClass();
13895 
13896   if (TC1 != TC2)
13897     return false;
13898 
13899   if (TC1 == Type::Enum) {
13900     return isLayoutCompatible(C,
13901                               cast<EnumType>(T1)->getDecl(),
13902                               cast<EnumType>(T2)->getDecl());
13903   } else if (TC1 == Type::Record) {
13904     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13905       return false;
13906 
13907     return isLayoutCompatible(C,
13908                               cast<RecordType>(T1)->getDecl(),
13909                               cast<RecordType>(T2)->getDecl());
13910   }
13911 
13912   return false;
13913 }
13914 
13915 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13916 
13917 /// Given a type tag expression find the type tag itself.
13918 ///
13919 /// \param TypeExpr Type tag expression, as it appears in user's code.
13920 ///
13921 /// \param VD Declaration of an identifier that appears in a type tag.
13922 ///
13923 /// \param MagicValue Type tag magic value.
13924 ///
13925 /// \param isConstantEvaluated wether the evalaution should be performed in
13926 
13927 /// constant context.
13928 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13929                             const ValueDecl **VD, uint64_t *MagicValue,
13930                             bool isConstantEvaluated) {
13931   while(true) {
13932     if (!TypeExpr)
13933       return false;
13934 
13935     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13936 
13937     switch (TypeExpr->getStmtClass()) {
13938     case Stmt::UnaryOperatorClass: {
13939       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13940       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13941         TypeExpr = UO->getSubExpr();
13942         continue;
13943       }
13944       return false;
13945     }
13946 
13947     case Stmt::DeclRefExprClass: {
13948       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13949       *VD = DRE->getDecl();
13950       return true;
13951     }
13952 
13953     case Stmt::IntegerLiteralClass: {
13954       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13955       llvm::APInt MagicValueAPInt = IL->getValue();
13956       if (MagicValueAPInt.getActiveBits() <= 64) {
13957         *MagicValue = MagicValueAPInt.getZExtValue();
13958         return true;
13959       } else
13960         return false;
13961     }
13962 
13963     case Stmt::BinaryConditionalOperatorClass:
13964     case Stmt::ConditionalOperatorClass: {
13965       const AbstractConditionalOperator *ACO =
13966           cast<AbstractConditionalOperator>(TypeExpr);
13967       bool Result;
13968       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
13969                                                      isConstantEvaluated)) {
13970         if (Result)
13971           TypeExpr = ACO->getTrueExpr();
13972         else
13973           TypeExpr = ACO->getFalseExpr();
13974         continue;
13975       }
13976       return false;
13977     }
13978 
13979     case Stmt::BinaryOperatorClass: {
13980       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13981       if (BO->getOpcode() == BO_Comma) {
13982         TypeExpr = BO->getRHS();
13983         continue;
13984       }
13985       return false;
13986     }
13987 
13988     default:
13989       return false;
13990     }
13991   }
13992 }
13993 
13994 /// Retrieve the C type corresponding to type tag TypeExpr.
13995 ///
13996 /// \param TypeExpr Expression that specifies a type tag.
13997 ///
13998 /// \param MagicValues Registered magic values.
13999 ///
14000 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14001 ///        kind.
14002 ///
14003 /// \param TypeInfo Information about the corresponding C type.
14004 ///
14005 /// \param isConstantEvaluated wether the evalaution should be performed in
14006 /// constant context.
14007 ///
14008 /// \returns true if the corresponding C type was found.
14009 static bool GetMatchingCType(
14010     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14011     const ASTContext &Ctx,
14012     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14013         *MagicValues,
14014     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14015     bool isConstantEvaluated) {
14016   FoundWrongKind = false;
14017 
14018   // Variable declaration that has type_tag_for_datatype attribute.
14019   const ValueDecl *VD = nullptr;
14020 
14021   uint64_t MagicValue;
14022 
14023   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14024     return false;
14025 
14026   if (VD) {
14027     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14028       if (I->getArgumentKind() != ArgumentKind) {
14029         FoundWrongKind = true;
14030         return false;
14031       }
14032       TypeInfo.Type = I->getMatchingCType();
14033       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14034       TypeInfo.MustBeNull = I->getMustBeNull();
14035       return true;
14036     }
14037     return false;
14038   }
14039 
14040   if (!MagicValues)
14041     return false;
14042 
14043   llvm::DenseMap<Sema::TypeTagMagicValue,
14044                  Sema::TypeTagData>::const_iterator I =
14045       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14046   if (I == MagicValues->end())
14047     return false;
14048 
14049   TypeInfo = I->second;
14050   return true;
14051 }
14052 
14053 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14054                                       uint64_t MagicValue, QualType Type,
14055                                       bool LayoutCompatible,
14056                                       bool MustBeNull) {
14057   if (!TypeTagForDatatypeMagicValues)
14058     TypeTagForDatatypeMagicValues.reset(
14059         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14060 
14061   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14062   (*TypeTagForDatatypeMagicValues)[Magic] =
14063       TypeTagData(Type, LayoutCompatible, MustBeNull);
14064 }
14065 
14066 static bool IsSameCharType(QualType T1, QualType T2) {
14067   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14068   if (!BT1)
14069     return false;
14070 
14071   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14072   if (!BT2)
14073     return false;
14074 
14075   BuiltinType::Kind T1Kind = BT1->getKind();
14076   BuiltinType::Kind T2Kind = BT2->getKind();
14077 
14078   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14079          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14080          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14081          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14082 }
14083 
14084 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14085                                     const ArrayRef<const Expr *> ExprArgs,
14086                                     SourceLocation CallSiteLoc) {
14087   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14088   bool IsPointerAttr = Attr->getIsPointer();
14089 
14090   // Retrieve the argument representing the 'type_tag'.
14091   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14092   if (TypeTagIdxAST >= ExprArgs.size()) {
14093     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14094         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14095     return;
14096   }
14097   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14098   bool FoundWrongKind;
14099   TypeTagData TypeInfo;
14100   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14101                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14102                         TypeInfo, isConstantEvaluated())) {
14103     if (FoundWrongKind)
14104       Diag(TypeTagExpr->getExprLoc(),
14105            diag::warn_type_tag_for_datatype_wrong_kind)
14106         << TypeTagExpr->getSourceRange();
14107     return;
14108   }
14109 
14110   // Retrieve the argument representing the 'arg_idx'.
14111   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14112   if (ArgumentIdxAST >= ExprArgs.size()) {
14113     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14114         << 1 << Attr->getArgumentIdx().getSourceIndex();
14115     return;
14116   }
14117   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14118   if (IsPointerAttr) {
14119     // Skip implicit cast of pointer to `void *' (as a function argument).
14120     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14121       if (ICE->getType()->isVoidPointerType() &&
14122           ICE->getCastKind() == CK_BitCast)
14123         ArgumentExpr = ICE->getSubExpr();
14124   }
14125   QualType ArgumentType = ArgumentExpr->getType();
14126 
14127   // Passing a `void*' pointer shouldn't trigger a warning.
14128   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14129     return;
14130 
14131   if (TypeInfo.MustBeNull) {
14132     // Type tag with matching void type requires a null pointer.
14133     if (!ArgumentExpr->isNullPointerConstant(Context,
14134                                              Expr::NPC_ValueDependentIsNotNull)) {
14135       Diag(ArgumentExpr->getExprLoc(),
14136            diag::warn_type_safety_null_pointer_required)
14137           << ArgumentKind->getName()
14138           << ArgumentExpr->getSourceRange()
14139           << TypeTagExpr->getSourceRange();
14140     }
14141     return;
14142   }
14143 
14144   QualType RequiredType = TypeInfo.Type;
14145   if (IsPointerAttr)
14146     RequiredType = Context.getPointerType(RequiredType);
14147 
14148   bool mismatch = false;
14149   if (!TypeInfo.LayoutCompatible) {
14150     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14151 
14152     // C++11 [basic.fundamental] p1:
14153     // Plain char, signed char, and unsigned char are three distinct types.
14154     //
14155     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14156     // char' depending on the current char signedness mode.
14157     if (mismatch)
14158       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14159                                            RequiredType->getPointeeType())) ||
14160           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14161         mismatch = false;
14162   } else
14163     if (IsPointerAttr)
14164       mismatch = !isLayoutCompatible(Context,
14165                                      ArgumentType->getPointeeType(),
14166                                      RequiredType->getPointeeType());
14167     else
14168       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14169 
14170   if (mismatch)
14171     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14172         << ArgumentType << ArgumentKind
14173         << TypeInfo.LayoutCompatible << RequiredType
14174         << ArgumentExpr->getSourceRange()
14175         << TypeTagExpr->getSourceRange();
14176 }
14177 
14178 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14179                                          CharUnits Alignment) {
14180   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14181 }
14182 
14183 void Sema::DiagnoseMisalignedMembers() {
14184   for (MisalignedMember &m : MisalignedMembers) {
14185     const NamedDecl *ND = m.RD;
14186     if (ND->getName().empty()) {
14187       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14188         ND = TD;
14189     }
14190     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14191         << m.MD << ND << m.E->getSourceRange();
14192   }
14193   MisalignedMembers.clear();
14194 }
14195 
14196 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14197   E = E->IgnoreParens();
14198   if (!T->isPointerType() && !T->isIntegerType())
14199     return;
14200   if (isa<UnaryOperator>(E) &&
14201       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14202     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14203     if (isa<MemberExpr>(Op)) {
14204       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14205       if (MA != MisalignedMembers.end() &&
14206           (T->isIntegerType() ||
14207            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14208                                    Context.getTypeAlignInChars(
14209                                        T->getPointeeType()) <= MA->Alignment))))
14210         MisalignedMembers.erase(MA);
14211     }
14212   }
14213 }
14214 
14215 void Sema::RefersToMemberWithReducedAlignment(
14216     Expr *E,
14217     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14218         Action) {
14219   const auto *ME = dyn_cast<MemberExpr>(E);
14220   if (!ME)
14221     return;
14222 
14223   // No need to check expressions with an __unaligned-qualified type.
14224   if (E->getType().getQualifiers().hasUnaligned())
14225     return;
14226 
14227   // For a chain of MemberExpr like "a.b.c.d" this list
14228   // will keep FieldDecl's like [d, c, b].
14229   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14230   const MemberExpr *TopME = nullptr;
14231   bool AnyIsPacked = false;
14232   do {
14233     QualType BaseType = ME->getBase()->getType();
14234     if (ME->isArrow())
14235       BaseType = BaseType->getPointeeType();
14236     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
14237     if (RD->isInvalidDecl())
14238       return;
14239 
14240     ValueDecl *MD = ME->getMemberDecl();
14241     auto *FD = dyn_cast<FieldDecl>(MD);
14242     // We do not care about non-data members.
14243     if (!FD || FD->isInvalidDecl())
14244       return;
14245 
14246     AnyIsPacked =
14247         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14248     ReverseMemberChain.push_back(FD);
14249 
14250     TopME = ME;
14251     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14252   } while (ME);
14253   assert(TopME && "We did not compute a topmost MemberExpr!");
14254 
14255   // Not the scope of this diagnostic.
14256   if (!AnyIsPacked)
14257     return;
14258 
14259   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14260   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14261   // TODO: The innermost base of the member expression may be too complicated.
14262   // For now, just disregard these cases. This is left for future
14263   // improvement.
14264   if (!DRE && !isa<CXXThisExpr>(TopBase))
14265       return;
14266 
14267   // Alignment expected by the whole expression.
14268   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14269 
14270   // No need to do anything else with this case.
14271   if (ExpectedAlignment.isOne())
14272     return;
14273 
14274   // Synthesize offset of the whole access.
14275   CharUnits Offset;
14276   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14277        I++) {
14278     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14279   }
14280 
14281   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14282   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14283       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14284 
14285   // The base expression of the innermost MemberExpr may give
14286   // stronger guarantees than the class containing the member.
14287   if (DRE && !TopME->isArrow()) {
14288     const ValueDecl *VD = DRE->getDecl();
14289     if (!VD->getType()->isReferenceType())
14290       CompleteObjectAlignment =
14291           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14292   }
14293 
14294   // Check if the synthesized offset fulfills the alignment.
14295   if (Offset % ExpectedAlignment != 0 ||
14296       // It may fulfill the offset it but the effective alignment may still be
14297       // lower than the expected expression alignment.
14298       CompleteObjectAlignment < ExpectedAlignment) {
14299     // If this happens, we want to determine a sensible culprit of this.
14300     // Intuitively, watching the chain of member expressions from right to
14301     // left, we start with the required alignment (as required by the field
14302     // type) but some packed attribute in that chain has reduced the alignment.
14303     // It may happen that another packed structure increases it again. But if
14304     // we are here such increase has not been enough. So pointing the first
14305     // FieldDecl that either is packed or else its RecordDecl is,
14306     // seems reasonable.
14307     FieldDecl *FD = nullptr;
14308     CharUnits Alignment;
14309     for (FieldDecl *FDI : ReverseMemberChain) {
14310       if (FDI->hasAttr<PackedAttr>() ||
14311           FDI->getParent()->hasAttr<PackedAttr>()) {
14312         FD = FDI;
14313         Alignment = std::min(
14314             Context.getTypeAlignInChars(FD->getType()),
14315             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14316         break;
14317       }
14318     }
14319     assert(FD && "We did not find a packed FieldDecl!");
14320     Action(E, FD->getParent(), FD, Alignment);
14321   }
14322 }
14323 
14324 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14325   using namespace std::placeholders;
14326 
14327   RefersToMemberWithReducedAlignment(
14328       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14329                      _2, _3, _4));
14330 }
14331