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()->castAs<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()->castAs<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(),
633            diag::err_typecheck_call_too_few_args_at_least)
634         << 0 << 4 << NumArgs;
635     return true;
636   }
637 
638   Expr *Arg0 = TheCall->getArg(0);
639   Expr *Arg1 = TheCall->getArg(1);
640   Expr *Arg2 = TheCall->getArg(2);
641   Expr *Arg3 = TheCall->getArg(3);
642 
643   // First argument always needs to be a queue_t type.
644   if (!Arg0->getType()->isQueueT()) {
645     S.Diag(TheCall->getArg(0)->getBeginLoc(),
646            diag::err_opencl_builtin_expected_type)
647         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
648     return true;
649   }
650 
651   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
652   if (!Arg1->getType()->isIntegerType()) {
653     S.Diag(TheCall->getArg(1)->getBeginLoc(),
654            diag::err_opencl_builtin_expected_type)
655         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
656     return true;
657   }
658 
659   // Third argument is always an ndrange_t type.
660   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
661     S.Diag(TheCall->getArg(2)->getBeginLoc(),
662            diag::err_opencl_builtin_expected_type)
663         << TheCall->getDirectCallee() << "'ndrange_t'";
664     return true;
665   }
666 
667   // With four arguments, there is only one form that the function could be
668   // called in: no events and no variable arguments.
669   if (NumArgs == 4) {
670     // check that the last argument is the right block type.
671     if (!isBlockPointer(Arg3)) {
672       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
673           << TheCall->getDirectCallee() << "block";
674       return true;
675     }
676     // we have a block type, check the prototype
677     const BlockPointerType *BPT =
678         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
679     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
680       S.Diag(Arg3->getBeginLoc(),
681              diag::err_opencl_enqueue_kernel_blocks_no_args);
682       return true;
683     }
684     return false;
685   }
686   // we can have block + varargs.
687   if (isBlockPointer(Arg3))
688     return (checkOpenCLBlockArgs(S, Arg3) ||
689             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
690   // last two cases with either exactly 7 args or 7 args and varargs.
691   if (NumArgs >= 7) {
692     // check common block argument.
693     Expr *Arg6 = TheCall->getArg(6);
694     if (!isBlockPointer(Arg6)) {
695       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
696           << TheCall->getDirectCallee() << "block";
697       return true;
698     }
699     if (checkOpenCLBlockArgs(S, Arg6))
700       return true;
701 
702     // Forth argument has to be any integer type.
703     if (!Arg3->getType()->isIntegerType()) {
704       S.Diag(TheCall->getArg(3)->getBeginLoc(),
705              diag::err_opencl_builtin_expected_type)
706           << TheCall->getDirectCallee() << "integer";
707       return true;
708     }
709     // check remaining common arguments.
710     Expr *Arg4 = TheCall->getArg(4);
711     Expr *Arg5 = TheCall->getArg(5);
712 
713     // Fifth argument is always passed as a pointer to clk_event_t.
714     if (!Arg4->isNullPointerConstant(S.Context,
715                                      Expr::NPC_ValueDependentIsNotNull) &&
716         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
717       S.Diag(TheCall->getArg(4)->getBeginLoc(),
718              diag::err_opencl_builtin_expected_type)
719           << TheCall->getDirectCallee()
720           << S.Context.getPointerType(S.Context.OCLClkEventTy);
721       return true;
722     }
723 
724     // Sixth argument is always passed as a pointer to clk_event_t.
725     if (!Arg5->isNullPointerConstant(S.Context,
726                                      Expr::NPC_ValueDependentIsNotNull) &&
727         !(Arg5->getType()->isPointerType() &&
728           Arg5->getType()->getPointeeType()->isClkEventT())) {
729       S.Diag(TheCall->getArg(5)->getBeginLoc(),
730              diag::err_opencl_builtin_expected_type)
731           << TheCall->getDirectCallee()
732           << S.Context.getPointerType(S.Context.OCLClkEventTy);
733       return true;
734     }
735 
736     if (NumArgs == 7)
737       return false;
738 
739     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
740   }
741 
742   // None of the specific case has been detected, give generic error
743   S.Diag(TheCall->getBeginLoc(),
744          diag::err_opencl_enqueue_kernel_incorrect_args);
745   return true;
746 }
747 
748 /// Returns OpenCL access qual.
749 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
750     return D->getAttr<OpenCLAccessAttr>();
751 }
752 
753 /// Returns true if pipe element type is different from the pointer.
754 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
755   const Expr *Arg0 = Call->getArg(0);
756   // First argument type should always be pipe.
757   if (!Arg0->getType()->isPipeType()) {
758     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
759         << Call->getDirectCallee() << Arg0->getSourceRange();
760     return true;
761   }
762   OpenCLAccessAttr *AccessQual =
763       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
764   // Validates the access qualifier is compatible with the call.
765   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
766   // read_only and write_only, and assumed to be read_only if no qualifier is
767   // specified.
768   switch (Call->getDirectCallee()->getBuiltinID()) {
769   case Builtin::BIread_pipe:
770   case Builtin::BIreserve_read_pipe:
771   case Builtin::BIcommit_read_pipe:
772   case Builtin::BIwork_group_reserve_read_pipe:
773   case Builtin::BIsub_group_reserve_read_pipe:
774   case Builtin::BIwork_group_commit_read_pipe:
775   case Builtin::BIsub_group_commit_read_pipe:
776     if (!(!AccessQual || AccessQual->isReadOnly())) {
777       S.Diag(Arg0->getBeginLoc(),
778              diag::err_opencl_builtin_pipe_invalid_access_modifier)
779           << "read_only" << Arg0->getSourceRange();
780       return true;
781     }
782     break;
783   case Builtin::BIwrite_pipe:
784   case Builtin::BIreserve_write_pipe:
785   case Builtin::BIcommit_write_pipe:
786   case Builtin::BIwork_group_reserve_write_pipe:
787   case Builtin::BIsub_group_reserve_write_pipe:
788   case Builtin::BIwork_group_commit_write_pipe:
789   case Builtin::BIsub_group_commit_write_pipe:
790     if (!(AccessQual && AccessQual->isWriteOnly())) {
791       S.Diag(Arg0->getBeginLoc(),
792              diag::err_opencl_builtin_pipe_invalid_access_modifier)
793           << "write_only" << Arg0->getSourceRange();
794       return true;
795     }
796     break;
797   default:
798     break;
799   }
800   return false;
801 }
802 
803 /// Returns true if pipe element type is different from the pointer.
804 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
805   const Expr *Arg0 = Call->getArg(0);
806   const Expr *ArgIdx = Call->getArg(Idx);
807   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
808   const QualType EltTy = PipeTy->getElementType();
809   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
810   // The Idx argument should be a pointer and the type of the pointer and
811   // the type of pipe element should also be the same.
812   if (!ArgTy ||
813       !S.Context.hasSameType(
814           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
815     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
816         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
817         << ArgIdx->getType() << ArgIdx->getSourceRange();
818     return true;
819   }
820   return false;
821 }
822 
823 // Performs semantic analysis for the read/write_pipe call.
824 // \param S Reference to the semantic analyzer.
825 // \param Call A pointer to the builtin call.
826 // \return True if a semantic error has been found, false otherwise.
827 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
828   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
829   // functions have two forms.
830   switch (Call->getNumArgs()) {
831   case 2:
832     if (checkOpenCLPipeArg(S, Call))
833       return true;
834     // The call with 2 arguments should be
835     // read/write_pipe(pipe T, T*).
836     // Check packet type T.
837     if (checkOpenCLPipePacketType(S, Call, 1))
838       return true;
839     break;
840 
841   case 4: {
842     if (checkOpenCLPipeArg(S, Call))
843       return true;
844     // The call with 4 arguments should be
845     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
846     // Check reserve_id_t.
847     if (!Call->getArg(1)->getType()->isReserveIDT()) {
848       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
849           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
850           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
851       return true;
852     }
853 
854     // Check the index.
855     const Expr *Arg2 = Call->getArg(2);
856     if (!Arg2->getType()->isIntegerType() &&
857         !Arg2->getType()->isUnsignedIntegerType()) {
858       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
859           << Call->getDirectCallee() << S.Context.UnsignedIntTy
860           << Arg2->getType() << Arg2->getSourceRange();
861       return true;
862     }
863 
864     // Check packet type T.
865     if (checkOpenCLPipePacketType(S, Call, 3))
866       return true;
867   } break;
868   default:
869     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
870         << Call->getDirectCallee() << Call->getSourceRange();
871     return true;
872   }
873 
874   return false;
875 }
876 
877 // Performs a semantic analysis on the {work_group_/sub_group_
878 //        /_}reserve_{read/write}_pipe
879 // \param S Reference to the semantic analyzer.
880 // \param Call The call to the builtin function to be analyzed.
881 // \return True if a semantic error was found, false otherwise.
882 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
883   if (checkArgCount(S, Call, 2))
884     return true;
885 
886   if (checkOpenCLPipeArg(S, Call))
887     return true;
888 
889   // Check the reserve size.
890   if (!Call->getArg(1)->getType()->isIntegerType() &&
891       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
892     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
893         << Call->getDirectCallee() << S.Context.UnsignedIntTy
894         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
895     return true;
896   }
897 
898   // Since return type of reserve_read/write_pipe built-in function is
899   // reserve_id_t, which is not defined in the builtin def file , we used int
900   // as return type and need to override the return type of these functions.
901   Call->setType(S.Context.OCLReserveIDTy);
902 
903   return false;
904 }
905 
906 // Performs a semantic analysis on {work_group_/sub_group_
907 //        /_}commit_{read/write}_pipe
908 // \param S Reference to the semantic analyzer.
909 // \param Call The call to the builtin function to be analyzed.
910 // \return True if a semantic error was found, false otherwise.
911 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
912   if (checkArgCount(S, Call, 2))
913     return true;
914 
915   if (checkOpenCLPipeArg(S, Call))
916     return true;
917 
918   // Check reserve_id_t.
919   if (!Call->getArg(1)->getType()->isReserveIDT()) {
920     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
921         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
922         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
923     return true;
924   }
925 
926   return false;
927 }
928 
929 // Performs a semantic analysis on the call to built-in Pipe
930 //        Query Functions.
931 // \param S Reference to the semantic analyzer.
932 // \param Call The call to the builtin function to be analyzed.
933 // \return True if a semantic error was found, false otherwise.
934 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
935   if (checkArgCount(S, Call, 1))
936     return true;
937 
938   if (!Call->getArg(0)->getType()->isPipeType()) {
939     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
940         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
941     return true;
942   }
943 
944   return false;
945 }
946 
947 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
948 // Performs semantic analysis for the to_global/local/private call.
949 // \param S Reference to the semantic analyzer.
950 // \param BuiltinID ID of the builtin function.
951 // \param Call A pointer to the builtin call.
952 // \return True if a semantic error has been found, false otherwise.
953 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
954                                     CallExpr *Call) {
955   if (Call->getNumArgs() != 1) {
956     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
957         << Call->getDirectCallee() << Call->getSourceRange();
958     return true;
959   }
960 
961   auto RT = Call->getArg(0)->getType();
962   if (!RT->isPointerType() || RT->getPointeeType()
963       .getAddressSpace() == LangAS::opencl_constant) {
964     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
965         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
966     return true;
967   }
968 
969   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
970     S.Diag(Call->getArg(0)->getBeginLoc(),
971            diag::warn_opencl_generic_address_space_arg)
972         << Call->getDirectCallee()->getNameInfo().getAsString()
973         << Call->getArg(0)->getSourceRange();
974   }
975 
976   RT = RT->getPointeeType();
977   auto Qual = RT.getQualifiers();
978   switch (BuiltinID) {
979   case Builtin::BIto_global:
980     Qual.setAddressSpace(LangAS::opencl_global);
981     break;
982   case Builtin::BIto_local:
983     Qual.setAddressSpace(LangAS::opencl_local);
984     break;
985   case Builtin::BIto_private:
986     Qual.setAddressSpace(LangAS::opencl_private);
987     break;
988   default:
989     llvm_unreachable("Invalid builtin function");
990   }
991   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
992       RT.getUnqualifiedType(), Qual)));
993 
994   return false;
995 }
996 
997 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
998   if (checkArgCount(S, TheCall, 1))
999     return ExprError();
1000 
1001   // Compute __builtin_launder's parameter type from the argument.
1002   // The parameter type is:
1003   //  * The type of the argument if it's not an array or function type,
1004   //  Otherwise,
1005   //  * The decayed argument type.
1006   QualType ParamTy = [&]() {
1007     QualType ArgTy = TheCall->getArg(0)->getType();
1008     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1009       return S.Context.getPointerType(Ty->getElementType());
1010     if (ArgTy->isFunctionType()) {
1011       return S.Context.getPointerType(ArgTy);
1012     }
1013     return ArgTy;
1014   }();
1015 
1016   TheCall->setType(ParamTy);
1017 
1018   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1019     if (!ParamTy->isPointerType())
1020       return 0;
1021     if (ParamTy->isFunctionPointerType())
1022       return 1;
1023     if (ParamTy->isVoidPointerType())
1024       return 2;
1025     return llvm::Optional<unsigned>{};
1026   }();
1027   if (DiagSelect.hasValue()) {
1028     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1029         << DiagSelect.getValue() << TheCall->getSourceRange();
1030     return ExprError();
1031   }
1032 
1033   // We either have an incomplete class type, or we have a class template
1034   // whose instantiation has not been forced. Example:
1035   //
1036   //   template <class T> struct Foo { T value; };
1037   //   Foo<int> *p = nullptr;
1038   //   auto *d = __builtin_launder(p);
1039   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1040                             diag::err_incomplete_type))
1041     return ExprError();
1042 
1043   assert(ParamTy->getPointeeType()->isObjectType() &&
1044          "Unhandled non-object pointer case");
1045 
1046   InitializedEntity Entity =
1047       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1048   ExprResult Arg =
1049       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1050   if (Arg.isInvalid())
1051     return ExprError();
1052   TheCall->setArg(0, Arg.get());
1053 
1054   return TheCall;
1055 }
1056 
1057 // Emit an error and return true if the current architecture is not in the list
1058 // of supported architectures.
1059 static bool
1060 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1061                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1062   llvm::Triple::ArchType CurArch =
1063       S.getASTContext().getTargetInfo().getTriple().getArch();
1064   if (llvm::is_contained(SupportedArchs, CurArch))
1065     return false;
1066   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1067       << TheCall->getSourceRange();
1068   return true;
1069 }
1070 
1071 ExprResult
1072 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1073                                CallExpr *TheCall) {
1074   ExprResult TheCallResult(TheCall);
1075 
1076   // Find out if any arguments are required to be integer constant expressions.
1077   unsigned ICEArguments = 0;
1078   ASTContext::GetBuiltinTypeError Error;
1079   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1080   if (Error != ASTContext::GE_None)
1081     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1082 
1083   // If any arguments are required to be ICE's, check and diagnose.
1084   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1085     // Skip arguments not required to be ICE's.
1086     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1087 
1088     llvm::APSInt Result;
1089     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1090       return true;
1091     ICEArguments &= ~(1 << ArgNo);
1092   }
1093 
1094   switch (BuiltinID) {
1095   case Builtin::BI__builtin___CFStringMakeConstantString:
1096     assert(TheCall->getNumArgs() == 1 &&
1097            "Wrong # arguments to builtin CFStringMakeConstantString");
1098     if (CheckObjCString(TheCall->getArg(0)))
1099       return ExprError();
1100     break;
1101   case Builtin::BI__builtin_ms_va_start:
1102   case Builtin::BI__builtin_stdarg_start:
1103   case Builtin::BI__builtin_va_start:
1104     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1105       return ExprError();
1106     break;
1107   case Builtin::BI__va_start: {
1108     switch (Context.getTargetInfo().getTriple().getArch()) {
1109     case llvm::Triple::aarch64:
1110     case llvm::Triple::arm:
1111     case llvm::Triple::thumb:
1112       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1113         return ExprError();
1114       break;
1115     default:
1116       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1117         return ExprError();
1118       break;
1119     }
1120     break;
1121   }
1122 
1123   // The acquire, release, and no fence variants are ARM and AArch64 only.
1124   case Builtin::BI_interlockedbittestandset_acq:
1125   case Builtin::BI_interlockedbittestandset_rel:
1126   case Builtin::BI_interlockedbittestandset_nf:
1127   case Builtin::BI_interlockedbittestandreset_acq:
1128   case Builtin::BI_interlockedbittestandreset_rel:
1129   case Builtin::BI_interlockedbittestandreset_nf:
1130     if (CheckBuiltinTargetSupport(
1131             *this, BuiltinID, TheCall,
1132             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1133       return ExprError();
1134     break;
1135 
1136   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1137   case Builtin::BI_bittest64:
1138   case Builtin::BI_bittestandcomplement64:
1139   case Builtin::BI_bittestandreset64:
1140   case Builtin::BI_bittestandset64:
1141   case Builtin::BI_interlockedbittestandreset64:
1142   case Builtin::BI_interlockedbittestandset64:
1143     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1144                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1145                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1146       return ExprError();
1147     break;
1148 
1149   case Builtin::BI__builtin_isgreater:
1150   case Builtin::BI__builtin_isgreaterequal:
1151   case Builtin::BI__builtin_isless:
1152   case Builtin::BI__builtin_islessequal:
1153   case Builtin::BI__builtin_islessgreater:
1154   case Builtin::BI__builtin_isunordered:
1155     if (SemaBuiltinUnorderedCompare(TheCall))
1156       return ExprError();
1157     break;
1158   case Builtin::BI__builtin_fpclassify:
1159     if (SemaBuiltinFPClassification(TheCall, 6))
1160       return ExprError();
1161     break;
1162   case Builtin::BI__builtin_isfinite:
1163   case Builtin::BI__builtin_isinf:
1164   case Builtin::BI__builtin_isinf_sign:
1165   case Builtin::BI__builtin_isnan:
1166   case Builtin::BI__builtin_isnormal:
1167   case Builtin::BI__builtin_signbit:
1168   case Builtin::BI__builtin_signbitf:
1169   case Builtin::BI__builtin_signbitl:
1170     if (SemaBuiltinFPClassification(TheCall, 1))
1171       return ExprError();
1172     break;
1173   case Builtin::BI__builtin_shufflevector:
1174     return SemaBuiltinShuffleVector(TheCall);
1175     // TheCall will be freed by the smart pointer here, but that's fine, since
1176     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1177   case Builtin::BI__builtin_prefetch:
1178     if (SemaBuiltinPrefetch(TheCall))
1179       return ExprError();
1180     break;
1181   case Builtin::BI__builtin_alloca_with_align:
1182     if (SemaBuiltinAllocaWithAlign(TheCall))
1183       return ExprError();
1184     LLVM_FALLTHROUGH;
1185   case Builtin::BI__builtin_alloca:
1186     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1187         << TheCall->getDirectCallee();
1188     break;
1189   case Builtin::BI__assume:
1190   case Builtin::BI__builtin_assume:
1191     if (SemaBuiltinAssume(TheCall))
1192       return ExprError();
1193     break;
1194   case Builtin::BI__builtin_assume_aligned:
1195     if (SemaBuiltinAssumeAligned(TheCall))
1196       return ExprError();
1197     break;
1198   case Builtin::BI__builtin_dynamic_object_size:
1199   case Builtin::BI__builtin_object_size:
1200     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1201       return ExprError();
1202     break;
1203   case Builtin::BI__builtin_longjmp:
1204     if (SemaBuiltinLongjmp(TheCall))
1205       return ExprError();
1206     break;
1207   case Builtin::BI__builtin_setjmp:
1208     if (SemaBuiltinSetjmp(TheCall))
1209       return ExprError();
1210     break;
1211   case Builtin::BI_setjmp:
1212   case Builtin::BI_setjmpex:
1213     if (checkArgCount(*this, TheCall, 1))
1214       return true;
1215     break;
1216   case Builtin::BI__builtin_classify_type:
1217     if (checkArgCount(*this, TheCall, 1)) return true;
1218     TheCall->setType(Context.IntTy);
1219     break;
1220   case Builtin::BI__builtin_constant_p: {
1221     if (checkArgCount(*this, TheCall, 1)) return true;
1222     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1223     if (Arg.isInvalid()) return true;
1224     TheCall->setArg(0, Arg.get());
1225     TheCall->setType(Context.IntTy);
1226     break;
1227   }
1228   case Builtin::BI__builtin_launder:
1229     return SemaBuiltinLaunder(*this, TheCall);
1230   case Builtin::BI__sync_fetch_and_add:
1231   case Builtin::BI__sync_fetch_and_add_1:
1232   case Builtin::BI__sync_fetch_and_add_2:
1233   case Builtin::BI__sync_fetch_and_add_4:
1234   case Builtin::BI__sync_fetch_and_add_8:
1235   case Builtin::BI__sync_fetch_and_add_16:
1236   case Builtin::BI__sync_fetch_and_sub:
1237   case Builtin::BI__sync_fetch_and_sub_1:
1238   case Builtin::BI__sync_fetch_and_sub_2:
1239   case Builtin::BI__sync_fetch_and_sub_4:
1240   case Builtin::BI__sync_fetch_and_sub_8:
1241   case Builtin::BI__sync_fetch_and_sub_16:
1242   case Builtin::BI__sync_fetch_and_or:
1243   case Builtin::BI__sync_fetch_and_or_1:
1244   case Builtin::BI__sync_fetch_and_or_2:
1245   case Builtin::BI__sync_fetch_and_or_4:
1246   case Builtin::BI__sync_fetch_and_or_8:
1247   case Builtin::BI__sync_fetch_and_or_16:
1248   case Builtin::BI__sync_fetch_and_and:
1249   case Builtin::BI__sync_fetch_and_and_1:
1250   case Builtin::BI__sync_fetch_and_and_2:
1251   case Builtin::BI__sync_fetch_and_and_4:
1252   case Builtin::BI__sync_fetch_and_and_8:
1253   case Builtin::BI__sync_fetch_and_and_16:
1254   case Builtin::BI__sync_fetch_and_xor:
1255   case Builtin::BI__sync_fetch_and_xor_1:
1256   case Builtin::BI__sync_fetch_and_xor_2:
1257   case Builtin::BI__sync_fetch_and_xor_4:
1258   case Builtin::BI__sync_fetch_and_xor_8:
1259   case Builtin::BI__sync_fetch_and_xor_16:
1260   case Builtin::BI__sync_fetch_and_nand:
1261   case Builtin::BI__sync_fetch_and_nand_1:
1262   case Builtin::BI__sync_fetch_and_nand_2:
1263   case Builtin::BI__sync_fetch_and_nand_4:
1264   case Builtin::BI__sync_fetch_and_nand_8:
1265   case Builtin::BI__sync_fetch_and_nand_16:
1266   case Builtin::BI__sync_add_and_fetch:
1267   case Builtin::BI__sync_add_and_fetch_1:
1268   case Builtin::BI__sync_add_and_fetch_2:
1269   case Builtin::BI__sync_add_and_fetch_4:
1270   case Builtin::BI__sync_add_and_fetch_8:
1271   case Builtin::BI__sync_add_and_fetch_16:
1272   case Builtin::BI__sync_sub_and_fetch:
1273   case Builtin::BI__sync_sub_and_fetch_1:
1274   case Builtin::BI__sync_sub_and_fetch_2:
1275   case Builtin::BI__sync_sub_and_fetch_4:
1276   case Builtin::BI__sync_sub_and_fetch_8:
1277   case Builtin::BI__sync_sub_and_fetch_16:
1278   case Builtin::BI__sync_and_and_fetch:
1279   case Builtin::BI__sync_and_and_fetch_1:
1280   case Builtin::BI__sync_and_and_fetch_2:
1281   case Builtin::BI__sync_and_and_fetch_4:
1282   case Builtin::BI__sync_and_and_fetch_8:
1283   case Builtin::BI__sync_and_and_fetch_16:
1284   case Builtin::BI__sync_or_and_fetch:
1285   case Builtin::BI__sync_or_and_fetch_1:
1286   case Builtin::BI__sync_or_and_fetch_2:
1287   case Builtin::BI__sync_or_and_fetch_4:
1288   case Builtin::BI__sync_or_and_fetch_8:
1289   case Builtin::BI__sync_or_and_fetch_16:
1290   case Builtin::BI__sync_xor_and_fetch:
1291   case Builtin::BI__sync_xor_and_fetch_1:
1292   case Builtin::BI__sync_xor_and_fetch_2:
1293   case Builtin::BI__sync_xor_and_fetch_4:
1294   case Builtin::BI__sync_xor_and_fetch_8:
1295   case Builtin::BI__sync_xor_and_fetch_16:
1296   case Builtin::BI__sync_nand_and_fetch:
1297   case Builtin::BI__sync_nand_and_fetch_1:
1298   case Builtin::BI__sync_nand_and_fetch_2:
1299   case Builtin::BI__sync_nand_and_fetch_4:
1300   case Builtin::BI__sync_nand_and_fetch_8:
1301   case Builtin::BI__sync_nand_and_fetch_16:
1302   case Builtin::BI__sync_val_compare_and_swap:
1303   case Builtin::BI__sync_val_compare_and_swap_1:
1304   case Builtin::BI__sync_val_compare_and_swap_2:
1305   case Builtin::BI__sync_val_compare_and_swap_4:
1306   case Builtin::BI__sync_val_compare_and_swap_8:
1307   case Builtin::BI__sync_val_compare_and_swap_16:
1308   case Builtin::BI__sync_bool_compare_and_swap:
1309   case Builtin::BI__sync_bool_compare_and_swap_1:
1310   case Builtin::BI__sync_bool_compare_and_swap_2:
1311   case Builtin::BI__sync_bool_compare_and_swap_4:
1312   case Builtin::BI__sync_bool_compare_and_swap_8:
1313   case Builtin::BI__sync_bool_compare_and_swap_16:
1314   case Builtin::BI__sync_lock_test_and_set:
1315   case Builtin::BI__sync_lock_test_and_set_1:
1316   case Builtin::BI__sync_lock_test_and_set_2:
1317   case Builtin::BI__sync_lock_test_and_set_4:
1318   case Builtin::BI__sync_lock_test_and_set_8:
1319   case Builtin::BI__sync_lock_test_and_set_16:
1320   case Builtin::BI__sync_lock_release:
1321   case Builtin::BI__sync_lock_release_1:
1322   case Builtin::BI__sync_lock_release_2:
1323   case Builtin::BI__sync_lock_release_4:
1324   case Builtin::BI__sync_lock_release_8:
1325   case Builtin::BI__sync_lock_release_16:
1326   case Builtin::BI__sync_swap:
1327   case Builtin::BI__sync_swap_1:
1328   case Builtin::BI__sync_swap_2:
1329   case Builtin::BI__sync_swap_4:
1330   case Builtin::BI__sync_swap_8:
1331   case Builtin::BI__sync_swap_16:
1332     return SemaBuiltinAtomicOverloaded(TheCallResult);
1333   case Builtin::BI__sync_synchronize:
1334     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1335         << TheCall->getCallee()->getSourceRange();
1336     break;
1337   case Builtin::BI__builtin_nontemporal_load:
1338   case Builtin::BI__builtin_nontemporal_store:
1339     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1340 #define BUILTIN(ID, TYPE, ATTRS)
1341 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1342   case Builtin::BI##ID: \
1343     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1344 #include "clang/Basic/Builtins.def"
1345   case Builtin::BI__annotation:
1346     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1347       return ExprError();
1348     break;
1349   case Builtin::BI__builtin_annotation:
1350     if (SemaBuiltinAnnotation(*this, TheCall))
1351       return ExprError();
1352     break;
1353   case Builtin::BI__builtin_addressof:
1354     if (SemaBuiltinAddressof(*this, TheCall))
1355       return ExprError();
1356     break;
1357   case Builtin::BI__builtin_add_overflow:
1358   case Builtin::BI__builtin_sub_overflow:
1359   case Builtin::BI__builtin_mul_overflow:
1360     if (SemaBuiltinOverflow(*this, TheCall))
1361       return ExprError();
1362     break;
1363   case Builtin::BI__builtin_operator_new:
1364   case Builtin::BI__builtin_operator_delete: {
1365     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1366     ExprResult Res =
1367         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1368     if (Res.isInvalid())
1369       CorrectDelayedTyposInExpr(TheCallResult.get());
1370     return Res;
1371   }
1372   case Builtin::BI__builtin_dump_struct: {
1373     // We first want to ensure we are called with 2 arguments
1374     if (checkArgCount(*this, TheCall, 2))
1375       return ExprError();
1376     // Ensure that the first argument is of type 'struct XX *'
1377     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1378     const QualType PtrArgType = PtrArg->getType();
1379     if (!PtrArgType->isPointerType() ||
1380         !PtrArgType->getPointeeType()->isRecordType()) {
1381       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1382           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1383           << "structure pointer";
1384       return ExprError();
1385     }
1386 
1387     // Ensure that the second argument is of type 'FunctionType'
1388     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1389     const QualType FnPtrArgType = FnPtrArg->getType();
1390     if (!FnPtrArgType->isPointerType()) {
1391       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1392           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1393           << FnPtrArgType << "'int (*)(const char *, ...)'";
1394       return ExprError();
1395     }
1396 
1397     const auto *FuncType =
1398         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1399 
1400     if (!FuncType) {
1401       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1402           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1403           << FnPtrArgType << "'int (*)(const char *, ...)'";
1404       return ExprError();
1405     }
1406 
1407     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1408       if (!FT->getNumParams()) {
1409         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1410             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1411             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1412         return ExprError();
1413       }
1414       QualType PT = FT->getParamType(0);
1415       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1416           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1417           !PT->getPointeeType().isConstQualified()) {
1418         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1419             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1420             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1421         return ExprError();
1422       }
1423     }
1424 
1425     TheCall->setType(Context.IntTy);
1426     break;
1427   }
1428   case Builtin::BI__builtin_preserve_access_index:
1429     if (SemaBuiltinPreserveAI(*this, TheCall))
1430       return ExprError();
1431     break;
1432   case Builtin::BI__builtin_call_with_static_chain:
1433     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1434       return ExprError();
1435     break;
1436   case Builtin::BI__exception_code:
1437   case Builtin::BI_exception_code:
1438     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1439                                  diag::err_seh___except_block))
1440       return ExprError();
1441     break;
1442   case Builtin::BI__exception_info:
1443   case Builtin::BI_exception_info:
1444     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1445                                  diag::err_seh___except_filter))
1446       return ExprError();
1447     break;
1448   case Builtin::BI__GetExceptionInfo:
1449     if (checkArgCount(*this, TheCall, 1))
1450       return ExprError();
1451 
1452     if (CheckCXXThrowOperand(
1453             TheCall->getBeginLoc(),
1454             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1455             TheCall))
1456       return ExprError();
1457 
1458     TheCall->setType(Context.VoidPtrTy);
1459     break;
1460   // OpenCL v2.0, s6.13.16 - Pipe functions
1461   case Builtin::BIread_pipe:
1462   case Builtin::BIwrite_pipe:
1463     // Since those two functions are declared with var args, we need a semantic
1464     // check for the argument.
1465     if (SemaBuiltinRWPipe(*this, TheCall))
1466       return ExprError();
1467     break;
1468   case Builtin::BIreserve_read_pipe:
1469   case Builtin::BIreserve_write_pipe:
1470   case Builtin::BIwork_group_reserve_read_pipe:
1471   case Builtin::BIwork_group_reserve_write_pipe:
1472     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BIsub_group_reserve_read_pipe:
1476   case Builtin::BIsub_group_reserve_write_pipe:
1477     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1478         SemaBuiltinReserveRWPipe(*this, TheCall))
1479       return ExprError();
1480     break;
1481   case Builtin::BIcommit_read_pipe:
1482   case Builtin::BIcommit_write_pipe:
1483   case Builtin::BIwork_group_commit_read_pipe:
1484   case Builtin::BIwork_group_commit_write_pipe:
1485     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1486       return ExprError();
1487     break;
1488   case Builtin::BIsub_group_commit_read_pipe:
1489   case Builtin::BIsub_group_commit_write_pipe:
1490     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1491         SemaBuiltinCommitRWPipe(*this, TheCall))
1492       return ExprError();
1493     break;
1494   case Builtin::BIget_pipe_num_packets:
1495   case Builtin::BIget_pipe_max_packets:
1496     if (SemaBuiltinPipePackets(*this, TheCall))
1497       return ExprError();
1498     break;
1499   case Builtin::BIto_global:
1500   case Builtin::BIto_local:
1501   case Builtin::BIto_private:
1502     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1503       return ExprError();
1504     break;
1505   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1506   case Builtin::BIenqueue_kernel:
1507     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1508       return ExprError();
1509     break;
1510   case Builtin::BIget_kernel_work_group_size:
1511   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1512     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1513       return ExprError();
1514     break;
1515   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1516   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1517     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1518       return ExprError();
1519     break;
1520   case Builtin::BI__builtin_os_log_format:
1521   case Builtin::BI__builtin_os_log_format_buffer_size:
1522     if (SemaBuiltinOSLogFormat(TheCall))
1523       return ExprError();
1524     break;
1525   }
1526 
1527   // Since the target specific builtins for each arch overlap, only check those
1528   // of the arch we are compiling for.
1529   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1530     switch (Context.getTargetInfo().getTriple().getArch()) {
1531       case llvm::Triple::arm:
1532       case llvm::Triple::armeb:
1533       case llvm::Triple::thumb:
1534       case llvm::Triple::thumbeb:
1535         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1536           return ExprError();
1537         break;
1538       case llvm::Triple::aarch64:
1539       case llvm::Triple::aarch64_32:
1540       case llvm::Triple::aarch64_be:
1541         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1542           return ExprError();
1543         break;
1544       case llvm::Triple::bpfeb:
1545       case llvm::Triple::bpfel:
1546         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1547           return ExprError();
1548         break;
1549       case llvm::Triple::hexagon:
1550         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1551           return ExprError();
1552         break;
1553       case llvm::Triple::mips:
1554       case llvm::Triple::mipsel:
1555       case llvm::Triple::mips64:
1556       case llvm::Triple::mips64el:
1557         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1558           return ExprError();
1559         break;
1560       case llvm::Triple::systemz:
1561         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1562           return ExprError();
1563         break;
1564       case llvm::Triple::x86:
1565       case llvm::Triple::x86_64:
1566         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1567           return ExprError();
1568         break;
1569       case llvm::Triple::ppc:
1570       case llvm::Triple::ppc64:
1571       case llvm::Triple::ppc64le:
1572         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1573           return ExprError();
1574         break;
1575       default:
1576         break;
1577     }
1578   }
1579 
1580   return TheCallResult;
1581 }
1582 
1583 // Get the valid immediate range for the specified NEON type code.
1584 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1585   NeonTypeFlags Type(t);
1586   int IsQuad = ForceQuad ? true : Type.isQuad();
1587   switch (Type.getEltType()) {
1588   case NeonTypeFlags::Int8:
1589   case NeonTypeFlags::Poly8:
1590     return shift ? 7 : (8 << IsQuad) - 1;
1591   case NeonTypeFlags::Int16:
1592   case NeonTypeFlags::Poly16:
1593     return shift ? 15 : (4 << IsQuad) - 1;
1594   case NeonTypeFlags::Int32:
1595     return shift ? 31 : (2 << IsQuad) - 1;
1596   case NeonTypeFlags::Int64:
1597   case NeonTypeFlags::Poly64:
1598     return shift ? 63 : (1 << IsQuad) - 1;
1599   case NeonTypeFlags::Poly128:
1600     return shift ? 127 : (1 << IsQuad) - 1;
1601   case NeonTypeFlags::Float16:
1602     assert(!shift && "cannot shift float types!");
1603     return (4 << IsQuad) - 1;
1604   case NeonTypeFlags::Float32:
1605     assert(!shift && "cannot shift float types!");
1606     return (2 << IsQuad) - 1;
1607   case NeonTypeFlags::Float64:
1608     assert(!shift && "cannot shift float types!");
1609     return (1 << IsQuad) - 1;
1610   }
1611   llvm_unreachable("Invalid NeonTypeFlag!");
1612 }
1613 
1614 /// getNeonEltType - Return the QualType corresponding to the elements of
1615 /// the vector type specified by the NeonTypeFlags.  This is used to check
1616 /// the pointer arguments for Neon load/store intrinsics.
1617 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1618                                bool IsPolyUnsigned, bool IsInt64Long) {
1619   switch (Flags.getEltType()) {
1620   case NeonTypeFlags::Int8:
1621     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1622   case NeonTypeFlags::Int16:
1623     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1624   case NeonTypeFlags::Int32:
1625     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1626   case NeonTypeFlags::Int64:
1627     if (IsInt64Long)
1628       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1629     else
1630       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1631                                 : Context.LongLongTy;
1632   case NeonTypeFlags::Poly8:
1633     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1634   case NeonTypeFlags::Poly16:
1635     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1636   case NeonTypeFlags::Poly64:
1637     if (IsInt64Long)
1638       return Context.UnsignedLongTy;
1639     else
1640       return Context.UnsignedLongLongTy;
1641   case NeonTypeFlags::Poly128:
1642     break;
1643   case NeonTypeFlags::Float16:
1644     return Context.HalfTy;
1645   case NeonTypeFlags::Float32:
1646     return Context.FloatTy;
1647   case NeonTypeFlags::Float64:
1648     return Context.DoubleTy;
1649   }
1650   llvm_unreachable("Invalid NeonTypeFlag!");
1651 }
1652 
1653 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1654   llvm::APSInt Result;
1655   uint64_t mask = 0;
1656   unsigned TV = 0;
1657   int PtrArgNum = -1;
1658   bool HasConstPtr = false;
1659   switch (BuiltinID) {
1660 #define GET_NEON_OVERLOAD_CHECK
1661 #include "clang/Basic/arm_neon.inc"
1662 #include "clang/Basic/arm_fp16.inc"
1663 #undef GET_NEON_OVERLOAD_CHECK
1664   }
1665 
1666   // For NEON intrinsics which are overloaded on vector element type, validate
1667   // the immediate which specifies which variant to emit.
1668   unsigned ImmArg = TheCall->getNumArgs()-1;
1669   if (mask) {
1670     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1671       return true;
1672 
1673     TV = Result.getLimitedValue(64);
1674     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1675       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1676              << TheCall->getArg(ImmArg)->getSourceRange();
1677   }
1678 
1679   if (PtrArgNum >= 0) {
1680     // Check that pointer arguments have the specified type.
1681     Expr *Arg = TheCall->getArg(PtrArgNum);
1682     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1683       Arg = ICE->getSubExpr();
1684     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1685     QualType RHSTy = RHS.get()->getType();
1686 
1687     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1688     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1689                           Arch == llvm::Triple::aarch64_32 ||
1690                           Arch == llvm::Triple::aarch64_be;
1691     bool IsInt64Long =
1692         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1693     QualType EltTy =
1694         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1695     if (HasConstPtr)
1696       EltTy = EltTy.withConst();
1697     QualType LHSTy = Context.getPointerType(EltTy);
1698     AssignConvertType ConvTy;
1699     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1700     if (RHS.isInvalid())
1701       return true;
1702     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1703                                  RHS.get(), AA_Assigning))
1704       return true;
1705   }
1706 
1707   // For NEON intrinsics which take an immediate value as part of the
1708   // instruction, range check them here.
1709   unsigned i = 0, l = 0, u = 0;
1710   switch (BuiltinID) {
1711   default:
1712     return false;
1713   #define GET_NEON_IMMEDIATE_CHECK
1714   #include "clang/Basic/arm_neon.inc"
1715   #include "clang/Basic/arm_fp16.inc"
1716   #undef GET_NEON_IMMEDIATE_CHECK
1717   }
1718 
1719   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1720 }
1721 
1722 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1723   switch (BuiltinID) {
1724   default:
1725     return false;
1726   #include "clang/Basic/arm_mve_builtin_sema.inc"
1727   }
1728 }
1729 
1730 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1731                                         unsigned MaxWidth) {
1732   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1733           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1734           BuiltinID == ARM::BI__builtin_arm_strex ||
1735           BuiltinID == ARM::BI__builtin_arm_stlex ||
1736           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1737           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1738           BuiltinID == AArch64::BI__builtin_arm_strex ||
1739           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1740          "unexpected ARM builtin");
1741   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1742                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1743                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1744                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1745 
1746   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1747 
1748   // Ensure that we have the proper number of arguments.
1749   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1750     return true;
1751 
1752   // Inspect the pointer argument of the atomic builtin.  This should always be
1753   // a pointer type, whose element is an integral scalar or pointer type.
1754   // Because it is a pointer type, we don't have to worry about any implicit
1755   // casts here.
1756   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1757   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1758   if (PointerArgRes.isInvalid())
1759     return true;
1760   PointerArg = PointerArgRes.get();
1761 
1762   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1763   if (!pointerType) {
1764     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1765         << PointerArg->getType() << PointerArg->getSourceRange();
1766     return true;
1767   }
1768 
1769   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1770   // task is to insert the appropriate casts into the AST. First work out just
1771   // what the appropriate type is.
1772   QualType ValType = pointerType->getPointeeType();
1773   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1774   if (IsLdrex)
1775     AddrType.addConst();
1776 
1777   // Issue a warning if the cast is dodgy.
1778   CastKind CastNeeded = CK_NoOp;
1779   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1780     CastNeeded = CK_BitCast;
1781     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1782         << PointerArg->getType() << Context.getPointerType(AddrType)
1783         << AA_Passing << PointerArg->getSourceRange();
1784   }
1785 
1786   // Finally, do the cast and replace the argument with the corrected version.
1787   AddrType = Context.getPointerType(AddrType);
1788   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1789   if (PointerArgRes.isInvalid())
1790     return true;
1791   PointerArg = PointerArgRes.get();
1792 
1793   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1794 
1795   // In general, we allow ints, floats and pointers to be loaded and stored.
1796   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1797       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1798     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1799         << PointerArg->getType() << PointerArg->getSourceRange();
1800     return true;
1801   }
1802 
1803   // But ARM doesn't have instructions to deal with 128-bit versions.
1804   if (Context.getTypeSize(ValType) > MaxWidth) {
1805     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1806     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1807         << PointerArg->getType() << PointerArg->getSourceRange();
1808     return true;
1809   }
1810 
1811   switch (ValType.getObjCLifetime()) {
1812   case Qualifiers::OCL_None:
1813   case Qualifiers::OCL_ExplicitNone:
1814     // okay
1815     break;
1816 
1817   case Qualifiers::OCL_Weak:
1818   case Qualifiers::OCL_Strong:
1819   case Qualifiers::OCL_Autoreleasing:
1820     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1821         << ValType << PointerArg->getSourceRange();
1822     return true;
1823   }
1824 
1825   if (IsLdrex) {
1826     TheCall->setType(ValType);
1827     return false;
1828   }
1829 
1830   // Initialize the argument to be stored.
1831   ExprResult ValArg = TheCall->getArg(0);
1832   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1833       Context, ValType, /*consume*/ false);
1834   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1835   if (ValArg.isInvalid())
1836     return true;
1837   TheCall->setArg(0, ValArg.get());
1838 
1839   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1840   // but the custom checker bypasses all default analysis.
1841   TheCall->setType(Context.IntTy);
1842   return false;
1843 }
1844 
1845 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1846   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1847       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1848       BuiltinID == ARM::BI__builtin_arm_strex ||
1849       BuiltinID == ARM::BI__builtin_arm_stlex) {
1850     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1851   }
1852 
1853   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1854     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1855       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1856   }
1857 
1858   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1859       BuiltinID == ARM::BI__builtin_arm_wsr64)
1860     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1861 
1862   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1863       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1864       BuiltinID == ARM::BI__builtin_arm_wsr ||
1865       BuiltinID == ARM::BI__builtin_arm_wsrp)
1866     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1867 
1868   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1869     return true;
1870   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
1871     return true;
1872 
1873   // For intrinsics which take an immediate value as part of the instruction,
1874   // range check them here.
1875   // FIXME: VFP Intrinsics should error if VFP not present.
1876   switch (BuiltinID) {
1877   default: return false;
1878   case ARM::BI__builtin_arm_ssat:
1879     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1880   case ARM::BI__builtin_arm_usat:
1881     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1882   case ARM::BI__builtin_arm_ssat16:
1883     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1884   case ARM::BI__builtin_arm_usat16:
1885     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1886   case ARM::BI__builtin_arm_vcvtr_f:
1887   case ARM::BI__builtin_arm_vcvtr_d:
1888     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1889   case ARM::BI__builtin_arm_dmb:
1890   case ARM::BI__builtin_arm_dsb:
1891   case ARM::BI__builtin_arm_isb:
1892   case ARM::BI__builtin_arm_dbg:
1893     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1894   }
1895 }
1896 
1897 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1898                                          CallExpr *TheCall) {
1899   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1900       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1901       BuiltinID == AArch64::BI__builtin_arm_strex ||
1902       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1903     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1904   }
1905 
1906   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1907     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1908       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1909       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1910       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1911   }
1912 
1913   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1914       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1915     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1916 
1917   // Memory Tagging Extensions (MTE) Intrinsics
1918   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1919       BuiltinID == AArch64::BI__builtin_arm_addg ||
1920       BuiltinID == AArch64::BI__builtin_arm_gmi ||
1921       BuiltinID == AArch64::BI__builtin_arm_ldg ||
1922       BuiltinID == AArch64::BI__builtin_arm_stg ||
1923       BuiltinID == AArch64::BI__builtin_arm_subp) {
1924     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1925   }
1926 
1927   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1928       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1929       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1930       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1931     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1932 
1933   // Only check the valid encoding range. Any constant in this range would be
1934   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1935   // an exception for incorrect registers. This matches MSVC behavior.
1936   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1937       BuiltinID == AArch64::BI_WriteStatusReg)
1938     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1939 
1940   if (BuiltinID == AArch64::BI__getReg)
1941     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1942 
1943   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1944     return true;
1945 
1946   // For intrinsics which take an immediate value as part of the instruction,
1947   // range check them here.
1948   unsigned i = 0, l = 0, u = 0;
1949   switch (BuiltinID) {
1950   default: return false;
1951   case AArch64::BI__builtin_arm_dmb:
1952   case AArch64::BI__builtin_arm_dsb:
1953   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1954   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
1955   }
1956 
1957   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1958 }
1959 
1960 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
1961                                        CallExpr *TheCall) {
1962   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
1963          "unexpected ARM builtin");
1964 
1965   if (checkArgCount(*this, TheCall, 2))
1966     return true;
1967 
1968   // The first argument needs to be a record field access.
1969   // If it is an array element access, we delay decision
1970   // to BPF backend to check whether the access is a
1971   // field access or not.
1972   Expr *Arg = TheCall->getArg(0);
1973   if (Arg->getType()->getAsPlaceholderType() ||
1974       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
1975        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
1976        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
1977     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
1978         << 1 << Arg->getSourceRange();
1979     return true;
1980   }
1981 
1982   // The second argument needs to be a constant int
1983   llvm::APSInt Value;
1984   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
1985     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
1986         << 2 << Arg->getSourceRange();
1987     return true;
1988   }
1989 
1990   TheCall->setType(Context.UnsignedIntTy);
1991   return false;
1992 }
1993 
1994 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1995   struct BuiltinAndString {
1996     unsigned BuiltinID;
1997     const char *Str;
1998   };
1999 
2000   static BuiltinAndString ValidCPU[] = {
2001     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
2004     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
2005     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
2006     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
2009     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
2024   };
2025 
2026   static BuiltinAndString ValidHVX[] = {
2027     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2671     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2672     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2673     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2674     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2675     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2676     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2677     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2678     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2679     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2680     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2681     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2682     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2683     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2684     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2685     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2686     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2687     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2688     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2689     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2690     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2691     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2692     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2693     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2694     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2695     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2696     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2697     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2706     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2708     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2709     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2710     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2711     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2712     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2713     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2714     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2715     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2716     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2717     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2718     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2719     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2720     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2721     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2722     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2723     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2724     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2725     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2726     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2727     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2728     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2729     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2730     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2733     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2734     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2735     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2736     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2737     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2738     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2739     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2740     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2741     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2742     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2743     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2744     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2745     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2746     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2747     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2748     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2749     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2750     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2751     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2752     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2753     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2754     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2755     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2756     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2757     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2758     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2759   };
2760 
2761   // Sort the tables on first execution so we can binary search them.
2762   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2763     return LHS.BuiltinID < RHS.BuiltinID;
2764   };
2765   static const bool SortOnce =
2766       (llvm::sort(ValidCPU, SortCmp),
2767        llvm::sort(ValidHVX, SortCmp), true);
2768   (void)SortOnce;
2769   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2770     return BI.BuiltinID < BuiltinID;
2771   };
2772 
2773   const TargetInfo &TI = Context.getTargetInfo();
2774 
2775   const BuiltinAndString *FC =
2776       llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2777   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2778     const TargetOptions &Opts = TI.getTargetOpts();
2779     StringRef CPU = Opts.CPU;
2780     if (!CPU.empty()) {
2781       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2782       CPU.consume_front("hexagon");
2783       SmallVector<StringRef, 3> CPUs;
2784       StringRef(FC->Str).split(CPUs, ',');
2785       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2786         return Diag(TheCall->getBeginLoc(),
2787                     diag::err_hexagon_builtin_unsupported_cpu);
2788     }
2789   }
2790 
2791   const BuiltinAndString *FH =
2792       llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2793   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2794     if (!TI.hasFeature("hvx"))
2795       return Diag(TheCall->getBeginLoc(),
2796                   diag::err_hexagon_builtin_requires_hvx);
2797 
2798     SmallVector<StringRef, 3> HVXs;
2799     StringRef(FH->Str).split(HVXs, ',');
2800     bool IsValid = llvm::any_of(HVXs,
2801                                 [&TI] (StringRef V) {
2802                                   std::string F = "hvx" + V.str();
2803                                   return TI.hasFeature(F);
2804                                 });
2805     if (!IsValid)
2806       return Diag(TheCall->getBeginLoc(),
2807                   diag::err_hexagon_builtin_unsupported_hvx);
2808   }
2809 
2810   return false;
2811 }
2812 
2813 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2814   struct ArgInfo {
2815     uint8_t OpNum;
2816     bool IsSigned;
2817     uint8_t BitWidth;
2818     uint8_t Align;
2819   };
2820   struct BuiltinInfo {
2821     unsigned BuiltinID;
2822     ArgInfo Infos[2];
2823   };
2824 
2825   static BuiltinInfo Infos[] = {
2826     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2827     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2828     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2829     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2830     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2831     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2832     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2833     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2834     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2835     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2836     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2837 
2838     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2841     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2842     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2843     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2849 
2850     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2902                                                       {{ 1, false, 6,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2910                                                       {{ 1, false, 5,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2917                                                        { 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2919                                                        { 2, false, 6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2921                                                        { 3, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2923                                                        { 3, false, 6,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2940                                                       {{ 2, false, 4,  0 },
2941                                                        { 3, false, 5,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2943                                                       {{ 2, false, 4,  0 },
2944                                                        { 3, false, 5,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2946                                                       {{ 2, false, 4,  0 },
2947                                                        { 3, false, 5,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2949                                                       {{ 2, false, 4,  0 },
2950                                                        { 3, false, 5,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2961     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2962                                                        { 2, false, 5,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2964                                                        { 2, false, 6,  0 }} },
2965     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2967     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2968     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2969     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2970     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2971     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2972     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2973     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2974                                                       {{ 1, false, 4,  0 }} },
2975     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2976     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2977                                                       {{ 1, false, 4,  0 }} },
2978     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2979     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2980     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2981     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2982     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2983     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2984     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2985     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2986     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2987     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2988     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2989     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2990     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2991     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2992     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2993     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2994     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2995     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2996     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2997     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2998                                                       {{ 3, false, 1,  0 }} },
2999     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3000     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3001     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3002     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3003                                                       {{ 3, false, 1,  0 }} },
3004     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3005     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3006     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3007     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3008                                                       {{ 3, false, 1,  0 }} },
3009   };
3010 
3011   // Use a dynamically initialized static to sort the table exactly once on
3012   // first run.
3013   static const bool SortOnce =
3014       (llvm::sort(Infos,
3015                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3016                    return LHS.BuiltinID < RHS.BuiltinID;
3017                  }),
3018        true);
3019   (void)SortOnce;
3020 
3021   const BuiltinInfo *F = llvm::partition_point(
3022       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3023   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3024     return false;
3025 
3026   bool Error = false;
3027 
3028   for (const ArgInfo &A : F->Infos) {
3029     // Ignore empty ArgInfo elements.
3030     if (A.BitWidth == 0)
3031       continue;
3032 
3033     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3034     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3035     if (!A.Align) {
3036       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3037     } else {
3038       unsigned M = 1 << A.Align;
3039       Min *= M;
3040       Max *= M;
3041       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
3042                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3043     }
3044   }
3045   return Error;
3046 }
3047 
3048 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3049                                            CallExpr *TheCall) {
3050   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3051          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3052 }
3053 
3054 
3055 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3056 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3057 // ordering for DSP is unspecified. MSA is ordered by the data format used
3058 // by the underlying instruction i.e., df/m, df/n and then by size.
3059 //
3060 // FIXME: The size tests here should instead be tablegen'd along with the
3061 //        definitions from include/clang/Basic/BuiltinsMips.def.
3062 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3063 //        be too.
3064 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3065   unsigned i = 0, l = 0, u = 0, m = 0;
3066   switch (BuiltinID) {
3067   default: return false;
3068   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3069   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3070   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3071   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3072   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3073   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3074   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3075   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3076   // df/m field.
3077   // These intrinsics take an unsigned 3 bit immediate.
3078   case Mips::BI__builtin_msa_bclri_b:
3079   case Mips::BI__builtin_msa_bnegi_b:
3080   case Mips::BI__builtin_msa_bseti_b:
3081   case Mips::BI__builtin_msa_sat_s_b:
3082   case Mips::BI__builtin_msa_sat_u_b:
3083   case Mips::BI__builtin_msa_slli_b:
3084   case Mips::BI__builtin_msa_srai_b:
3085   case Mips::BI__builtin_msa_srari_b:
3086   case Mips::BI__builtin_msa_srli_b:
3087   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3088   case Mips::BI__builtin_msa_binsli_b:
3089   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3090   // These intrinsics take an unsigned 4 bit immediate.
3091   case Mips::BI__builtin_msa_bclri_h:
3092   case Mips::BI__builtin_msa_bnegi_h:
3093   case Mips::BI__builtin_msa_bseti_h:
3094   case Mips::BI__builtin_msa_sat_s_h:
3095   case Mips::BI__builtin_msa_sat_u_h:
3096   case Mips::BI__builtin_msa_slli_h:
3097   case Mips::BI__builtin_msa_srai_h:
3098   case Mips::BI__builtin_msa_srari_h:
3099   case Mips::BI__builtin_msa_srli_h:
3100   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3101   case Mips::BI__builtin_msa_binsli_h:
3102   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3103   // These intrinsics take an unsigned 5 bit immediate.
3104   // The first block of intrinsics actually have an unsigned 5 bit field,
3105   // not a df/n field.
3106   case Mips::BI__builtin_msa_cfcmsa:
3107   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3108   case Mips::BI__builtin_msa_clei_u_b:
3109   case Mips::BI__builtin_msa_clei_u_h:
3110   case Mips::BI__builtin_msa_clei_u_w:
3111   case Mips::BI__builtin_msa_clei_u_d:
3112   case Mips::BI__builtin_msa_clti_u_b:
3113   case Mips::BI__builtin_msa_clti_u_h:
3114   case Mips::BI__builtin_msa_clti_u_w:
3115   case Mips::BI__builtin_msa_clti_u_d:
3116   case Mips::BI__builtin_msa_maxi_u_b:
3117   case Mips::BI__builtin_msa_maxi_u_h:
3118   case Mips::BI__builtin_msa_maxi_u_w:
3119   case Mips::BI__builtin_msa_maxi_u_d:
3120   case Mips::BI__builtin_msa_mini_u_b:
3121   case Mips::BI__builtin_msa_mini_u_h:
3122   case Mips::BI__builtin_msa_mini_u_w:
3123   case Mips::BI__builtin_msa_mini_u_d:
3124   case Mips::BI__builtin_msa_addvi_b:
3125   case Mips::BI__builtin_msa_addvi_h:
3126   case Mips::BI__builtin_msa_addvi_w:
3127   case Mips::BI__builtin_msa_addvi_d:
3128   case Mips::BI__builtin_msa_bclri_w:
3129   case Mips::BI__builtin_msa_bnegi_w:
3130   case Mips::BI__builtin_msa_bseti_w:
3131   case Mips::BI__builtin_msa_sat_s_w:
3132   case Mips::BI__builtin_msa_sat_u_w:
3133   case Mips::BI__builtin_msa_slli_w:
3134   case Mips::BI__builtin_msa_srai_w:
3135   case Mips::BI__builtin_msa_srari_w:
3136   case Mips::BI__builtin_msa_srli_w:
3137   case Mips::BI__builtin_msa_srlri_w:
3138   case Mips::BI__builtin_msa_subvi_b:
3139   case Mips::BI__builtin_msa_subvi_h:
3140   case Mips::BI__builtin_msa_subvi_w:
3141   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3142   case Mips::BI__builtin_msa_binsli_w:
3143   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3144   // These intrinsics take an unsigned 6 bit immediate.
3145   case Mips::BI__builtin_msa_bclri_d:
3146   case Mips::BI__builtin_msa_bnegi_d:
3147   case Mips::BI__builtin_msa_bseti_d:
3148   case Mips::BI__builtin_msa_sat_s_d:
3149   case Mips::BI__builtin_msa_sat_u_d:
3150   case Mips::BI__builtin_msa_slli_d:
3151   case Mips::BI__builtin_msa_srai_d:
3152   case Mips::BI__builtin_msa_srari_d:
3153   case Mips::BI__builtin_msa_srli_d:
3154   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3155   case Mips::BI__builtin_msa_binsli_d:
3156   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3157   // These intrinsics take a signed 5 bit immediate.
3158   case Mips::BI__builtin_msa_ceqi_b:
3159   case Mips::BI__builtin_msa_ceqi_h:
3160   case Mips::BI__builtin_msa_ceqi_w:
3161   case Mips::BI__builtin_msa_ceqi_d:
3162   case Mips::BI__builtin_msa_clti_s_b:
3163   case Mips::BI__builtin_msa_clti_s_h:
3164   case Mips::BI__builtin_msa_clti_s_w:
3165   case Mips::BI__builtin_msa_clti_s_d:
3166   case Mips::BI__builtin_msa_clei_s_b:
3167   case Mips::BI__builtin_msa_clei_s_h:
3168   case Mips::BI__builtin_msa_clei_s_w:
3169   case Mips::BI__builtin_msa_clei_s_d:
3170   case Mips::BI__builtin_msa_maxi_s_b:
3171   case Mips::BI__builtin_msa_maxi_s_h:
3172   case Mips::BI__builtin_msa_maxi_s_w:
3173   case Mips::BI__builtin_msa_maxi_s_d:
3174   case Mips::BI__builtin_msa_mini_s_b:
3175   case Mips::BI__builtin_msa_mini_s_h:
3176   case Mips::BI__builtin_msa_mini_s_w:
3177   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3178   // These intrinsics take an unsigned 8 bit immediate.
3179   case Mips::BI__builtin_msa_andi_b:
3180   case Mips::BI__builtin_msa_nori_b:
3181   case Mips::BI__builtin_msa_ori_b:
3182   case Mips::BI__builtin_msa_shf_b:
3183   case Mips::BI__builtin_msa_shf_h:
3184   case Mips::BI__builtin_msa_shf_w:
3185   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3186   case Mips::BI__builtin_msa_bseli_b:
3187   case Mips::BI__builtin_msa_bmnzi_b:
3188   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3189   // df/n format
3190   // These intrinsics take an unsigned 4 bit immediate.
3191   case Mips::BI__builtin_msa_copy_s_b:
3192   case Mips::BI__builtin_msa_copy_u_b:
3193   case Mips::BI__builtin_msa_insve_b:
3194   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3195   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3196   // These intrinsics take an unsigned 3 bit immediate.
3197   case Mips::BI__builtin_msa_copy_s_h:
3198   case Mips::BI__builtin_msa_copy_u_h:
3199   case Mips::BI__builtin_msa_insve_h:
3200   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3201   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3202   // These intrinsics take an unsigned 2 bit immediate.
3203   case Mips::BI__builtin_msa_copy_s_w:
3204   case Mips::BI__builtin_msa_copy_u_w:
3205   case Mips::BI__builtin_msa_insve_w:
3206   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3207   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3208   // These intrinsics take an unsigned 1 bit immediate.
3209   case Mips::BI__builtin_msa_copy_s_d:
3210   case Mips::BI__builtin_msa_copy_u_d:
3211   case Mips::BI__builtin_msa_insve_d:
3212   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3213   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3214   // Memory offsets and immediate loads.
3215   // These intrinsics take a signed 10 bit immediate.
3216   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3217   case Mips::BI__builtin_msa_ldi_h:
3218   case Mips::BI__builtin_msa_ldi_w:
3219   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3220   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3221   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3222   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3223   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3224   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3225   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3226   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3227   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3228   }
3229 
3230   if (!m)
3231     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3232 
3233   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3234          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3235 }
3236 
3237 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3238   unsigned i = 0, l = 0, u = 0;
3239   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3240                       BuiltinID == PPC::BI__builtin_divdeu ||
3241                       BuiltinID == PPC::BI__builtin_bpermd;
3242   bool IsTarget64Bit = Context.getTargetInfo()
3243                               .getTypeWidth(Context
3244                                             .getTargetInfo()
3245                                             .getIntPtrType()) == 64;
3246   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3247                        BuiltinID == PPC::BI__builtin_divweu ||
3248                        BuiltinID == PPC::BI__builtin_divde ||
3249                        BuiltinID == PPC::BI__builtin_divdeu;
3250 
3251   if (Is64BitBltin && !IsTarget64Bit)
3252     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3253            << TheCall->getSourceRange();
3254 
3255   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3256       (BuiltinID == PPC::BI__builtin_bpermd &&
3257        !Context.getTargetInfo().hasFeature("bpermd")))
3258     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3259            << TheCall->getSourceRange();
3260 
3261   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3262     if (!Context.getTargetInfo().hasFeature("vsx"))
3263       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3264              << TheCall->getSourceRange();
3265     return false;
3266   };
3267 
3268   switch (BuiltinID) {
3269   default: return false;
3270   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3271   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3272     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3273            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3274   case PPC::BI__builtin_altivec_dss:
3275     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3276   case PPC::BI__builtin_tbegin:
3277   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3278   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3279   case PPC::BI__builtin_tabortwc:
3280   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3281   case PPC::BI__builtin_tabortwci:
3282   case PPC::BI__builtin_tabortdci:
3283     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3284            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3285   case PPC::BI__builtin_altivec_dst:
3286   case PPC::BI__builtin_altivec_dstt:
3287   case PPC::BI__builtin_altivec_dstst:
3288   case PPC::BI__builtin_altivec_dststt:
3289     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3290   case PPC::BI__builtin_vsx_xxpermdi:
3291   case PPC::BI__builtin_vsx_xxsldwi:
3292     return SemaBuiltinVSX(TheCall);
3293   case PPC::BI__builtin_unpack_vector_int128:
3294     return SemaVSXCheck(TheCall) ||
3295            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3296   case PPC::BI__builtin_pack_vector_int128:
3297     return SemaVSXCheck(TheCall);
3298   }
3299   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3300 }
3301 
3302 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3303                                            CallExpr *TheCall) {
3304   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3305     Expr *Arg = TheCall->getArg(0);
3306     llvm::APSInt AbortCode(32);
3307     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3308         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3309       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3310              << Arg->getSourceRange();
3311   }
3312 
3313   // For intrinsics which take an immediate value as part of the instruction,
3314   // range check them here.
3315   unsigned i = 0, l = 0, u = 0;
3316   switch (BuiltinID) {
3317   default: return false;
3318   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3319   case SystemZ::BI__builtin_s390_verimb:
3320   case SystemZ::BI__builtin_s390_verimh:
3321   case SystemZ::BI__builtin_s390_verimf:
3322   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3323   case SystemZ::BI__builtin_s390_vfaeb:
3324   case SystemZ::BI__builtin_s390_vfaeh:
3325   case SystemZ::BI__builtin_s390_vfaef:
3326   case SystemZ::BI__builtin_s390_vfaebs:
3327   case SystemZ::BI__builtin_s390_vfaehs:
3328   case SystemZ::BI__builtin_s390_vfaefs:
3329   case SystemZ::BI__builtin_s390_vfaezb:
3330   case SystemZ::BI__builtin_s390_vfaezh:
3331   case SystemZ::BI__builtin_s390_vfaezf:
3332   case SystemZ::BI__builtin_s390_vfaezbs:
3333   case SystemZ::BI__builtin_s390_vfaezhs:
3334   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3335   case SystemZ::BI__builtin_s390_vfisb:
3336   case SystemZ::BI__builtin_s390_vfidb:
3337     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3338            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3339   case SystemZ::BI__builtin_s390_vftcisb:
3340   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3341   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3342   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3343   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3344   case SystemZ::BI__builtin_s390_vstrcb:
3345   case SystemZ::BI__builtin_s390_vstrch:
3346   case SystemZ::BI__builtin_s390_vstrcf:
3347   case SystemZ::BI__builtin_s390_vstrczb:
3348   case SystemZ::BI__builtin_s390_vstrczh:
3349   case SystemZ::BI__builtin_s390_vstrczf:
3350   case SystemZ::BI__builtin_s390_vstrcbs:
3351   case SystemZ::BI__builtin_s390_vstrchs:
3352   case SystemZ::BI__builtin_s390_vstrcfs:
3353   case SystemZ::BI__builtin_s390_vstrczbs:
3354   case SystemZ::BI__builtin_s390_vstrczhs:
3355   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3356   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3357   case SystemZ::BI__builtin_s390_vfminsb:
3358   case SystemZ::BI__builtin_s390_vfmaxsb:
3359   case SystemZ::BI__builtin_s390_vfmindb:
3360   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3361   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3362   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3363   }
3364   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3365 }
3366 
3367 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3368 /// This checks that the target supports __builtin_cpu_supports and
3369 /// that the string argument is constant and valid.
3370 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3371   Expr *Arg = TheCall->getArg(0);
3372 
3373   // Check if the argument is a string literal.
3374   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3375     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3376            << Arg->getSourceRange();
3377 
3378   // Check the contents of the string.
3379   StringRef Feature =
3380       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3381   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3382     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3383            << Arg->getSourceRange();
3384   return false;
3385 }
3386 
3387 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3388 /// This checks that the target supports __builtin_cpu_is and
3389 /// that the string argument is constant and valid.
3390 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3391   Expr *Arg = TheCall->getArg(0);
3392 
3393   // Check if the argument is a string literal.
3394   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3395     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3396            << Arg->getSourceRange();
3397 
3398   // Check the contents of the string.
3399   StringRef Feature =
3400       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3401   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3402     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3403            << Arg->getSourceRange();
3404   return false;
3405 }
3406 
3407 // Check if the rounding mode is legal.
3408 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3409   // Indicates if this instruction has rounding control or just SAE.
3410   bool HasRC = false;
3411 
3412   unsigned ArgNum = 0;
3413   switch (BuiltinID) {
3414   default:
3415     return false;
3416   case X86::BI__builtin_ia32_vcvttsd2si32:
3417   case X86::BI__builtin_ia32_vcvttsd2si64:
3418   case X86::BI__builtin_ia32_vcvttsd2usi32:
3419   case X86::BI__builtin_ia32_vcvttsd2usi64:
3420   case X86::BI__builtin_ia32_vcvttss2si32:
3421   case X86::BI__builtin_ia32_vcvttss2si64:
3422   case X86::BI__builtin_ia32_vcvttss2usi32:
3423   case X86::BI__builtin_ia32_vcvttss2usi64:
3424     ArgNum = 1;
3425     break;
3426   case X86::BI__builtin_ia32_maxpd512:
3427   case X86::BI__builtin_ia32_maxps512:
3428   case X86::BI__builtin_ia32_minpd512:
3429   case X86::BI__builtin_ia32_minps512:
3430     ArgNum = 2;
3431     break;
3432   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3433   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3434   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3435   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3436   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3437   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3438   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3439   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3440   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3441   case X86::BI__builtin_ia32_exp2pd_mask:
3442   case X86::BI__builtin_ia32_exp2ps_mask:
3443   case X86::BI__builtin_ia32_getexppd512_mask:
3444   case X86::BI__builtin_ia32_getexpps512_mask:
3445   case X86::BI__builtin_ia32_rcp28pd_mask:
3446   case X86::BI__builtin_ia32_rcp28ps_mask:
3447   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3448   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3449   case X86::BI__builtin_ia32_vcomisd:
3450   case X86::BI__builtin_ia32_vcomiss:
3451   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3452     ArgNum = 3;
3453     break;
3454   case X86::BI__builtin_ia32_cmppd512_mask:
3455   case X86::BI__builtin_ia32_cmpps512_mask:
3456   case X86::BI__builtin_ia32_cmpsd_mask:
3457   case X86::BI__builtin_ia32_cmpss_mask:
3458   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3459   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3460   case X86::BI__builtin_ia32_getexpss128_round_mask:
3461   case X86::BI__builtin_ia32_getmantpd512_mask:
3462   case X86::BI__builtin_ia32_getmantps512_mask:
3463   case X86::BI__builtin_ia32_maxsd_round_mask:
3464   case X86::BI__builtin_ia32_maxss_round_mask:
3465   case X86::BI__builtin_ia32_minsd_round_mask:
3466   case X86::BI__builtin_ia32_minss_round_mask:
3467   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3468   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3469   case X86::BI__builtin_ia32_reducepd512_mask:
3470   case X86::BI__builtin_ia32_reduceps512_mask:
3471   case X86::BI__builtin_ia32_rndscalepd_mask:
3472   case X86::BI__builtin_ia32_rndscaleps_mask:
3473   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3474   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3475     ArgNum = 4;
3476     break;
3477   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3478   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3479   case X86::BI__builtin_ia32_fixupimmps512_mask:
3480   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3481   case X86::BI__builtin_ia32_fixupimmsd_mask:
3482   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3483   case X86::BI__builtin_ia32_fixupimmss_mask:
3484   case X86::BI__builtin_ia32_fixupimmss_maskz:
3485   case X86::BI__builtin_ia32_getmantsd_round_mask:
3486   case X86::BI__builtin_ia32_getmantss_round_mask:
3487   case X86::BI__builtin_ia32_rangepd512_mask:
3488   case X86::BI__builtin_ia32_rangeps512_mask:
3489   case X86::BI__builtin_ia32_rangesd128_round_mask:
3490   case X86::BI__builtin_ia32_rangess128_round_mask:
3491   case X86::BI__builtin_ia32_reducesd_mask:
3492   case X86::BI__builtin_ia32_reducess_mask:
3493   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3494   case X86::BI__builtin_ia32_rndscaless_round_mask:
3495     ArgNum = 5;
3496     break;
3497   case X86::BI__builtin_ia32_vcvtsd2si64:
3498   case X86::BI__builtin_ia32_vcvtsd2si32:
3499   case X86::BI__builtin_ia32_vcvtsd2usi32:
3500   case X86::BI__builtin_ia32_vcvtsd2usi64:
3501   case X86::BI__builtin_ia32_vcvtss2si32:
3502   case X86::BI__builtin_ia32_vcvtss2si64:
3503   case X86::BI__builtin_ia32_vcvtss2usi32:
3504   case X86::BI__builtin_ia32_vcvtss2usi64:
3505   case X86::BI__builtin_ia32_sqrtpd512:
3506   case X86::BI__builtin_ia32_sqrtps512:
3507     ArgNum = 1;
3508     HasRC = true;
3509     break;
3510   case X86::BI__builtin_ia32_addpd512:
3511   case X86::BI__builtin_ia32_addps512:
3512   case X86::BI__builtin_ia32_divpd512:
3513   case X86::BI__builtin_ia32_divps512:
3514   case X86::BI__builtin_ia32_mulpd512:
3515   case X86::BI__builtin_ia32_mulps512:
3516   case X86::BI__builtin_ia32_subpd512:
3517   case X86::BI__builtin_ia32_subps512:
3518   case X86::BI__builtin_ia32_cvtsi2sd64:
3519   case X86::BI__builtin_ia32_cvtsi2ss32:
3520   case X86::BI__builtin_ia32_cvtsi2ss64:
3521   case X86::BI__builtin_ia32_cvtusi2sd64:
3522   case X86::BI__builtin_ia32_cvtusi2ss32:
3523   case X86::BI__builtin_ia32_cvtusi2ss64:
3524     ArgNum = 2;
3525     HasRC = true;
3526     break;
3527   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3528   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3529   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3530   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3531   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3532   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3533   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3534   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3535   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3536   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3537   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3538   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3539   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3540   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3541   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3542     ArgNum = 3;
3543     HasRC = true;
3544     break;
3545   case X86::BI__builtin_ia32_addss_round_mask:
3546   case X86::BI__builtin_ia32_addsd_round_mask:
3547   case X86::BI__builtin_ia32_divss_round_mask:
3548   case X86::BI__builtin_ia32_divsd_round_mask:
3549   case X86::BI__builtin_ia32_mulss_round_mask:
3550   case X86::BI__builtin_ia32_mulsd_round_mask:
3551   case X86::BI__builtin_ia32_subss_round_mask:
3552   case X86::BI__builtin_ia32_subsd_round_mask:
3553   case X86::BI__builtin_ia32_scalefpd512_mask:
3554   case X86::BI__builtin_ia32_scalefps512_mask:
3555   case X86::BI__builtin_ia32_scalefsd_round_mask:
3556   case X86::BI__builtin_ia32_scalefss_round_mask:
3557   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3558   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3559   case X86::BI__builtin_ia32_sqrtss_round_mask:
3560   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3561   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3562   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3563   case X86::BI__builtin_ia32_vfmaddss3_mask:
3564   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3565   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3566   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3567   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3568   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3569   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3570   case X86::BI__builtin_ia32_vfmaddps512_mask:
3571   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3572   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3573   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3574   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3575   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3576   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3577   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3578   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3579   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3580   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3581   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3582     ArgNum = 4;
3583     HasRC = true;
3584     break;
3585   }
3586 
3587   llvm::APSInt Result;
3588 
3589   // We can't check the value of a dependent argument.
3590   Expr *Arg = TheCall->getArg(ArgNum);
3591   if (Arg->isTypeDependent() || Arg->isValueDependent())
3592     return false;
3593 
3594   // Check constant-ness first.
3595   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3596     return true;
3597 
3598   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3599   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3600   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3601   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3602   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3603       Result == 8/*ROUND_NO_EXC*/ ||
3604       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3605       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3606     return false;
3607 
3608   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3609          << Arg->getSourceRange();
3610 }
3611 
3612 // Check if the gather/scatter scale is legal.
3613 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3614                                              CallExpr *TheCall) {
3615   unsigned ArgNum = 0;
3616   switch (BuiltinID) {
3617   default:
3618     return false;
3619   case X86::BI__builtin_ia32_gatherpfdpd:
3620   case X86::BI__builtin_ia32_gatherpfdps:
3621   case X86::BI__builtin_ia32_gatherpfqpd:
3622   case X86::BI__builtin_ia32_gatherpfqps:
3623   case X86::BI__builtin_ia32_scatterpfdpd:
3624   case X86::BI__builtin_ia32_scatterpfdps:
3625   case X86::BI__builtin_ia32_scatterpfqpd:
3626   case X86::BI__builtin_ia32_scatterpfqps:
3627     ArgNum = 3;
3628     break;
3629   case X86::BI__builtin_ia32_gatherd_pd:
3630   case X86::BI__builtin_ia32_gatherd_pd256:
3631   case X86::BI__builtin_ia32_gatherq_pd:
3632   case X86::BI__builtin_ia32_gatherq_pd256:
3633   case X86::BI__builtin_ia32_gatherd_ps:
3634   case X86::BI__builtin_ia32_gatherd_ps256:
3635   case X86::BI__builtin_ia32_gatherq_ps:
3636   case X86::BI__builtin_ia32_gatherq_ps256:
3637   case X86::BI__builtin_ia32_gatherd_q:
3638   case X86::BI__builtin_ia32_gatherd_q256:
3639   case X86::BI__builtin_ia32_gatherq_q:
3640   case X86::BI__builtin_ia32_gatherq_q256:
3641   case X86::BI__builtin_ia32_gatherd_d:
3642   case X86::BI__builtin_ia32_gatherd_d256:
3643   case X86::BI__builtin_ia32_gatherq_d:
3644   case X86::BI__builtin_ia32_gatherq_d256:
3645   case X86::BI__builtin_ia32_gather3div2df:
3646   case X86::BI__builtin_ia32_gather3div2di:
3647   case X86::BI__builtin_ia32_gather3div4df:
3648   case X86::BI__builtin_ia32_gather3div4di:
3649   case X86::BI__builtin_ia32_gather3div4sf:
3650   case X86::BI__builtin_ia32_gather3div4si:
3651   case X86::BI__builtin_ia32_gather3div8sf:
3652   case X86::BI__builtin_ia32_gather3div8si:
3653   case X86::BI__builtin_ia32_gather3siv2df:
3654   case X86::BI__builtin_ia32_gather3siv2di:
3655   case X86::BI__builtin_ia32_gather3siv4df:
3656   case X86::BI__builtin_ia32_gather3siv4di:
3657   case X86::BI__builtin_ia32_gather3siv4sf:
3658   case X86::BI__builtin_ia32_gather3siv4si:
3659   case X86::BI__builtin_ia32_gather3siv8sf:
3660   case X86::BI__builtin_ia32_gather3siv8si:
3661   case X86::BI__builtin_ia32_gathersiv8df:
3662   case X86::BI__builtin_ia32_gathersiv16sf:
3663   case X86::BI__builtin_ia32_gatherdiv8df:
3664   case X86::BI__builtin_ia32_gatherdiv16sf:
3665   case X86::BI__builtin_ia32_gathersiv8di:
3666   case X86::BI__builtin_ia32_gathersiv16si:
3667   case X86::BI__builtin_ia32_gatherdiv8di:
3668   case X86::BI__builtin_ia32_gatherdiv16si:
3669   case X86::BI__builtin_ia32_scatterdiv2df:
3670   case X86::BI__builtin_ia32_scatterdiv2di:
3671   case X86::BI__builtin_ia32_scatterdiv4df:
3672   case X86::BI__builtin_ia32_scatterdiv4di:
3673   case X86::BI__builtin_ia32_scatterdiv4sf:
3674   case X86::BI__builtin_ia32_scatterdiv4si:
3675   case X86::BI__builtin_ia32_scatterdiv8sf:
3676   case X86::BI__builtin_ia32_scatterdiv8si:
3677   case X86::BI__builtin_ia32_scattersiv2df:
3678   case X86::BI__builtin_ia32_scattersiv2di:
3679   case X86::BI__builtin_ia32_scattersiv4df:
3680   case X86::BI__builtin_ia32_scattersiv4di:
3681   case X86::BI__builtin_ia32_scattersiv4sf:
3682   case X86::BI__builtin_ia32_scattersiv4si:
3683   case X86::BI__builtin_ia32_scattersiv8sf:
3684   case X86::BI__builtin_ia32_scattersiv8si:
3685   case X86::BI__builtin_ia32_scattersiv8df:
3686   case X86::BI__builtin_ia32_scattersiv16sf:
3687   case X86::BI__builtin_ia32_scatterdiv8df:
3688   case X86::BI__builtin_ia32_scatterdiv16sf:
3689   case X86::BI__builtin_ia32_scattersiv8di:
3690   case X86::BI__builtin_ia32_scattersiv16si:
3691   case X86::BI__builtin_ia32_scatterdiv8di:
3692   case X86::BI__builtin_ia32_scatterdiv16si:
3693     ArgNum = 4;
3694     break;
3695   }
3696 
3697   llvm::APSInt Result;
3698 
3699   // We can't check the value of a dependent argument.
3700   Expr *Arg = TheCall->getArg(ArgNum);
3701   if (Arg->isTypeDependent() || Arg->isValueDependent())
3702     return false;
3703 
3704   // Check constant-ness first.
3705   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3706     return true;
3707 
3708   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3709     return false;
3710 
3711   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3712          << Arg->getSourceRange();
3713 }
3714 
3715 static bool isX86_32Builtin(unsigned BuiltinID) {
3716   // These builtins only work on x86-32 targets.
3717   switch (BuiltinID) {
3718   case X86::BI__builtin_ia32_readeflags_u32:
3719   case X86::BI__builtin_ia32_writeeflags_u32:
3720     return true;
3721   }
3722 
3723   return false;
3724 }
3725 
3726 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3727   if (BuiltinID == X86::BI__builtin_cpu_supports)
3728     return SemaBuiltinCpuSupports(*this, TheCall);
3729 
3730   if (BuiltinID == X86::BI__builtin_cpu_is)
3731     return SemaBuiltinCpuIs(*this, TheCall);
3732 
3733   // Check for 32-bit only builtins on a 64-bit target.
3734   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3735   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3736     return Diag(TheCall->getCallee()->getBeginLoc(),
3737                 diag::err_32_bit_builtin_64_bit_tgt);
3738 
3739   // If the intrinsic has rounding or SAE make sure its valid.
3740   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3741     return true;
3742 
3743   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3744   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3745     return true;
3746 
3747   // For intrinsics which take an immediate value as part of the instruction,
3748   // range check them here.
3749   int i = 0, l = 0, u = 0;
3750   switch (BuiltinID) {
3751   default:
3752     return false;
3753   case X86::BI__builtin_ia32_vec_ext_v2si:
3754   case X86::BI__builtin_ia32_vec_ext_v2di:
3755   case X86::BI__builtin_ia32_vextractf128_pd256:
3756   case X86::BI__builtin_ia32_vextractf128_ps256:
3757   case X86::BI__builtin_ia32_vextractf128_si256:
3758   case X86::BI__builtin_ia32_extract128i256:
3759   case X86::BI__builtin_ia32_extractf64x4_mask:
3760   case X86::BI__builtin_ia32_extracti64x4_mask:
3761   case X86::BI__builtin_ia32_extractf32x8_mask:
3762   case X86::BI__builtin_ia32_extracti32x8_mask:
3763   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3764   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3765   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3766   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3767     i = 1; l = 0; u = 1;
3768     break;
3769   case X86::BI__builtin_ia32_vec_set_v2di:
3770   case X86::BI__builtin_ia32_vinsertf128_pd256:
3771   case X86::BI__builtin_ia32_vinsertf128_ps256:
3772   case X86::BI__builtin_ia32_vinsertf128_si256:
3773   case X86::BI__builtin_ia32_insert128i256:
3774   case X86::BI__builtin_ia32_insertf32x8:
3775   case X86::BI__builtin_ia32_inserti32x8:
3776   case X86::BI__builtin_ia32_insertf64x4:
3777   case X86::BI__builtin_ia32_inserti64x4:
3778   case X86::BI__builtin_ia32_insertf64x2_256:
3779   case X86::BI__builtin_ia32_inserti64x2_256:
3780   case X86::BI__builtin_ia32_insertf32x4_256:
3781   case X86::BI__builtin_ia32_inserti32x4_256:
3782     i = 2; l = 0; u = 1;
3783     break;
3784   case X86::BI__builtin_ia32_vpermilpd:
3785   case X86::BI__builtin_ia32_vec_ext_v4hi:
3786   case X86::BI__builtin_ia32_vec_ext_v4si:
3787   case X86::BI__builtin_ia32_vec_ext_v4sf:
3788   case X86::BI__builtin_ia32_vec_ext_v4di:
3789   case X86::BI__builtin_ia32_extractf32x4_mask:
3790   case X86::BI__builtin_ia32_extracti32x4_mask:
3791   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3792   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3793     i = 1; l = 0; u = 3;
3794     break;
3795   case X86::BI_mm_prefetch:
3796   case X86::BI__builtin_ia32_vec_ext_v8hi:
3797   case X86::BI__builtin_ia32_vec_ext_v8si:
3798     i = 1; l = 0; u = 7;
3799     break;
3800   case X86::BI__builtin_ia32_sha1rnds4:
3801   case X86::BI__builtin_ia32_blendpd:
3802   case X86::BI__builtin_ia32_shufpd:
3803   case X86::BI__builtin_ia32_vec_set_v4hi:
3804   case X86::BI__builtin_ia32_vec_set_v4si:
3805   case X86::BI__builtin_ia32_vec_set_v4di:
3806   case X86::BI__builtin_ia32_shuf_f32x4_256:
3807   case X86::BI__builtin_ia32_shuf_f64x2_256:
3808   case X86::BI__builtin_ia32_shuf_i32x4_256:
3809   case X86::BI__builtin_ia32_shuf_i64x2_256:
3810   case X86::BI__builtin_ia32_insertf64x2_512:
3811   case X86::BI__builtin_ia32_inserti64x2_512:
3812   case X86::BI__builtin_ia32_insertf32x4:
3813   case X86::BI__builtin_ia32_inserti32x4:
3814     i = 2; l = 0; u = 3;
3815     break;
3816   case X86::BI__builtin_ia32_vpermil2pd:
3817   case X86::BI__builtin_ia32_vpermil2pd256:
3818   case X86::BI__builtin_ia32_vpermil2ps:
3819   case X86::BI__builtin_ia32_vpermil2ps256:
3820     i = 3; l = 0; u = 3;
3821     break;
3822   case X86::BI__builtin_ia32_cmpb128_mask:
3823   case X86::BI__builtin_ia32_cmpw128_mask:
3824   case X86::BI__builtin_ia32_cmpd128_mask:
3825   case X86::BI__builtin_ia32_cmpq128_mask:
3826   case X86::BI__builtin_ia32_cmpb256_mask:
3827   case X86::BI__builtin_ia32_cmpw256_mask:
3828   case X86::BI__builtin_ia32_cmpd256_mask:
3829   case X86::BI__builtin_ia32_cmpq256_mask:
3830   case X86::BI__builtin_ia32_cmpb512_mask:
3831   case X86::BI__builtin_ia32_cmpw512_mask:
3832   case X86::BI__builtin_ia32_cmpd512_mask:
3833   case X86::BI__builtin_ia32_cmpq512_mask:
3834   case X86::BI__builtin_ia32_ucmpb128_mask:
3835   case X86::BI__builtin_ia32_ucmpw128_mask:
3836   case X86::BI__builtin_ia32_ucmpd128_mask:
3837   case X86::BI__builtin_ia32_ucmpq128_mask:
3838   case X86::BI__builtin_ia32_ucmpb256_mask:
3839   case X86::BI__builtin_ia32_ucmpw256_mask:
3840   case X86::BI__builtin_ia32_ucmpd256_mask:
3841   case X86::BI__builtin_ia32_ucmpq256_mask:
3842   case X86::BI__builtin_ia32_ucmpb512_mask:
3843   case X86::BI__builtin_ia32_ucmpw512_mask:
3844   case X86::BI__builtin_ia32_ucmpd512_mask:
3845   case X86::BI__builtin_ia32_ucmpq512_mask:
3846   case X86::BI__builtin_ia32_vpcomub:
3847   case X86::BI__builtin_ia32_vpcomuw:
3848   case X86::BI__builtin_ia32_vpcomud:
3849   case X86::BI__builtin_ia32_vpcomuq:
3850   case X86::BI__builtin_ia32_vpcomb:
3851   case X86::BI__builtin_ia32_vpcomw:
3852   case X86::BI__builtin_ia32_vpcomd:
3853   case X86::BI__builtin_ia32_vpcomq:
3854   case X86::BI__builtin_ia32_vec_set_v8hi:
3855   case X86::BI__builtin_ia32_vec_set_v8si:
3856     i = 2; l = 0; u = 7;
3857     break;
3858   case X86::BI__builtin_ia32_vpermilpd256:
3859   case X86::BI__builtin_ia32_roundps:
3860   case X86::BI__builtin_ia32_roundpd:
3861   case X86::BI__builtin_ia32_roundps256:
3862   case X86::BI__builtin_ia32_roundpd256:
3863   case X86::BI__builtin_ia32_getmantpd128_mask:
3864   case X86::BI__builtin_ia32_getmantpd256_mask:
3865   case X86::BI__builtin_ia32_getmantps128_mask:
3866   case X86::BI__builtin_ia32_getmantps256_mask:
3867   case X86::BI__builtin_ia32_getmantpd512_mask:
3868   case X86::BI__builtin_ia32_getmantps512_mask:
3869   case X86::BI__builtin_ia32_vec_ext_v16qi:
3870   case X86::BI__builtin_ia32_vec_ext_v16hi:
3871     i = 1; l = 0; u = 15;
3872     break;
3873   case X86::BI__builtin_ia32_pblendd128:
3874   case X86::BI__builtin_ia32_blendps:
3875   case X86::BI__builtin_ia32_blendpd256:
3876   case X86::BI__builtin_ia32_shufpd256:
3877   case X86::BI__builtin_ia32_roundss:
3878   case X86::BI__builtin_ia32_roundsd:
3879   case X86::BI__builtin_ia32_rangepd128_mask:
3880   case X86::BI__builtin_ia32_rangepd256_mask:
3881   case X86::BI__builtin_ia32_rangepd512_mask:
3882   case X86::BI__builtin_ia32_rangeps128_mask:
3883   case X86::BI__builtin_ia32_rangeps256_mask:
3884   case X86::BI__builtin_ia32_rangeps512_mask:
3885   case X86::BI__builtin_ia32_getmantsd_round_mask:
3886   case X86::BI__builtin_ia32_getmantss_round_mask:
3887   case X86::BI__builtin_ia32_vec_set_v16qi:
3888   case X86::BI__builtin_ia32_vec_set_v16hi:
3889     i = 2; l = 0; u = 15;
3890     break;
3891   case X86::BI__builtin_ia32_vec_ext_v32qi:
3892     i = 1; l = 0; u = 31;
3893     break;
3894   case X86::BI__builtin_ia32_cmpps:
3895   case X86::BI__builtin_ia32_cmpss:
3896   case X86::BI__builtin_ia32_cmppd:
3897   case X86::BI__builtin_ia32_cmpsd:
3898   case X86::BI__builtin_ia32_cmpps256:
3899   case X86::BI__builtin_ia32_cmppd256:
3900   case X86::BI__builtin_ia32_cmpps128_mask:
3901   case X86::BI__builtin_ia32_cmppd128_mask:
3902   case X86::BI__builtin_ia32_cmpps256_mask:
3903   case X86::BI__builtin_ia32_cmppd256_mask:
3904   case X86::BI__builtin_ia32_cmpps512_mask:
3905   case X86::BI__builtin_ia32_cmppd512_mask:
3906   case X86::BI__builtin_ia32_cmpsd_mask:
3907   case X86::BI__builtin_ia32_cmpss_mask:
3908   case X86::BI__builtin_ia32_vec_set_v32qi:
3909     i = 2; l = 0; u = 31;
3910     break;
3911   case X86::BI__builtin_ia32_permdf256:
3912   case X86::BI__builtin_ia32_permdi256:
3913   case X86::BI__builtin_ia32_permdf512:
3914   case X86::BI__builtin_ia32_permdi512:
3915   case X86::BI__builtin_ia32_vpermilps:
3916   case X86::BI__builtin_ia32_vpermilps256:
3917   case X86::BI__builtin_ia32_vpermilpd512:
3918   case X86::BI__builtin_ia32_vpermilps512:
3919   case X86::BI__builtin_ia32_pshufd:
3920   case X86::BI__builtin_ia32_pshufd256:
3921   case X86::BI__builtin_ia32_pshufd512:
3922   case X86::BI__builtin_ia32_pshufhw:
3923   case X86::BI__builtin_ia32_pshufhw256:
3924   case X86::BI__builtin_ia32_pshufhw512:
3925   case X86::BI__builtin_ia32_pshuflw:
3926   case X86::BI__builtin_ia32_pshuflw256:
3927   case X86::BI__builtin_ia32_pshuflw512:
3928   case X86::BI__builtin_ia32_vcvtps2ph:
3929   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3930   case X86::BI__builtin_ia32_vcvtps2ph256:
3931   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3932   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3933   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3934   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3935   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3936   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3937   case X86::BI__builtin_ia32_rndscaleps_mask:
3938   case X86::BI__builtin_ia32_rndscalepd_mask:
3939   case X86::BI__builtin_ia32_reducepd128_mask:
3940   case X86::BI__builtin_ia32_reducepd256_mask:
3941   case X86::BI__builtin_ia32_reducepd512_mask:
3942   case X86::BI__builtin_ia32_reduceps128_mask:
3943   case X86::BI__builtin_ia32_reduceps256_mask:
3944   case X86::BI__builtin_ia32_reduceps512_mask:
3945   case X86::BI__builtin_ia32_prold512:
3946   case X86::BI__builtin_ia32_prolq512:
3947   case X86::BI__builtin_ia32_prold128:
3948   case X86::BI__builtin_ia32_prold256:
3949   case X86::BI__builtin_ia32_prolq128:
3950   case X86::BI__builtin_ia32_prolq256:
3951   case X86::BI__builtin_ia32_prord512:
3952   case X86::BI__builtin_ia32_prorq512:
3953   case X86::BI__builtin_ia32_prord128:
3954   case X86::BI__builtin_ia32_prord256:
3955   case X86::BI__builtin_ia32_prorq128:
3956   case X86::BI__builtin_ia32_prorq256:
3957   case X86::BI__builtin_ia32_fpclasspd128_mask:
3958   case X86::BI__builtin_ia32_fpclasspd256_mask:
3959   case X86::BI__builtin_ia32_fpclassps128_mask:
3960   case X86::BI__builtin_ia32_fpclassps256_mask:
3961   case X86::BI__builtin_ia32_fpclassps512_mask:
3962   case X86::BI__builtin_ia32_fpclasspd512_mask:
3963   case X86::BI__builtin_ia32_fpclasssd_mask:
3964   case X86::BI__builtin_ia32_fpclassss_mask:
3965   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3966   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3967   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3968   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3969   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3970   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3971   case X86::BI__builtin_ia32_kshiftliqi:
3972   case X86::BI__builtin_ia32_kshiftlihi:
3973   case X86::BI__builtin_ia32_kshiftlisi:
3974   case X86::BI__builtin_ia32_kshiftlidi:
3975   case X86::BI__builtin_ia32_kshiftriqi:
3976   case X86::BI__builtin_ia32_kshiftrihi:
3977   case X86::BI__builtin_ia32_kshiftrisi:
3978   case X86::BI__builtin_ia32_kshiftridi:
3979     i = 1; l = 0; u = 255;
3980     break;
3981   case X86::BI__builtin_ia32_vperm2f128_pd256:
3982   case X86::BI__builtin_ia32_vperm2f128_ps256:
3983   case X86::BI__builtin_ia32_vperm2f128_si256:
3984   case X86::BI__builtin_ia32_permti256:
3985   case X86::BI__builtin_ia32_pblendw128:
3986   case X86::BI__builtin_ia32_pblendw256:
3987   case X86::BI__builtin_ia32_blendps256:
3988   case X86::BI__builtin_ia32_pblendd256:
3989   case X86::BI__builtin_ia32_palignr128:
3990   case X86::BI__builtin_ia32_palignr256:
3991   case X86::BI__builtin_ia32_palignr512:
3992   case X86::BI__builtin_ia32_alignq512:
3993   case X86::BI__builtin_ia32_alignd512:
3994   case X86::BI__builtin_ia32_alignd128:
3995   case X86::BI__builtin_ia32_alignd256:
3996   case X86::BI__builtin_ia32_alignq128:
3997   case X86::BI__builtin_ia32_alignq256:
3998   case X86::BI__builtin_ia32_vcomisd:
3999   case X86::BI__builtin_ia32_vcomiss:
4000   case X86::BI__builtin_ia32_shuf_f32x4:
4001   case X86::BI__builtin_ia32_shuf_f64x2:
4002   case X86::BI__builtin_ia32_shuf_i32x4:
4003   case X86::BI__builtin_ia32_shuf_i64x2:
4004   case X86::BI__builtin_ia32_shufpd512:
4005   case X86::BI__builtin_ia32_shufps:
4006   case X86::BI__builtin_ia32_shufps256:
4007   case X86::BI__builtin_ia32_shufps512:
4008   case X86::BI__builtin_ia32_dbpsadbw128:
4009   case X86::BI__builtin_ia32_dbpsadbw256:
4010   case X86::BI__builtin_ia32_dbpsadbw512:
4011   case X86::BI__builtin_ia32_vpshldd128:
4012   case X86::BI__builtin_ia32_vpshldd256:
4013   case X86::BI__builtin_ia32_vpshldd512:
4014   case X86::BI__builtin_ia32_vpshldq128:
4015   case X86::BI__builtin_ia32_vpshldq256:
4016   case X86::BI__builtin_ia32_vpshldq512:
4017   case X86::BI__builtin_ia32_vpshldw128:
4018   case X86::BI__builtin_ia32_vpshldw256:
4019   case X86::BI__builtin_ia32_vpshldw512:
4020   case X86::BI__builtin_ia32_vpshrdd128:
4021   case X86::BI__builtin_ia32_vpshrdd256:
4022   case X86::BI__builtin_ia32_vpshrdd512:
4023   case X86::BI__builtin_ia32_vpshrdq128:
4024   case X86::BI__builtin_ia32_vpshrdq256:
4025   case X86::BI__builtin_ia32_vpshrdq512:
4026   case X86::BI__builtin_ia32_vpshrdw128:
4027   case X86::BI__builtin_ia32_vpshrdw256:
4028   case X86::BI__builtin_ia32_vpshrdw512:
4029     i = 2; l = 0; u = 255;
4030     break;
4031   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4032   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4033   case X86::BI__builtin_ia32_fixupimmps512_mask:
4034   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4035   case X86::BI__builtin_ia32_fixupimmsd_mask:
4036   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4037   case X86::BI__builtin_ia32_fixupimmss_mask:
4038   case X86::BI__builtin_ia32_fixupimmss_maskz:
4039   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4040   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4041   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4042   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4043   case X86::BI__builtin_ia32_fixupimmps128_mask:
4044   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4045   case X86::BI__builtin_ia32_fixupimmps256_mask:
4046   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4047   case X86::BI__builtin_ia32_pternlogd512_mask:
4048   case X86::BI__builtin_ia32_pternlogd512_maskz:
4049   case X86::BI__builtin_ia32_pternlogq512_mask:
4050   case X86::BI__builtin_ia32_pternlogq512_maskz:
4051   case X86::BI__builtin_ia32_pternlogd128_mask:
4052   case X86::BI__builtin_ia32_pternlogd128_maskz:
4053   case X86::BI__builtin_ia32_pternlogd256_mask:
4054   case X86::BI__builtin_ia32_pternlogd256_maskz:
4055   case X86::BI__builtin_ia32_pternlogq128_mask:
4056   case X86::BI__builtin_ia32_pternlogq128_maskz:
4057   case X86::BI__builtin_ia32_pternlogq256_mask:
4058   case X86::BI__builtin_ia32_pternlogq256_maskz:
4059     i = 3; l = 0; u = 255;
4060     break;
4061   case X86::BI__builtin_ia32_gatherpfdpd:
4062   case X86::BI__builtin_ia32_gatherpfdps:
4063   case X86::BI__builtin_ia32_gatherpfqpd:
4064   case X86::BI__builtin_ia32_gatherpfqps:
4065   case X86::BI__builtin_ia32_scatterpfdpd:
4066   case X86::BI__builtin_ia32_scatterpfdps:
4067   case X86::BI__builtin_ia32_scatterpfqpd:
4068   case X86::BI__builtin_ia32_scatterpfqps:
4069     i = 4; l = 2; u = 3;
4070     break;
4071   case X86::BI__builtin_ia32_reducesd_mask:
4072   case X86::BI__builtin_ia32_reducess_mask:
4073   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4074   case X86::BI__builtin_ia32_rndscaless_round_mask:
4075     i = 4; l = 0; u = 255;
4076     break;
4077   }
4078 
4079   // Note that we don't force a hard error on the range check here, allowing
4080   // template-generated or macro-generated dead code to potentially have out-of-
4081   // range values. These need to code generate, but don't need to necessarily
4082   // make any sense. We use a warning that defaults to an error.
4083   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4084 }
4085 
4086 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4087 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4088 /// Returns true when the format fits the function and the FormatStringInfo has
4089 /// been populated.
4090 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4091                                FormatStringInfo *FSI) {
4092   FSI->HasVAListArg = Format->getFirstArg() == 0;
4093   FSI->FormatIdx = Format->getFormatIdx() - 1;
4094   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4095 
4096   // The way the format attribute works in GCC, the implicit this argument
4097   // of member functions is counted. However, it doesn't appear in our own
4098   // lists, so decrement format_idx in that case.
4099   if (IsCXXMember) {
4100     if(FSI->FormatIdx == 0)
4101       return false;
4102     --FSI->FormatIdx;
4103     if (FSI->FirstDataArg != 0)
4104       --FSI->FirstDataArg;
4105   }
4106   return true;
4107 }
4108 
4109 /// Checks if a the given expression evaluates to null.
4110 ///
4111 /// Returns true if the value evaluates to null.
4112 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4113   // If the expression has non-null type, it doesn't evaluate to null.
4114   if (auto nullability
4115         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4116     if (*nullability == NullabilityKind::NonNull)
4117       return false;
4118   }
4119 
4120   // As a special case, transparent unions initialized with zero are
4121   // considered null for the purposes of the nonnull attribute.
4122   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4123     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4124       if (const CompoundLiteralExpr *CLE =
4125           dyn_cast<CompoundLiteralExpr>(Expr))
4126         if (const InitListExpr *ILE =
4127             dyn_cast<InitListExpr>(CLE->getInitializer()))
4128           Expr = ILE->getInit(0);
4129   }
4130 
4131   bool Result;
4132   return (!Expr->isValueDependent() &&
4133           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4134           !Result);
4135 }
4136 
4137 static void CheckNonNullArgument(Sema &S,
4138                                  const Expr *ArgExpr,
4139                                  SourceLocation CallSiteLoc) {
4140   if (CheckNonNullExpr(S, ArgExpr))
4141     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4142                           S.PDiag(diag::warn_null_arg)
4143                               << ArgExpr->getSourceRange());
4144 }
4145 
4146 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4147   FormatStringInfo FSI;
4148   if ((GetFormatStringType(Format) == FST_NSString) &&
4149       getFormatStringInfo(Format, false, &FSI)) {
4150     Idx = FSI.FormatIdx;
4151     return true;
4152   }
4153   return false;
4154 }
4155 
4156 /// Diagnose use of %s directive in an NSString which is being passed
4157 /// as formatting string to formatting method.
4158 static void
4159 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4160                                         const NamedDecl *FDecl,
4161                                         Expr **Args,
4162                                         unsigned NumArgs) {
4163   unsigned Idx = 0;
4164   bool Format = false;
4165   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4166   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4167     Idx = 2;
4168     Format = true;
4169   }
4170   else
4171     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4172       if (S.GetFormatNSStringIdx(I, Idx)) {
4173         Format = true;
4174         break;
4175       }
4176     }
4177   if (!Format || NumArgs <= Idx)
4178     return;
4179   const Expr *FormatExpr = Args[Idx];
4180   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4181     FormatExpr = CSCE->getSubExpr();
4182   const StringLiteral *FormatString;
4183   if (const ObjCStringLiteral *OSL =
4184       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4185     FormatString = OSL->getString();
4186   else
4187     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4188   if (!FormatString)
4189     return;
4190   if (S.FormatStringHasSArg(FormatString)) {
4191     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4192       << "%s" << 1 << 1;
4193     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4194       << FDecl->getDeclName();
4195   }
4196 }
4197 
4198 /// Determine whether the given type has a non-null nullability annotation.
4199 static bool isNonNullType(ASTContext &ctx, QualType type) {
4200   if (auto nullability = type->getNullability(ctx))
4201     return *nullability == NullabilityKind::NonNull;
4202 
4203   return false;
4204 }
4205 
4206 static void CheckNonNullArguments(Sema &S,
4207                                   const NamedDecl *FDecl,
4208                                   const FunctionProtoType *Proto,
4209                                   ArrayRef<const Expr *> Args,
4210                                   SourceLocation CallSiteLoc) {
4211   assert((FDecl || Proto) && "Need a function declaration or prototype");
4212 
4213   // Already checked by by constant evaluator.
4214   if (S.isConstantEvaluated())
4215     return;
4216   // Check the attributes attached to the method/function itself.
4217   llvm::SmallBitVector NonNullArgs;
4218   if (FDecl) {
4219     // Handle the nonnull attribute on the function/method declaration itself.
4220     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4221       if (!NonNull->args_size()) {
4222         // Easy case: all pointer arguments are nonnull.
4223         for (const auto *Arg : Args)
4224           if (S.isValidPointerAttrType(Arg->getType()))
4225             CheckNonNullArgument(S, Arg, CallSiteLoc);
4226         return;
4227       }
4228 
4229       for (const ParamIdx &Idx : NonNull->args()) {
4230         unsigned IdxAST = Idx.getASTIndex();
4231         if (IdxAST >= Args.size())
4232           continue;
4233         if (NonNullArgs.empty())
4234           NonNullArgs.resize(Args.size());
4235         NonNullArgs.set(IdxAST);
4236       }
4237     }
4238   }
4239 
4240   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4241     // Handle the nonnull attribute on the parameters of the
4242     // function/method.
4243     ArrayRef<ParmVarDecl*> parms;
4244     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4245       parms = FD->parameters();
4246     else
4247       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4248 
4249     unsigned ParamIndex = 0;
4250     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4251          I != E; ++I, ++ParamIndex) {
4252       const ParmVarDecl *PVD = *I;
4253       if (PVD->hasAttr<NonNullAttr>() ||
4254           isNonNullType(S.Context, PVD->getType())) {
4255         if (NonNullArgs.empty())
4256           NonNullArgs.resize(Args.size());
4257 
4258         NonNullArgs.set(ParamIndex);
4259       }
4260     }
4261   } else {
4262     // If we have a non-function, non-method declaration but no
4263     // function prototype, try to dig out the function prototype.
4264     if (!Proto) {
4265       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4266         QualType type = VD->getType().getNonReferenceType();
4267         if (auto pointerType = type->getAs<PointerType>())
4268           type = pointerType->getPointeeType();
4269         else if (auto blockType = type->getAs<BlockPointerType>())
4270           type = blockType->getPointeeType();
4271         // FIXME: data member pointers?
4272 
4273         // Dig out the function prototype, if there is one.
4274         Proto = type->getAs<FunctionProtoType>();
4275       }
4276     }
4277 
4278     // Fill in non-null argument information from the nullability
4279     // information on the parameter types (if we have them).
4280     if (Proto) {
4281       unsigned Index = 0;
4282       for (auto paramType : Proto->getParamTypes()) {
4283         if (isNonNullType(S.Context, paramType)) {
4284           if (NonNullArgs.empty())
4285             NonNullArgs.resize(Args.size());
4286 
4287           NonNullArgs.set(Index);
4288         }
4289 
4290         ++Index;
4291       }
4292     }
4293   }
4294 
4295   // Check for non-null arguments.
4296   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4297        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4298     if (NonNullArgs[ArgIndex])
4299       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4300   }
4301 }
4302 
4303 /// Handles the checks for format strings, non-POD arguments to vararg
4304 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4305 /// attributes.
4306 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4307                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4308                      bool IsMemberFunction, SourceLocation Loc,
4309                      SourceRange Range, VariadicCallType CallType) {
4310   // FIXME: We should check as much as we can in the template definition.
4311   if (CurContext->isDependentContext())
4312     return;
4313 
4314   // Printf and scanf checking.
4315   llvm::SmallBitVector CheckedVarArgs;
4316   if (FDecl) {
4317     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4318       // Only create vector if there are format attributes.
4319       CheckedVarArgs.resize(Args.size());
4320 
4321       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4322                            CheckedVarArgs);
4323     }
4324   }
4325 
4326   // Refuse POD arguments that weren't caught by the format string
4327   // checks above.
4328   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4329   if (CallType != VariadicDoesNotApply &&
4330       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4331     unsigned NumParams = Proto ? Proto->getNumParams()
4332                        : FDecl && isa<FunctionDecl>(FDecl)
4333                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4334                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4335                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4336                        : 0;
4337 
4338     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4339       // Args[ArgIdx] can be null in malformed code.
4340       if (const Expr *Arg = Args[ArgIdx]) {
4341         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4342           checkVariadicArgument(Arg, CallType);
4343       }
4344     }
4345   }
4346 
4347   if (FDecl || Proto) {
4348     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4349 
4350     // Type safety checking.
4351     if (FDecl) {
4352       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4353         CheckArgumentWithTypeTag(I, Args, Loc);
4354     }
4355   }
4356 
4357   if (FD)
4358     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4359 }
4360 
4361 /// CheckConstructorCall - Check a constructor call for correctness and safety
4362 /// properties not enforced by the C type system.
4363 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4364                                 ArrayRef<const Expr *> Args,
4365                                 const FunctionProtoType *Proto,
4366                                 SourceLocation Loc) {
4367   VariadicCallType CallType =
4368     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4369   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4370             Loc, SourceRange(), CallType);
4371 }
4372 
4373 /// CheckFunctionCall - Check a direct function call for various correctness
4374 /// and safety properties not strictly enforced by the C type system.
4375 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4376                              const FunctionProtoType *Proto) {
4377   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4378                               isa<CXXMethodDecl>(FDecl);
4379   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4380                           IsMemberOperatorCall;
4381   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4382                                                   TheCall->getCallee());
4383   Expr** Args = TheCall->getArgs();
4384   unsigned NumArgs = TheCall->getNumArgs();
4385 
4386   Expr *ImplicitThis = nullptr;
4387   if (IsMemberOperatorCall) {
4388     // If this is a call to a member operator, hide the first argument
4389     // from checkCall.
4390     // FIXME: Our choice of AST representation here is less than ideal.
4391     ImplicitThis = Args[0];
4392     ++Args;
4393     --NumArgs;
4394   } else if (IsMemberFunction)
4395     ImplicitThis =
4396         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4397 
4398   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4399             IsMemberFunction, TheCall->getRParenLoc(),
4400             TheCall->getCallee()->getSourceRange(), CallType);
4401 
4402   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4403   // None of the checks below are needed for functions that don't have
4404   // simple names (e.g., C++ conversion functions).
4405   if (!FnInfo)
4406     return false;
4407 
4408   CheckAbsoluteValueFunction(TheCall, FDecl);
4409   CheckMaxUnsignedZero(TheCall, FDecl);
4410 
4411   if (getLangOpts().ObjC)
4412     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4413 
4414   unsigned CMId = FDecl->getMemoryFunctionKind();
4415   if (CMId == 0)
4416     return false;
4417 
4418   // Handle memory setting and copying functions.
4419   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4420     CheckStrlcpycatArguments(TheCall, FnInfo);
4421   else if (CMId == Builtin::BIstrncat)
4422     CheckStrncatArguments(TheCall, FnInfo);
4423   else
4424     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4425 
4426   return false;
4427 }
4428 
4429 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4430                                ArrayRef<const Expr *> Args) {
4431   VariadicCallType CallType =
4432       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4433 
4434   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4435             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4436             CallType);
4437 
4438   return false;
4439 }
4440 
4441 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4442                             const FunctionProtoType *Proto) {
4443   QualType Ty;
4444   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4445     Ty = V->getType().getNonReferenceType();
4446   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4447     Ty = F->getType().getNonReferenceType();
4448   else
4449     return false;
4450 
4451   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4452       !Ty->isFunctionProtoType())
4453     return false;
4454 
4455   VariadicCallType CallType;
4456   if (!Proto || !Proto->isVariadic()) {
4457     CallType = VariadicDoesNotApply;
4458   } else if (Ty->isBlockPointerType()) {
4459     CallType = VariadicBlock;
4460   } else { // Ty->isFunctionPointerType()
4461     CallType = VariadicFunction;
4462   }
4463 
4464   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4465             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4466             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4467             TheCall->getCallee()->getSourceRange(), CallType);
4468 
4469   return false;
4470 }
4471 
4472 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4473 /// such as function pointers returned from functions.
4474 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4475   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4476                                                   TheCall->getCallee());
4477   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4478             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4479             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4480             TheCall->getCallee()->getSourceRange(), CallType);
4481 
4482   return false;
4483 }
4484 
4485 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4486   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4487     return false;
4488 
4489   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4490   switch (Op) {
4491   case AtomicExpr::AO__c11_atomic_init:
4492   case AtomicExpr::AO__opencl_atomic_init:
4493     llvm_unreachable("There is no ordering argument for an init");
4494 
4495   case AtomicExpr::AO__c11_atomic_load:
4496   case AtomicExpr::AO__opencl_atomic_load:
4497   case AtomicExpr::AO__atomic_load_n:
4498   case AtomicExpr::AO__atomic_load:
4499     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4500            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4501 
4502   case AtomicExpr::AO__c11_atomic_store:
4503   case AtomicExpr::AO__opencl_atomic_store:
4504   case AtomicExpr::AO__atomic_store:
4505   case AtomicExpr::AO__atomic_store_n:
4506     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4507            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4508            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4509 
4510   default:
4511     return true;
4512   }
4513 }
4514 
4515 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4516                                          AtomicExpr::AtomicOp Op) {
4517   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4518   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4519   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4520   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4521                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4522                          Op);
4523 }
4524 
4525 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4526                                  SourceLocation RParenLoc, MultiExprArg Args,
4527                                  AtomicExpr::AtomicOp Op,
4528                                  AtomicArgumentOrder ArgOrder) {
4529   // All the non-OpenCL operations take one of the following forms.
4530   // The OpenCL operations take the __c11 forms with one extra argument for
4531   // synchronization scope.
4532   enum {
4533     // C    __c11_atomic_init(A *, C)
4534     Init,
4535 
4536     // C    __c11_atomic_load(A *, int)
4537     Load,
4538 
4539     // void __atomic_load(A *, CP, int)
4540     LoadCopy,
4541 
4542     // void __atomic_store(A *, CP, int)
4543     Copy,
4544 
4545     // C    __c11_atomic_add(A *, M, int)
4546     Arithmetic,
4547 
4548     // C    __atomic_exchange_n(A *, CP, int)
4549     Xchg,
4550 
4551     // void __atomic_exchange(A *, C *, CP, int)
4552     GNUXchg,
4553 
4554     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4555     C11CmpXchg,
4556 
4557     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4558     GNUCmpXchg
4559   } Form = Init;
4560 
4561   const unsigned NumForm = GNUCmpXchg + 1;
4562   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4563   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4564   // where:
4565   //   C is an appropriate type,
4566   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4567   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4568   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4569   //   the int parameters are for orderings.
4570 
4571   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4572       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4573       "need to update code for modified forms");
4574   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4575                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4576                         AtomicExpr::AO__atomic_load,
4577                 "need to update code for modified C11 atomics");
4578   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4579                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4580   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4581                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4582                IsOpenCL;
4583   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4584              Op == AtomicExpr::AO__atomic_store_n ||
4585              Op == AtomicExpr::AO__atomic_exchange_n ||
4586              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4587   bool IsAddSub = false;
4588 
4589   switch (Op) {
4590   case AtomicExpr::AO__c11_atomic_init:
4591   case AtomicExpr::AO__opencl_atomic_init:
4592     Form = Init;
4593     break;
4594 
4595   case AtomicExpr::AO__c11_atomic_load:
4596   case AtomicExpr::AO__opencl_atomic_load:
4597   case AtomicExpr::AO__atomic_load_n:
4598     Form = Load;
4599     break;
4600 
4601   case AtomicExpr::AO__atomic_load:
4602     Form = LoadCopy;
4603     break;
4604 
4605   case AtomicExpr::AO__c11_atomic_store:
4606   case AtomicExpr::AO__opencl_atomic_store:
4607   case AtomicExpr::AO__atomic_store:
4608   case AtomicExpr::AO__atomic_store_n:
4609     Form = Copy;
4610     break;
4611 
4612   case AtomicExpr::AO__c11_atomic_fetch_add:
4613   case AtomicExpr::AO__c11_atomic_fetch_sub:
4614   case AtomicExpr::AO__opencl_atomic_fetch_add:
4615   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4616   case AtomicExpr::AO__opencl_atomic_fetch_min:
4617   case AtomicExpr::AO__opencl_atomic_fetch_max:
4618   case AtomicExpr::AO__atomic_fetch_add:
4619   case AtomicExpr::AO__atomic_fetch_sub:
4620   case AtomicExpr::AO__atomic_add_fetch:
4621   case AtomicExpr::AO__atomic_sub_fetch:
4622     IsAddSub = true;
4623     LLVM_FALLTHROUGH;
4624   case AtomicExpr::AO__c11_atomic_fetch_and:
4625   case AtomicExpr::AO__c11_atomic_fetch_or:
4626   case AtomicExpr::AO__c11_atomic_fetch_xor:
4627   case AtomicExpr::AO__opencl_atomic_fetch_and:
4628   case AtomicExpr::AO__opencl_atomic_fetch_or:
4629   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4630   case AtomicExpr::AO__atomic_fetch_and:
4631   case AtomicExpr::AO__atomic_fetch_or:
4632   case AtomicExpr::AO__atomic_fetch_xor:
4633   case AtomicExpr::AO__atomic_fetch_nand:
4634   case AtomicExpr::AO__atomic_and_fetch:
4635   case AtomicExpr::AO__atomic_or_fetch:
4636   case AtomicExpr::AO__atomic_xor_fetch:
4637   case AtomicExpr::AO__atomic_nand_fetch:
4638   case AtomicExpr::AO__c11_atomic_fetch_min:
4639   case AtomicExpr::AO__c11_atomic_fetch_max:
4640   case AtomicExpr::AO__atomic_min_fetch:
4641   case AtomicExpr::AO__atomic_max_fetch:
4642   case AtomicExpr::AO__atomic_fetch_min:
4643   case AtomicExpr::AO__atomic_fetch_max:
4644     Form = Arithmetic;
4645     break;
4646 
4647   case AtomicExpr::AO__c11_atomic_exchange:
4648   case AtomicExpr::AO__opencl_atomic_exchange:
4649   case AtomicExpr::AO__atomic_exchange_n:
4650     Form = Xchg;
4651     break;
4652 
4653   case AtomicExpr::AO__atomic_exchange:
4654     Form = GNUXchg;
4655     break;
4656 
4657   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4658   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4659   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4660   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4661     Form = C11CmpXchg;
4662     break;
4663 
4664   case AtomicExpr::AO__atomic_compare_exchange:
4665   case AtomicExpr::AO__atomic_compare_exchange_n:
4666     Form = GNUCmpXchg;
4667     break;
4668   }
4669 
4670   unsigned AdjustedNumArgs = NumArgs[Form];
4671   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4672     ++AdjustedNumArgs;
4673   // Check we have the right number of arguments.
4674   if (Args.size() < AdjustedNumArgs) {
4675     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4676         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4677         << ExprRange;
4678     return ExprError();
4679   } else if (Args.size() > AdjustedNumArgs) {
4680     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4681          diag::err_typecheck_call_too_many_args)
4682         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4683         << ExprRange;
4684     return ExprError();
4685   }
4686 
4687   // Inspect the first argument of the atomic operation.
4688   Expr *Ptr = Args[0];
4689   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4690   if (ConvertedPtr.isInvalid())
4691     return ExprError();
4692 
4693   Ptr = ConvertedPtr.get();
4694   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4695   if (!pointerType) {
4696     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4697         << Ptr->getType() << Ptr->getSourceRange();
4698     return ExprError();
4699   }
4700 
4701   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4702   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4703   QualType ValType = AtomTy; // 'C'
4704   if (IsC11) {
4705     if (!AtomTy->isAtomicType()) {
4706       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4707           << Ptr->getType() << Ptr->getSourceRange();
4708       return ExprError();
4709     }
4710     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4711         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4712       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4713           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4714           << Ptr->getSourceRange();
4715       return ExprError();
4716     }
4717     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4718   } else if (Form != Load && Form != LoadCopy) {
4719     if (ValType.isConstQualified()) {
4720       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4721           << Ptr->getType() << Ptr->getSourceRange();
4722       return ExprError();
4723     }
4724   }
4725 
4726   // For an arithmetic operation, the implied arithmetic must be well-formed.
4727   if (Form == Arithmetic) {
4728     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4729     if (IsAddSub && !ValType->isIntegerType()
4730         && !ValType->isPointerType()) {
4731       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4732           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4733       return ExprError();
4734     }
4735     if (!IsAddSub && !ValType->isIntegerType()) {
4736       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4737           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4738       return ExprError();
4739     }
4740     if (IsC11 && ValType->isPointerType() &&
4741         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4742                             diag::err_incomplete_type)) {
4743       return ExprError();
4744     }
4745   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4746     // For __atomic_*_n operations, the value type must be a scalar integral or
4747     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4748     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4749         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4750     return ExprError();
4751   }
4752 
4753   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4754       !AtomTy->isScalarType()) {
4755     // For GNU atomics, require a trivially-copyable type. This is not part of
4756     // the GNU atomics specification, but we enforce it for sanity.
4757     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4758         << Ptr->getType() << Ptr->getSourceRange();
4759     return ExprError();
4760   }
4761 
4762   switch (ValType.getObjCLifetime()) {
4763   case Qualifiers::OCL_None:
4764   case Qualifiers::OCL_ExplicitNone:
4765     // okay
4766     break;
4767 
4768   case Qualifiers::OCL_Weak:
4769   case Qualifiers::OCL_Strong:
4770   case Qualifiers::OCL_Autoreleasing:
4771     // FIXME: Can this happen? By this point, ValType should be known
4772     // to be trivially copyable.
4773     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4774         << ValType << Ptr->getSourceRange();
4775     return ExprError();
4776   }
4777 
4778   // All atomic operations have an overload which takes a pointer to a volatile
4779   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4780   // into the result or the other operands. Similarly atomic_load takes a
4781   // pointer to a const 'A'.
4782   ValType.removeLocalVolatile();
4783   ValType.removeLocalConst();
4784   QualType ResultType = ValType;
4785   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4786       Form == Init)
4787     ResultType = Context.VoidTy;
4788   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4789     ResultType = Context.BoolTy;
4790 
4791   // The type of a parameter passed 'by value'. In the GNU atomics, such
4792   // arguments are actually passed as pointers.
4793   QualType ByValType = ValType; // 'CP'
4794   bool IsPassedByAddress = false;
4795   if (!IsC11 && !IsN) {
4796     ByValType = Ptr->getType();
4797     IsPassedByAddress = true;
4798   }
4799 
4800   SmallVector<Expr *, 5> APIOrderedArgs;
4801   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4802     APIOrderedArgs.push_back(Args[0]);
4803     switch (Form) {
4804     case Init:
4805     case Load:
4806       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4807       break;
4808     case LoadCopy:
4809     case Copy:
4810     case Arithmetic:
4811     case Xchg:
4812       APIOrderedArgs.push_back(Args[2]); // Val1
4813       APIOrderedArgs.push_back(Args[1]); // Order
4814       break;
4815     case GNUXchg:
4816       APIOrderedArgs.push_back(Args[2]); // Val1
4817       APIOrderedArgs.push_back(Args[3]); // Val2
4818       APIOrderedArgs.push_back(Args[1]); // Order
4819       break;
4820     case C11CmpXchg:
4821       APIOrderedArgs.push_back(Args[2]); // Val1
4822       APIOrderedArgs.push_back(Args[4]); // Val2
4823       APIOrderedArgs.push_back(Args[1]); // Order
4824       APIOrderedArgs.push_back(Args[3]); // OrderFail
4825       break;
4826     case GNUCmpXchg:
4827       APIOrderedArgs.push_back(Args[2]); // Val1
4828       APIOrderedArgs.push_back(Args[4]); // Val2
4829       APIOrderedArgs.push_back(Args[5]); // Weak
4830       APIOrderedArgs.push_back(Args[1]); // Order
4831       APIOrderedArgs.push_back(Args[3]); // OrderFail
4832       break;
4833     }
4834   } else
4835     APIOrderedArgs.append(Args.begin(), Args.end());
4836 
4837   // The first argument's non-CV pointer type is used to deduce the type of
4838   // subsequent arguments, except for:
4839   //  - weak flag (always converted to bool)
4840   //  - memory order (always converted to int)
4841   //  - scope  (always converted to int)
4842   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4843     QualType Ty;
4844     if (i < NumVals[Form] + 1) {
4845       switch (i) {
4846       case 0:
4847         // The first argument is always a pointer. It has a fixed type.
4848         // It is always dereferenced, a nullptr is undefined.
4849         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4850         // Nothing else to do: we already know all we want about this pointer.
4851         continue;
4852       case 1:
4853         // The second argument is the non-atomic operand. For arithmetic, this
4854         // is always passed by value, and for a compare_exchange it is always
4855         // passed by address. For the rest, GNU uses by-address and C11 uses
4856         // by-value.
4857         assert(Form != Load);
4858         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4859           Ty = ValType;
4860         else if (Form == Copy || Form == Xchg) {
4861           if (IsPassedByAddress) {
4862             // The value pointer is always dereferenced, a nullptr is undefined.
4863             CheckNonNullArgument(*this, APIOrderedArgs[i],
4864                                  ExprRange.getBegin());
4865           }
4866           Ty = ByValType;
4867         } else if (Form == Arithmetic)
4868           Ty = Context.getPointerDiffType();
4869         else {
4870           Expr *ValArg = APIOrderedArgs[i];
4871           // The value pointer is always dereferenced, a nullptr is undefined.
4872           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4873           LangAS AS = LangAS::Default;
4874           // Keep address space of non-atomic pointer type.
4875           if (const PointerType *PtrTy =
4876                   ValArg->getType()->getAs<PointerType>()) {
4877             AS = PtrTy->getPointeeType().getAddressSpace();
4878           }
4879           Ty = Context.getPointerType(
4880               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4881         }
4882         break;
4883       case 2:
4884         // The third argument to compare_exchange / GNU exchange is the desired
4885         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4886         if (IsPassedByAddress)
4887           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4888         Ty = ByValType;
4889         break;
4890       case 3:
4891         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4892         Ty = Context.BoolTy;
4893         break;
4894       }
4895     } else {
4896       // The order(s) and scope are always converted to int.
4897       Ty = Context.IntTy;
4898     }
4899 
4900     InitializedEntity Entity =
4901         InitializedEntity::InitializeParameter(Context, Ty, false);
4902     ExprResult Arg = APIOrderedArgs[i];
4903     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4904     if (Arg.isInvalid())
4905       return true;
4906     APIOrderedArgs[i] = Arg.get();
4907   }
4908 
4909   // Permute the arguments into a 'consistent' order.
4910   SmallVector<Expr*, 5> SubExprs;
4911   SubExprs.push_back(Ptr);
4912   switch (Form) {
4913   case Init:
4914     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4915     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4916     break;
4917   case Load:
4918     SubExprs.push_back(APIOrderedArgs[1]); // Order
4919     break;
4920   case LoadCopy:
4921   case Copy:
4922   case Arithmetic:
4923   case Xchg:
4924     SubExprs.push_back(APIOrderedArgs[2]); // Order
4925     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4926     break;
4927   case GNUXchg:
4928     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4929     SubExprs.push_back(APIOrderedArgs[3]); // Order
4930     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4931     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4932     break;
4933   case C11CmpXchg:
4934     SubExprs.push_back(APIOrderedArgs[3]); // Order
4935     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4936     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4937     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4938     break;
4939   case GNUCmpXchg:
4940     SubExprs.push_back(APIOrderedArgs[4]); // Order
4941     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4942     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4943     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4944     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4945     break;
4946   }
4947 
4948   if (SubExprs.size() >= 2 && Form != Init) {
4949     llvm::APSInt Result(32);
4950     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4951         !isValidOrderingForOp(Result.getSExtValue(), Op))
4952       Diag(SubExprs[1]->getBeginLoc(),
4953            diag::warn_atomic_op_has_invalid_memory_order)
4954           << SubExprs[1]->getSourceRange();
4955   }
4956 
4957   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4958     auto *Scope = Args[Args.size() - 1];
4959     llvm::APSInt Result(32);
4960     if (Scope->isIntegerConstantExpr(Result, Context) &&
4961         !ScopeModel->isValid(Result.getZExtValue())) {
4962       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4963           << Scope->getSourceRange();
4964     }
4965     SubExprs.push_back(Scope);
4966   }
4967 
4968   AtomicExpr *AE = new (Context)
4969       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4970 
4971   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4972        Op == AtomicExpr::AO__c11_atomic_store ||
4973        Op == AtomicExpr::AO__opencl_atomic_load ||
4974        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4975       Context.AtomicUsesUnsupportedLibcall(AE))
4976     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4977         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4978              Op == AtomicExpr::AO__opencl_atomic_load)
4979                 ? 0
4980                 : 1);
4981 
4982   return AE;
4983 }
4984 
4985 /// checkBuiltinArgument - Given a call to a builtin function, perform
4986 /// normal type-checking on the given argument, updating the call in
4987 /// place.  This is useful when a builtin function requires custom
4988 /// type-checking for some of its arguments but not necessarily all of
4989 /// them.
4990 ///
4991 /// Returns true on error.
4992 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4993   FunctionDecl *Fn = E->getDirectCallee();
4994   assert(Fn && "builtin call without direct callee!");
4995 
4996   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4997   InitializedEntity Entity =
4998     InitializedEntity::InitializeParameter(S.Context, Param);
4999 
5000   ExprResult Arg = E->getArg(0);
5001   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5002   if (Arg.isInvalid())
5003     return true;
5004 
5005   E->setArg(ArgIndex, Arg.get());
5006   return false;
5007 }
5008 
5009 /// We have a call to a function like __sync_fetch_and_add, which is an
5010 /// overloaded function based on the pointer type of its first argument.
5011 /// The main BuildCallExpr routines have already promoted the types of
5012 /// arguments because all of these calls are prototyped as void(...).
5013 ///
5014 /// This function goes through and does final semantic checking for these
5015 /// builtins, as well as generating any warnings.
5016 ExprResult
5017 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5018   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5019   Expr *Callee = TheCall->getCallee();
5020   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5021   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5022 
5023   // Ensure that we have at least one argument to do type inference from.
5024   if (TheCall->getNumArgs() < 1) {
5025     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5026         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5027     return ExprError();
5028   }
5029 
5030   // Inspect the first argument of the atomic builtin.  This should always be
5031   // a pointer type, whose element is an integral scalar or pointer type.
5032   // Because it is a pointer type, we don't have to worry about any implicit
5033   // casts here.
5034   // FIXME: We don't allow floating point scalars as input.
5035   Expr *FirstArg = TheCall->getArg(0);
5036   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5037   if (FirstArgResult.isInvalid())
5038     return ExprError();
5039   FirstArg = FirstArgResult.get();
5040   TheCall->setArg(0, FirstArg);
5041 
5042   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5043   if (!pointerType) {
5044     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5045         << FirstArg->getType() << FirstArg->getSourceRange();
5046     return ExprError();
5047   }
5048 
5049   QualType ValType = pointerType->getPointeeType();
5050   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5051       !ValType->isBlockPointerType()) {
5052     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5053         << FirstArg->getType() << FirstArg->getSourceRange();
5054     return ExprError();
5055   }
5056 
5057   if (ValType.isConstQualified()) {
5058     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5059         << FirstArg->getType() << FirstArg->getSourceRange();
5060     return ExprError();
5061   }
5062 
5063   switch (ValType.getObjCLifetime()) {
5064   case Qualifiers::OCL_None:
5065   case Qualifiers::OCL_ExplicitNone:
5066     // okay
5067     break;
5068 
5069   case Qualifiers::OCL_Weak:
5070   case Qualifiers::OCL_Strong:
5071   case Qualifiers::OCL_Autoreleasing:
5072     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5073         << ValType << FirstArg->getSourceRange();
5074     return ExprError();
5075   }
5076 
5077   // Strip any qualifiers off ValType.
5078   ValType = ValType.getUnqualifiedType();
5079 
5080   // The majority of builtins return a value, but a few have special return
5081   // types, so allow them to override appropriately below.
5082   QualType ResultType = ValType;
5083 
5084   // We need to figure out which concrete builtin this maps onto.  For example,
5085   // __sync_fetch_and_add with a 2 byte object turns into
5086   // __sync_fetch_and_add_2.
5087 #define BUILTIN_ROW(x) \
5088   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5089     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5090 
5091   static const unsigned BuiltinIndices[][5] = {
5092     BUILTIN_ROW(__sync_fetch_and_add),
5093     BUILTIN_ROW(__sync_fetch_and_sub),
5094     BUILTIN_ROW(__sync_fetch_and_or),
5095     BUILTIN_ROW(__sync_fetch_and_and),
5096     BUILTIN_ROW(__sync_fetch_and_xor),
5097     BUILTIN_ROW(__sync_fetch_and_nand),
5098 
5099     BUILTIN_ROW(__sync_add_and_fetch),
5100     BUILTIN_ROW(__sync_sub_and_fetch),
5101     BUILTIN_ROW(__sync_and_and_fetch),
5102     BUILTIN_ROW(__sync_or_and_fetch),
5103     BUILTIN_ROW(__sync_xor_and_fetch),
5104     BUILTIN_ROW(__sync_nand_and_fetch),
5105 
5106     BUILTIN_ROW(__sync_val_compare_and_swap),
5107     BUILTIN_ROW(__sync_bool_compare_and_swap),
5108     BUILTIN_ROW(__sync_lock_test_and_set),
5109     BUILTIN_ROW(__sync_lock_release),
5110     BUILTIN_ROW(__sync_swap)
5111   };
5112 #undef BUILTIN_ROW
5113 
5114   // Determine the index of the size.
5115   unsigned SizeIndex;
5116   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5117   case 1: SizeIndex = 0; break;
5118   case 2: SizeIndex = 1; break;
5119   case 4: SizeIndex = 2; break;
5120   case 8: SizeIndex = 3; break;
5121   case 16: SizeIndex = 4; break;
5122   default:
5123     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5124         << FirstArg->getType() << FirstArg->getSourceRange();
5125     return ExprError();
5126   }
5127 
5128   // Each of these builtins has one pointer argument, followed by some number of
5129   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5130   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5131   // as the number of fixed args.
5132   unsigned BuiltinID = FDecl->getBuiltinID();
5133   unsigned BuiltinIndex, NumFixed = 1;
5134   bool WarnAboutSemanticsChange = false;
5135   switch (BuiltinID) {
5136   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5137   case Builtin::BI__sync_fetch_and_add:
5138   case Builtin::BI__sync_fetch_and_add_1:
5139   case Builtin::BI__sync_fetch_and_add_2:
5140   case Builtin::BI__sync_fetch_and_add_4:
5141   case Builtin::BI__sync_fetch_and_add_8:
5142   case Builtin::BI__sync_fetch_and_add_16:
5143     BuiltinIndex = 0;
5144     break;
5145 
5146   case Builtin::BI__sync_fetch_and_sub:
5147   case Builtin::BI__sync_fetch_and_sub_1:
5148   case Builtin::BI__sync_fetch_and_sub_2:
5149   case Builtin::BI__sync_fetch_and_sub_4:
5150   case Builtin::BI__sync_fetch_and_sub_8:
5151   case Builtin::BI__sync_fetch_and_sub_16:
5152     BuiltinIndex = 1;
5153     break;
5154 
5155   case Builtin::BI__sync_fetch_and_or:
5156   case Builtin::BI__sync_fetch_and_or_1:
5157   case Builtin::BI__sync_fetch_and_or_2:
5158   case Builtin::BI__sync_fetch_and_or_4:
5159   case Builtin::BI__sync_fetch_and_or_8:
5160   case Builtin::BI__sync_fetch_and_or_16:
5161     BuiltinIndex = 2;
5162     break;
5163 
5164   case Builtin::BI__sync_fetch_and_and:
5165   case Builtin::BI__sync_fetch_and_and_1:
5166   case Builtin::BI__sync_fetch_and_and_2:
5167   case Builtin::BI__sync_fetch_and_and_4:
5168   case Builtin::BI__sync_fetch_and_and_8:
5169   case Builtin::BI__sync_fetch_and_and_16:
5170     BuiltinIndex = 3;
5171     break;
5172 
5173   case Builtin::BI__sync_fetch_and_xor:
5174   case Builtin::BI__sync_fetch_and_xor_1:
5175   case Builtin::BI__sync_fetch_and_xor_2:
5176   case Builtin::BI__sync_fetch_and_xor_4:
5177   case Builtin::BI__sync_fetch_and_xor_8:
5178   case Builtin::BI__sync_fetch_and_xor_16:
5179     BuiltinIndex = 4;
5180     break;
5181 
5182   case Builtin::BI__sync_fetch_and_nand:
5183   case Builtin::BI__sync_fetch_and_nand_1:
5184   case Builtin::BI__sync_fetch_and_nand_2:
5185   case Builtin::BI__sync_fetch_and_nand_4:
5186   case Builtin::BI__sync_fetch_and_nand_8:
5187   case Builtin::BI__sync_fetch_and_nand_16:
5188     BuiltinIndex = 5;
5189     WarnAboutSemanticsChange = true;
5190     break;
5191 
5192   case Builtin::BI__sync_add_and_fetch:
5193   case Builtin::BI__sync_add_and_fetch_1:
5194   case Builtin::BI__sync_add_and_fetch_2:
5195   case Builtin::BI__sync_add_and_fetch_4:
5196   case Builtin::BI__sync_add_and_fetch_8:
5197   case Builtin::BI__sync_add_and_fetch_16:
5198     BuiltinIndex = 6;
5199     break;
5200 
5201   case Builtin::BI__sync_sub_and_fetch:
5202   case Builtin::BI__sync_sub_and_fetch_1:
5203   case Builtin::BI__sync_sub_and_fetch_2:
5204   case Builtin::BI__sync_sub_and_fetch_4:
5205   case Builtin::BI__sync_sub_and_fetch_8:
5206   case Builtin::BI__sync_sub_and_fetch_16:
5207     BuiltinIndex = 7;
5208     break;
5209 
5210   case Builtin::BI__sync_and_and_fetch:
5211   case Builtin::BI__sync_and_and_fetch_1:
5212   case Builtin::BI__sync_and_and_fetch_2:
5213   case Builtin::BI__sync_and_and_fetch_4:
5214   case Builtin::BI__sync_and_and_fetch_8:
5215   case Builtin::BI__sync_and_and_fetch_16:
5216     BuiltinIndex = 8;
5217     break;
5218 
5219   case Builtin::BI__sync_or_and_fetch:
5220   case Builtin::BI__sync_or_and_fetch_1:
5221   case Builtin::BI__sync_or_and_fetch_2:
5222   case Builtin::BI__sync_or_and_fetch_4:
5223   case Builtin::BI__sync_or_and_fetch_8:
5224   case Builtin::BI__sync_or_and_fetch_16:
5225     BuiltinIndex = 9;
5226     break;
5227 
5228   case Builtin::BI__sync_xor_and_fetch:
5229   case Builtin::BI__sync_xor_and_fetch_1:
5230   case Builtin::BI__sync_xor_and_fetch_2:
5231   case Builtin::BI__sync_xor_and_fetch_4:
5232   case Builtin::BI__sync_xor_and_fetch_8:
5233   case Builtin::BI__sync_xor_and_fetch_16:
5234     BuiltinIndex = 10;
5235     break;
5236 
5237   case Builtin::BI__sync_nand_and_fetch:
5238   case Builtin::BI__sync_nand_and_fetch_1:
5239   case Builtin::BI__sync_nand_and_fetch_2:
5240   case Builtin::BI__sync_nand_and_fetch_4:
5241   case Builtin::BI__sync_nand_and_fetch_8:
5242   case Builtin::BI__sync_nand_and_fetch_16:
5243     BuiltinIndex = 11;
5244     WarnAboutSemanticsChange = true;
5245     break;
5246 
5247   case Builtin::BI__sync_val_compare_and_swap:
5248   case Builtin::BI__sync_val_compare_and_swap_1:
5249   case Builtin::BI__sync_val_compare_and_swap_2:
5250   case Builtin::BI__sync_val_compare_and_swap_4:
5251   case Builtin::BI__sync_val_compare_and_swap_8:
5252   case Builtin::BI__sync_val_compare_and_swap_16:
5253     BuiltinIndex = 12;
5254     NumFixed = 2;
5255     break;
5256 
5257   case Builtin::BI__sync_bool_compare_and_swap:
5258   case Builtin::BI__sync_bool_compare_and_swap_1:
5259   case Builtin::BI__sync_bool_compare_and_swap_2:
5260   case Builtin::BI__sync_bool_compare_and_swap_4:
5261   case Builtin::BI__sync_bool_compare_and_swap_8:
5262   case Builtin::BI__sync_bool_compare_and_swap_16:
5263     BuiltinIndex = 13;
5264     NumFixed = 2;
5265     ResultType = Context.BoolTy;
5266     break;
5267 
5268   case Builtin::BI__sync_lock_test_and_set:
5269   case Builtin::BI__sync_lock_test_and_set_1:
5270   case Builtin::BI__sync_lock_test_and_set_2:
5271   case Builtin::BI__sync_lock_test_and_set_4:
5272   case Builtin::BI__sync_lock_test_and_set_8:
5273   case Builtin::BI__sync_lock_test_and_set_16:
5274     BuiltinIndex = 14;
5275     break;
5276 
5277   case Builtin::BI__sync_lock_release:
5278   case Builtin::BI__sync_lock_release_1:
5279   case Builtin::BI__sync_lock_release_2:
5280   case Builtin::BI__sync_lock_release_4:
5281   case Builtin::BI__sync_lock_release_8:
5282   case Builtin::BI__sync_lock_release_16:
5283     BuiltinIndex = 15;
5284     NumFixed = 0;
5285     ResultType = Context.VoidTy;
5286     break;
5287 
5288   case Builtin::BI__sync_swap:
5289   case Builtin::BI__sync_swap_1:
5290   case Builtin::BI__sync_swap_2:
5291   case Builtin::BI__sync_swap_4:
5292   case Builtin::BI__sync_swap_8:
5293   case Builtin::BI__sync_swap_16:
5294     BuiltinIndex = 16;
5295     break;
5296   }
5297 
5298   // Now that we know how many fixed arguments we expect, first check that we
5299   // have at least that many.
5300   if (TheCall->getNumArgs() < 1+NumFixed) {
5301     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5302         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5303         << Callee->getSourceRange();
5304     return ExprError();
5305   }
5306 
5307   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5308       << Callee->getSourceRange();
5309 
5310   if (WarnAboutSemanticsChange) {
5311     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5312         << Callee->getSourceRange();
5313   }
5314 
5315   // Get the decl for the concrete builtin from this, we can tell what the
5316   // concrete integer type we should convert to is.
5317   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5318   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5319   FunctionDecl *NewBuiltinDecl;
5320   if (NewBuiltinID == BuiltinID)
5321     NewBuiltinDecl = FDecl;
5322   else {
5323     // Perform builtin lookup to avoid redeclaring it.
5324     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5325     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5326     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5327     assert(Res.getFoundDecl());
5328     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5329     if (!NewBuiltinDecl)
5330       return ExprError();
5331   }
5332 
5333   // The first argument --- the pointer --- has a fixed type; we
5334   // deduce the types of the rest of the arguments accordingly.  Walk
5335   // the remaining arguments, converting them to the deduced value type.
5336   for (unsigned i = 0; i != NumFixed; ++i) {
5337     ExprResult Arg = TheCall->getArg(i+1);
5338 
5339     // GCC does an implicit conversion to the pointer or integer ValType.  This
5340     // can fail in some cases (1i -> int**), check for this error case now.
5341     // Initialize the argument.
5342     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5343                                                    ValType, /*consume*/ false);
5344     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5345     if (Arg.isInvalid())
5346       return ExprError();
5347 
5348     // Okay, we have something that *can* be converted to the right type.  Check
5349     // to see if there is a potentially weird extension going on here.  This can
5350     // happen when you do an atomic operation on something like an char* and
5351     // pass in 42.  The 42 gets converted to char.  This is even more strange
5352     // for things like 45.123 -> char, etc.
5353     // FIXME: Do this check.
5354     TheCall->setArg(i+1, Arg.get());
5355   }
5356 
5357   // Create a new DeclRefExpr to refer to the new decl.
5358   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5359       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5360       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5361       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5362 
5363   // Set the callee in the CallExpr.
5364   // FIXME: This loses syntactic information.
5365   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5366   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5367                                               CK_BuiltinFnToFnPtr);
5368   TheCall->setCallee(PromotedCall.get());
5369 
5370   // Change the result type of the call to match the original value type. This
5371   // is arbitrary, but the codegen for these builtins ins design to handle it
5372   // gracefully.
5373   TheCall->setType(ResultType);
5374 
5375   return TheCallResult;
5376 }
5377 
5378 /// SemaBuiltinNontemporalOverloaded - We have a call to
5379 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5380 /// overloaded function based on the pointer type of its last argument.
5381 ///
5382 /// This function goes through and does final semantic checking for these
5383 /// builtins.
5384 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5385   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5386   DeclRefExpr *DRE =
5387       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5388   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5389   unsigned BuiltinID = FDecl->getBuiltinID();
5390   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5391           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5392          "Unexpected nontemporal load/store builtin!");
5393   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5394   unsigned numArgs = isStore ? 2 : 1;
5395 
5396   // Ensure that we have the proper number of arguments.
5397   if (checkArgCount(*this, TheCall, numArgs))
5398     return ExprError();
5399 
5400   // Inspect the last argument of the nontemporal builtin.  This should always
5401   // be a pointer type, from which we imply the type of the memory access.
5402   // Because it is a pointer type, we don't have to worry about any implicit
5403   // casts here.
5404   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5405   ExprResult PointerArgResult =
5406       DefaultFunctionArrayLvalueConversion(PointerArg);
5407 
5408   if (PointerArgResult.isInvalid())
5409     return ExprError();
5410   PointerArg = PointerArgResult.get();
5411   TheCall->setArg(numArgs - 1, PointerArg);
5412 
5413   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5414   if (!pointerType) {
5415     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5416         << PointerArg->getType() << PointerArg->getSourceRange();
5417     return ExprError();
5418   }
5419 
5420   QualType ValType = pointerType->getPointeeType();
5421 
5422   // Strip any qualifiers off ValType.
5423   ValType = ValType.getUnqualifiedType();
5424   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5425       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5426       !ValType->isVectorType()) {
5427     Diag(DRE->getBeginLoc(),
5428          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5429         << PointerArg->getType() << PointerArg->getSourceRange();
5430     return ExprError();
5431   }
5432 
5433   if (!isStore) {
5434     TheCall->setType(ValType);
5435     return TheCallResult;
5436   }
5437 
5438   ExprResult ValArg = TheCall->getArg(0);
5439   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5440       Context, ValType, /*consume*/ false);
5441   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5442   if (ValArg.isInvalid())
5443     return ExprError();
5444 
5445   TheCall->setArg(0, ValArg.get());
5446   TheCall->setType(Context.VoidTy);
5447   return TheCallResult;
5448 }
5449 
5450 /// CheckObjCString - Checks that the argument to the builtin
5451 /// CFString constructor is correct
5452 /// Note: It might also make sense to do the UTF-16 conversion here (would
5453 /// simplify the backend).
5454 bool Sema::CheckObjCString(Expr *Arg) {
5455   Arg = Arg->IgnoreParenCasts();
5456   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5457 
5458   if (!Literal || !Literal->isAscii()) {
5459     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5460         << Arg->getSourceRange();
5461     return true;
5462   }
5463 
5464   if (Literal->containsNonAsciiOrNull()) {
5465     StringRef String = Literal->getString();
5466     unsigned NumBytes = String.size();
5467     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5468     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5469     llvm::UTF16 *ToPtr = &ToBuf[0];
5470 
5471     llvm::ConversionResult Result =
5472         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5473                                  ToPtr + NumBytes, llvm::strictConversion);
5474     // Check for conversion failure.
5475     if (Result != llvm::conversionOK)
5476       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5477           << Arg->getSourceRange();
5478   }
5479   return false;
5480 }
5481 
5482 /// CheckObjCString - Checks that the format string argument to the os_log()
5483 /// and os_trace() functions is correct, and converts it to const char *.
5484 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5485   Arg = Arg->IgnoreParenCasts();
5486   auto *Literal = dyn_cast<StringLiteral>(Arg);
5487   if (!Literal) {
5488     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5489       Literal = ObjcLiteral->getString();
5490     }
5491   }
5492 
5493   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5494     return ExprError(
5495         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5496         << Arg->getSourceRange());
5497   }
5498 
5499   ExprResult Result(Literal);
5500   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5501   InitializedEntity Entity =
5502       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5503   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5504   return Result;
5505 }
5506 
5507 /// Check that the user is calling the appropriate va_start builtin for the
5508 /// target and calling convention.
5509 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5510   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5511   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5512   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5513                     TT.getArch() == llvm::Triple::aarch64_32);
5514   bool IsWindows = TT.isOSWindows();
5515   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5516   if (IsX64 || IsAArch64) {
5517     CallingConv CC = CC_C;
5518     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5519       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5520     if (IsMSVAStart) {
5521       // Don't allow this in System V ABI functions.
5522       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5523         return S.Diag(Fn->getBeginLoc(),
5524                       diag::err_ms_va_start_used_in_sysv_function);
5525     } else {
5526       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5527       // On x64 Windows, don't allow this in System V ABI functions.
5528       // (Yes, that means there's no corresponding way to support variadic
5529       // System V ABI functions on Windows.)
5530       if ((IsWindows && CC == CC_X86_64SysV) ||
5531           (!IsWindows && CC == CC_Win64))
5532         return S.Diag(Fn->getBeginLoc(),
5533                       diag::err_va_start_used_in_wrong_abi_function)
5534                << !IsWindows;
5535     }
5536     return false;
5537   }
5538 
5539   if (IsMSVAStart)
5540     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5541   return false;
5542 }
5543 
5544 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5545                                              ParmVarDecl **LastParam = nullptr) {
5546   // Determine whether the current function, block, or obj-c method is variadic
5547   // and get its parameter list.
5548   bool IsVariadic = false;
5549   ArrayRef<ParmVarDecl *> Params;
5550   DeclContext *Caller = S.CurContext;
5551   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5552     IsVariadic = Block->isVariadic();
5553     Params = Block->parameters();
5554   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5555     IsVariadic = FD->isVariadic();
5556     Params = FD->parameters();
5557   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5558     IsVariadic = MD->isVariadic();
5559     // FIXME: This isn't correct for methods (results in bogus warning).
5560     Params = MD->parameters();
5561   } else if (isa<CapturedDecl>(Caller)) {
5562     // We don't support va_start in a CapturedDecl.
5563     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5564     return true;
5565   } else {
5566     // This must be some other declcontext that parses exprs.
5567     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5568     return true;
5569   }
5570 
5571   if (!IsVariadic) {
5572     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5573     return true;
5574   }
5575 
5576   if (LastParam)
5577     *LastParam = Params.empty() ? nullptr : Params.back();
5578 
5579   return false;
5580 }
5581 
5582 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5583 /// for validity.  Emit an error and return true on failure; return false
5584 /// on success.
5585 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5586   Expr *Fn = TheCall->getCallee();
5587 
5588   if (checkVAStartABI(*this, BuiltinID, Fn))
5589     return true;
5590 
5591   if (TheCall->getNumArgs() > 2) {
5592     Diag(TheCall->getArg(2)->getBeginLoc(),
5593          diag::err_typecheck_call_too_many_args)
5594         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5595         << Fn->getSourceRange()
5596         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5597                        (*(TheCall->arg_end() - 1))->getEndLoc());
5598     return true;
5599   }
5600 
5601   if (TheCall->getNumArgs() < 2) {
5602     return Diag(TheCall->getEndLoc(),
5603                 diag::err_typecheck_call_too_few_args_at_least)
5604            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5605   }
5606 
5607   // Type-check the first argument normally.
5608   if (checkBuiltinArgument(*this, TheCall, 0))
5609     return true;
5610 
5611   // Check that the current function is variadic, and get its last parameter.
5612   ParmVarDecl *LastParam;
5613   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5614     return true;
5615 
5616   // Verify that the second argument to the builtin is the last argument of the
5617   // current function or method.
5618   bool SecondArgIsLastNamedArgument = false;
5619   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5620 
5621   // These are valid if SecondArgIsLastNamedArgument is false after the next
5622   // block.
5623   QualType Type;
5624   SourceLocation ParamLoc;
5625   bool IsCRegister = false;
5626 
5627   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5628     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5629       SecondArgIsLastNamedArgument = PV == LastParam;
5630 
5631       Type = PV->getType();
5632       ParamLoc = PV->getLocation();
5633       IsCRegister =
5634           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5635     }
5636   }
5637 
5638   if (!SecondArgIsLastNamedArgument)
5639     Diag(TheCall->getArg(1)->getBeginLoc(),
5640          diag::warn_second_arg_of_va_start_not_last_named_param);
5641   else if (IsCRegister || Type->isReferenceType() ||
5642            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5643              // Promotable integers are UB, but enumerations need a bit of
5644              // extra checking to see what their promotable type actually is.
5645              if (!Type->isPromotableIntegerType())
5646                return false;
5647              if (!Type->isEnumeralType())
5648                return true;
5649              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5650              return !(ED &&
5651                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5652            }()) {
5653     unsigned Reason = 0;
5654     if (Type->isReferenceType())  Reason = 1;
5655     else if (IsCRegister)         Reason = 2;
5656     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5657     Diag(ParamLoc, diag::note_parameter_type) << Type;
5658   }
5659 
5660   TheCall->setType(Context.VoidTy);
5661   return false;
5662 }
5663 
5664 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5665   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5666   //                 const char *named_addr);
5667 
5668   Expr *Func = Call->getCallee();
5669 
5670   if (Call->getNumArgs() < 3)
5671     return Diag(Call->getEndLoc(),
5672                 diag::err_typecheck_call_too_few_args_at_least)
5673            << 0 /*function call*/ << 3 << Call->getNumArgs();
5674 
5675   // Type-check the first argument normally.
5676   if (checkBuiltinArgument(*this, Call, 0))
5677     return true;
5678 
5679   // Check that the current function is variadic.
5680   if (checkVAStartIsInVariadicFunction(*this, Func))
5681     return true;
5682 
5683   // __va_start on Windows does not validate the parameter qualifiers
5684 
5685   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5686   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5687 
5688   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5689   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5690 
5691   const QualType &ConstCharPtrTy =
5692       Context.getPointerType(Context.CharTy.withConst());
5693   if (!Arg1Ty->isPointerType() ||
5694       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5695     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5696         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5697         << 0                                      /* qualifier difference */
5698         << 3                                      /* parameter mismatch */
5699         << 2 << Arg1->getType() << ConstCharPtrTy;
5700 
5701   const QualType SizeTy = Context.getSizeType();
5702   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5703     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5704         << Arg2->getType() << SizeTy << 1 /* different class */
5705         << 0                              /* qualifier difference */
5706         << 3                              /* parameter mismatch */
5707         << 3 << Arg2->getType() << SizeTy;
5708 
5709   return false;
5710 }
5711 
5712 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5713 /// friends.  This is declared to take (...), so we have to check everything.
5714 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5715   if (TheCall->getNumArgs() < 2)
5716     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5717            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5718   if (TheCall->getNumArgs() > 2)
5719     return Diag(TheCall->getArg(2)->getBeginLoc(),
5720                 diag::err_typecheck_call_too_many_args)
5721            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5722            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5723                           (*(TheCall->arg_end() - 1))->getEndLoc());
5724 
5725   ExprResult OrigArg0 = TheCall->getArg(0);
5726   ExprResult OrigArg1 = TheCall->getArg(1);
5727 
5728   // Do standard promotions between the two arguments, returning their common
5729   // type.
5730   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5731   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5732     return true;
5733 
5734   // Make sure any conversions are pushed back into the call; this is
5735   // type safe since unordered compare builtins are declared as "_Bool
5736   // foo(...)".
5737   TheCall->setArg(0, OrigArg0.get());
5738   TheCall->setArg(1, OrigArg1.get());
5739 
5740   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5741     return false;
5742 
5743   // If the common type isn't a real floating type, then the arguments were
5744   // invalid for this operation.
5745   if (Res.isNull() || !Res->isRealFloatingType())
5746     return Diag(OrigArg0.get()->getBeginLoc(),
5747                 diag::err_typecheck_call_invalid_ordered_compare)
5748            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5749            << SourceRange(OrigArg0.get()->getBeginLoc(),
5750                           OrigArg1.get()->getEndLoc());
5751 
5752   return false;
5753 }
5754 
5755 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5756 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5757 /// to check everything. We expect the last argument to be a floating point
5758 /// value.
5759 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5760   if (TheCall->getNumArgs() < NumArgs)
5761     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5762            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5763   if (TheCall->getNumArgs() > NumArgs)
5764     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5765                 diag::err_typecheck_call_too_many_args)
5766            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5767            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5768                           (*(TheCall->arg_end() - 1))->getEndLoc());
5769 
5770   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5771 
5772   if (OrigArg->isTypeDependent())
5773     return false;
5774 
5775   // This operation requires a non-_Complex floating-point number.
5776   if (!OrigArg->getType()->isRealFloatingType())
5777     return Diag(OrigArg->getBeginLoc(),
5778                 diag::err_typecheck_call_invalid_unary_fp)
5779            << OrigArg->getType() << OrigArg->getSourceRange();
5780 
5781   // If this is an implicit conversion from float -> float, double, or
5782   // long double, remove it.
5783   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5784     // Only remove standard FloatCasts, leaving other casts inplace
5785     if (Cast->getCastKind() == CK_FloatingCast) {
5786       Expr *CastArg = Cast->getSubExpr();
5787       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5788         assert(
5789             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5790              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5791              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5792             "promotion from float to either float, double, or long double is "
5793             "the only expected cast here");
5794         Cast->setSubExpr(nullptr);
5795         TheCall->setArg(NumArgs-1, CastArg);
5796       }
5797     }
5798   }
5799 
5800   return false;
5801 }
5802 
5803 // Customized Sema Checking for VSX builtins that have the following signature:
5804 // vector [...] builtinName(vector [...], vector [...], const int);
5805 // Which takes the same type of vectors (any legal vector type) for the first
5806 // two arguments and takes compile time constant for the third argument.
5807 // Example builtins are :
5808 // vector double vec_xxpermdi(vector double, vector double, int);
5809 // vector short vec_xxsldwi(vector short, vector short, int);
5810 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5811   unsigned ExpectedNumArgs = 3;
5812   if (TheCall->getNumArgs() < ExpectedNumArgs)
5813     return Diag(TheCall->getEndLoc(),
5814                 diag::err_typecheck_call_too_few_args_at_least)
5815            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5816            << TheCall->getSourceRange();
5817 
5818   if (TheCall->getNumArgs() > ExpectedNumArgs)
5819     return Diag(TheCall->getEndLoc(),
5820                 diag::err_typecheck_call_too_many_args_at_most)
5821            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5822            << TheCall->getSourceRange();
5823 
5824   // Check the third argument is a compile time constant
5825   llvm::APSInt Value;
5826   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5827     return Diag(TheCall->getBeginLoc(),
5828                 diag::err_vsx_builtin_nonconstant_argument)
5829            << 3 /* argument index */ << TheCall->getDirectCallee()
5830            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5831                           TheCall->getArg(2)->getEndLoc());
5832 
5833   QualType Arg1Ty = TheCall->getArg(0)->getType();
5834   QualType Arg2Ty = TheCall->getArg(1)->getType();
5835 
5836   // Check the type of argument 1 and argument 2 are vectors.
5837   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5838   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5839       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5840     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5841            << TheCall->getDirectCallee()
5842            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5843                           TheCall->getArg(1)->getEndLoc());
5844   }
5845 
5846   // Check the first two arguments are the same type.
5847   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5848     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5849            << TheCall->getDirectCallee()
5850            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5851                           TheCall->getArg(1)->getEndLoc());
5852   }
5853 
5854   // When default clang type checking is turned off and the customized type
5855   // checking is used, the returning type of the function must be explicitly
5856   // set. Otherwise it is _Bool by default.
5857   TheCall->setType(Arg1Ty);
5858 
5859   return false;
5860 }
5861 
5862 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5863 // This is declared to take (...), so we have to check everything.
5864 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5865   if (TheCall->getNumArgs() < 2)
5866     return ExprError(Diag(TheCall->getEndLoc(),
5867                           diag::err_typecheck_call_too_few_args_at_least)
5868                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5869                      << TheCall->getSourceRange());
5870 
5871   // Determine which of the following types of shufflevector we're checking:
5872   // 1) unary, vector mask: (lhs, mask)
5873   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5874   QualType resType = TheCall->getArg(0)->getType();
5875   unsigned numElements = 0;
5876 
5877   if (!TheCall->getArg(0)->isTypeDependent() &&
5878       !TheCall->getArg(1)->isTypeDependent()) {
5879     QualType LHSType = TheCall->getArg(0)->getType();
5880     QualType RHSType = TheCall->getArg(1)->getType();
5881 
5882     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5883       return ExprError(
5884           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5885           << TheCall->getDirectCallee()
5886           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5887                          TheCall->getArg(1)->getEndLoc()));
5888 
5889     numElements = LHSType->castAs<VectorType>()->getNumElements();
5890     unsigned numResElements = TheCall->getNumArgs() - 2;
5891 
5892     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5893     // with mask.  If so, verify that RHS is an integer vector type with the
5894     // same number of elts as lhs.
5895     if (TheCall->getNumArgs() == 2) {
5896       if (!RHSType->hasIntegerRepresentation() ||
5897           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5898         return ExprError(Diag(TheCall->getBeginLoc(),
5899                               diag::err_vec_builtin_incompatible_vector)
5900                          << TheCall->getDirectCallee()
5901                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5902                                         TheCall->getArg(1)->getEndLoc()));
5903     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5904       return ExprError(Diag(TheCall->getBeginLoc(),
5905                             diag::err_vec_builtin_incompatible_vector)
5906                        << TheCall->getDirectCallee()
5907                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5908                                       TheCall->getArg(1)->getEndLoc()));
5909     } else if (numElements != numResElements) {
5910       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5911       resType = Context.getVectorType(eltType, numResElements,
5912                                       VectorType::GenericVector);
5913     }
5914   }
5915 
5916   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5917     if (TheCall->getArg(i)->isTypeDependent() ||
5918         TheCall->getArg(i)->isValueDependent())
5919       continue;
5920 
5921     llvm::APSInt Result(32);
5922     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5923       return ExprError(Diag(TheCall->getBeginLoc(),
5924                             diag::err_shufflevector_nonconstant_argument)
5925                        << TheCall->getArg(i)->getSourceRange());
5926 
5927     // Allow -1 which will be translated to undef in the IR.
5928     if (Result.isSigned() && Result.isAllOnesValue())
5929       continue;
5930 
5931     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5932       return ExprError(Diag(TheCall->getBeginLoc(),
5933                             diag::err_shufflevector_argument_too_large)
5934                        << TheCall->getArg(i)->getSourceRange());
5935   }
5936 
5937   SmallVector<Expr*, 32> exprs;
5938 
5939   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5940     exprs.push_back(TheCall->getArg(i));
5941     TheCall->setArg(i, nullptr);
5942   }
5943 
5944   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5945                                          TheCall->getCallee()->getBeginLoc(),
5946                                          TheCall->getRParenLoc());
5947 }
5948 
5949 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5950 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5951                                        SourceLocation BuiltinLoc,
5952                                        SourceLocation RParenLoc) {
5953   ExprValueKind VK = VK_RValue;
5954   ExprObjectKind OK = OK_Ordinary;
5955   QualType DstTy = TInfo->getType();
5956   QualType SrcTy = E->getType();
5957 
5958   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5959     return ExprError(Diag(BuiltinLoc,
5960                           diag::err_convertvector_non_vector)
5961                      << E->getSourceRange());
5962   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5963     return ExprError(Diag(BuiltinLoc,
5964                           diag::err_convertvector_non_vector_type));
5965 
5966   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5967     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5968     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5969     if (SrcElts != DstElts)
5970       return ExprError(Diag(BuiltinLoc,
5971                             diag::err_convertvector_incompatible_vector)
5972                        << E->getSourceRange());
5973   }
5974 
5975   return new (Context)
5976       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5977 }
5978 
5979 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5980 // This is declared to take (const void*, ...) and can take two
5981 // optional constant int args.
5982 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5983   unsigned NumArgs = TheCall->getNumArgs();
5984 
5985   if (NumArgs > 3)
5986     return Diag(TheCall->getEndLoc(),
5987                 diag::err_typecheck_call_too_many_args_at_most)
5988            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5989 
5990   // Argument 0 is checked for us and the remaining arguments must be
5991   // constant integers.
5992   for (unsigned i = 1; i != NumArgs; ++i)
5993     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5994       return true;
5995 
5996   return false;
5997 }
5998 
5999 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6000 // __assume does not evaluate its arguments, and should warn if its argument
6001 // has side effects.
6002 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6003   Expr *Arg = TheCall->getArg(0);
6004   if (Arg->isInstantiationDependent()) return false;
6005 
6006   if (Arg->HasSideEffects(Context))
6007     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6008         << Arg->getSourceRange()
6009         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6010 
6011   return false;
6012 }
6013 
6014 /// Handle __builtin_alloca_with_align. This is declared
6015 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6016 /// than 8.
6017 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6018   // The alignment must be a constant integer.
6019   Expr *Arg = TheCall->getArg(1);
6020 
6021   // We can't check the value of a dependent argument.
6022   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6023     if (const auto *UE =
6024             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6025       if (UE->getKind() == UETT_AlignOf ||
6026           UE->getKind() == UETT_PreferredAlignOf)
6027         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6028             << Arg->getSourceRange();
6029 
6030     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6031 
6032     if (!Result.isPowerOf2())
6033       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6034              << Arg->getSourceRange();
6035 
6036     if (Result < Context.getCharWidth())
6037       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6038              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6039 
6040     if (Result > std::numeric_limits<int32_t>::max())
6041       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6042              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6043   }
6044 
6045   return false;
6046 }
6047 
6048 /// Handle __builtin_assume_aligned. This is declared
6049 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6050 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6051   unsigned NumArgs = TheCall->getNumArgs();
6052 
6053   if (NumArgs > 3)
6054     return Diag(TheCall->getEndLoc(),
6055                 diag::err_typecheck_call_too_many_args_at_most)
6056            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6057 
6058   // The alignment must be a constant integer.
6059   Expr *Arg = TheCall->getArg(1);
6060 
6061   // We can't check the value of a dependent argument.
6062   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6063     llvm::APSInt Result;
6064     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6065       return true;
6066 
6067     if (!Result.isPowerOf2())
6068       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6069              << Arg->getSourceRange();
6070 
6071     // Alignment calculations can wrap around if it's greater than 2**29.
6072     unsigned MaximumAlignment = 536870912;
6073     if (Result > MaximumAlignment)
6074       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6075           << Arg->getSourceRange() << MaximumAlignment;
6076   }
6077 
6078   if (NumArgs > 2) {
6079     ExprResult Arg(TheCall->getArg(2));
6080     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6081       Context.getSizeType(), false);
6082     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6083     if (Arg.isInvalid()) return true;
6084     TheCall->setArg(2, Arg.get());
6085   }
6086 
6087   return false;
6088 }
6089 
6090 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6091   unsigned BuiltinID =
6092       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6093   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6094 
6095   unsigned NumArgs = TheCall->getNumArgs();
6096   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6097   if (NumArgs < NumRequiredArgs) {
6098     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6099            << 0 /* function call */ << NumRequiredArgs << NumArgs
6100            << TheCall->getSourceRange();
6101   }
6102   if (NumArgs >= NumRequiredArgs + 0x100) {
6103     return Diag(TheCall->getEndLoc(),
6104                 diag::err_typecheck_call_too_many_args_at_most)
6105            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6106            << TheCall->getSourceRange();
6107   }
6108   unsigned i = 0;
6109 
6110   // For formatting call, check buffer arg.
6111   if (!IsSizeCall) {
6112     ExprResult Arg(TheCall->getArg(i));
6113     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6114         Context, Context.VoidPtrTy, false);
6115     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6116     if (Arg.isInvalid())
6117       return true;
6118     TheCall->setArg(i, Arg.get());
6119     i++;
6120   }
6121 
6122   // Check string literal arg.
6123   unsigned FormatIdx = i;
6124   {
6125     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6126     if (Arg.isInvalid())
6127       return true;
6128     TheCall->setArg(i, Arg.get());
6129     i++;
6130   }
6131 
6132   // Make sure variadic args are scalar.
6133   unsigned FirstDataArg = i;
6134   while (i < NumArgs) {
6135     ExprResult Arg = DefaultVariadicArgumentPromotion(
6136         TheCall->getArg(i), VariadicFunction, nullptr);
6137     if (Arg.isInvalid())
6138       return true;
6139     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6140     if (ArgSize.getQuantity() >= 0x100) {
6141       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6142              << i << (int)ArgSize.getQuantity() << 0xff
6143              << TheCall->getSourceRange();
6144     }
6145     TheCall->setArg(i, Arg.get());
6146     i++;
6147   }
6148 
6149   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6150   // call to avoid duplicate diagnostics.
6151   if (!IsSizeCall) {
6152     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6153     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6154     bool Success = CheckFormatArguments(
6155         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6156         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6157         CheckedVarArgs);
6158     if (!Success)
6159       return true;
6160   }
6161 
6162   if (IsSizeCall) {
6163     TheCall->setType(Context.getSizeType());
6164   } else {
6165     TheCall->setType(Context.VoidPtrTy);
6166   }
6167   return false;
6168 }
6169 
6170 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6171 /// TheCall is a constant expression.
6172 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6173                                   llvm::APSInt &Result) {
6174   Expr *Arg = TheCall->getArg(ArgNum);
6175   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6176   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6177 
6178   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6179 
6180   if (!Arg->isIntegerConstantExpr(Result, Context))
6181     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6182            << FDecl->getDeclName() << Arg->getSourceRange();
6183 
6184   return false;
6185 }
6186 
6187 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6188 /// TheCall is a constant expression in the range [Low, High].
6189 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6190                                        int Low, int High, bool RangeIsError) {
6191   if (isConstantEvaluated())
6192     return false;
6193   llvm::APSInt Result;
6194 
6195   // We can't check the value of a dependent argument.
6196   Expr *Arg = TheCall->getArg(ArgNum);
6197   if (Arg->isTypeDependent() || Arg->isValueDependent())
6198     return false;
6199 
6200   // Check constant-ness first.
6201   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6202     return true;
6203 
6204   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6205     if (RangeIsError)
6206       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6207              << Result.toString(10) << Low << High << Arg->getSourceRange();
6208     else
6209       // Defer the warning until we know if the code will be emitted so that
6210       // dead code can ignore this.
6211       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6212                           PDiag(diag::warn_argument_invalid_range)
6213                               << Result.toString(10) << Low << High
6214                               << Arg->getSourceRange());
6215   }
6216 
6217   return false;
6218 }
6219 
6220 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6221 /// TheCall is a constant expression is a multiple of Num..
6222 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6223                                           unsigned Num) {
6224   llvm::APSInt Result;
6225 
6226   // We can't check the value of a dependent argument.
6227   Expr *Arg = TheCall->getArg(ArgNum);
6228   if (Arg->isTypeDependent() || Arg->isValueDependent())
6229     return false;
6230 
6231   // Check constant-ness first.
6232   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6233     return true;
6234 
6235   if (Result.getSExtValue() % Num != 0)
6236     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6237            << Num << Arg->getSourceRange();
6238 
6239   return false;
6240 }
6241 
6242 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6243 /// constant expression representing a power of 2.
6244 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6245   llvm::APSInt Result;
6246 
6247   // We can't check the value of a dependent argument.
6248   Expr *Arg = TheCall->getArg(ArgNum);
6249   if (Arg->isTypeDependent() || Arg->isValueDependent())
6250     return false;
6251 
6252   // Check constant-ness first.
6253   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6254     return true;
6255 
6256   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6257   // and only if x is a power of 2.
6258   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6259     return false;
6260 
6261   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6262          << Arg->getSourceRange();
6263 }
6264 
6265 static bool IsShiftedByte(llvm::APSInt Value) {
6266   if (Value.isNegative())
6267     return false;
6268 
6269   // Check if it's a shifted byte, by shifting it down
6270   while (true) {
6271     // If the value fits in the bottom byte, the check passes.
6272     if (Value < 0x100)
6273       return true;
6274 
6275     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6276     // fails.
6277     if ((Value & 0xFF) != 0)
6278       return false;
6279 
6280     // If the bottom 8 bits are all 0, but something above that is nonzero,
6281     // then shifting the value right by 8 bits won't affect whether it's a
6282     // shifted byte or not. So do that, and go round again.
6283     Value >>= 8;
6284   }
6285 }
6286 
6287 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6288 /// a constant expression representing an arbitrary byte value shifted left by
6289 /// a multiple of 8 bits.
6290 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) {
6291   llvm::APSInt Result;
6292 
6293   // We can't check the value of a dependent argument.
6294   Expr *Arg = TheCall->getArg(ArgNum);
6295   if (Arg->isTypeDependent() || Arg->isValueDependent())
6296     return false;
6297 
6298   // Check constant-ness first.
6299   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6300     return true;
6301 
6302   if (IsShiftedByte(Result))
6303     return false;
6304 
6305   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6306          << Arg->getSourceRange();
6307 }
6308 
6309 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6310 /// TheCall is a constant expression representing either a shifted byte value,
6311 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6312 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6313 /// Arm MVE intrinsics.
6314 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6315                                                    int ArgNum) {
6316   llvm::APSInt Result;
6317 
6318   // We can't check the value of a dependent argument.
6319   Expr *Arg = TheCall->getArg(ArgNum);
6320   if (Arg->isTypeDependent() || Arg->isValueDependent())
6321     return false;
6322 
6323   // Check constant-ness first.
6324   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6325     return true;
6326 
6327   // Check to see if it's in either of the required forms.
6328   if (IsShiftedByte(Result) ||
6329       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6330     return false;
6331 
6332   return Diag(TheCall->getBeginLoc(),
6333               diag::err_argument_not_shifted_byte_or_xxff)
6334          << Arg->getSourceRange();
6335 }
6336 
6337 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6338 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6339   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6340     if (checkArgCount(*this, TheCall, 2))
6341       return true;
6342     Expr *Arg0 = TheCall->getArg(0);
6343     Expr *Arg1 = TheCall->getArg(1);
6344 
6345     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6346     if (FirstArg.isInvalid())
6347       return true;
6348     QualType FirstArgType = FirstArg.get()->getType();
6349     if (!FirstArgType->isAnyPointerType())
6350       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6351                << "first" << FirstArgType << Arg0->getSourceRange();
6352     TheCall->setArg(0, FirstArg.get());
6353 
6354     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6355     if (SecArg.isInvalid())
6356       return true;
6357     QualType SecArgType = SecArg.get()->getType();
6358     if (!SecArgType->isIntegerType())
6359       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6360                << "second" << SecArgType << Arg1->getSourceRange();
6361 
6362     // Derive the return type from the pointer argument.
6363     TheCall->setType(FirstArgType);
6364     return false;
6365   }
6366 
6367   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6368     if (checkArgCount(*this, TheCall, 2))
6369       return true;
6370 
6371     Expr *Arg0 = TheCall->getArg(0);
6372     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6373     if (FirstArg.isInvalid())
6374       return true;
6375     QualType FirstArgType = FirstArg.get()->getType();
6376     if (!FirstArgType->isAnyPointerType())
6377       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6378                << "first" << FirstArgType << Arg0->getSourceRange();
6379     TheCall->setArg(0, FirstArg.get());
6380 
6381     // Derive the return type from the pointer argument.
6382     TheCall->setType(FirstArgType);
6383 
6384     // Second arg must be an constant in range [0,15]
6385     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6386   }
6387 
6388   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6389     if (checkArgCount(*this, TheCall, 2))
6390       return true;
6391     Expr *Arg0 = TheCall->getArg(0);
6392     Expr *Arg1 = TheCall->getArg(1);
6393 
6394     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6395     if (FirstArg.isInvalid())
6396       return true;
6397     QualType FirstArgType = FirstArg.get()->getType();
6398     if (!FirstArgType->isAnyPointerType())
6399       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6400                << "first" << FirstArgType << Arg0->getSourceRange();
6401 
6402     QualType SecArgType = Arg1->getType();
6403     if (!SecArgType->isIntegerType())
6404       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6405                << "second" << SecArgType << Arg1->getSourceRange();
6406     TheCall->setType(Context.IntTy);
6407     return false;
6408   }
6409 
6410   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6411       BuiltinID == AArch64::BI__builtin_arm_stg) {
6412     if (checkArgCount(*this, TheCall, 1))
6413       return true;
6414     Expr *Arg0 = TheCall->getArg(0);
6415     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6416     if (FirstArg.isInvalid())
6417       return true;
6418 
6419     QualType FirstArgType = FirstArg.get()->getType();
6420     if (!FirstArgType->isAnyPointerType())
6421       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6422                << "first" << FirstArgType << Arg0->getSourceRange();
6423     TheCall->setArg(0, FirstArg.get());
6424 
6425     // Derive the return type from the pointer argument.
6426     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6427       TheCall->setType(FirstArgType);
6428     return false;
6429   }
6430 
6431   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6432     Expr *ArgA = TheCall->getArg(0);
6433     Expr *ArgB = TheCall->getArg(1);
6434 
6435     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6436     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6437 
6438     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6439       return true;
6440 
6441     QualType ArgTypeA = ArgExprA.get()->getType();
6442     QualType ArgTypeB = ArgExprB.get()->getType();
6443 
6444     auto isNull = [&] (Expr *E) -> bool {
6445       return E->isNullPointerConstant(
6446                         Context, Expr::NPC_ValueDependentIsNotNull); };
6447 
6448     // argument should be either a pointer or null
6449     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6450       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6451         << "first" << ArgTypeA << ArgA->getSourceRange();
6452 
6453     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6454       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6455         << "second" << ArgTypeB << ArgB->getSourceRange();
6456 
6457     // Ensure Pointee types are compatible
6458     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6459         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6460       QualType pointeeA = ArgTypeA->getPointeeType();
6461       QualType pointeeB = ArgTypeB->getPointeeType();
6462       if (!Context.typesAreCompatible(
6463              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6464              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6465         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6466           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6467           << ArgB->getSourceRange();
6468       }
6469     }
6470 
6471     // at least one argument should be pointer type
6472     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6473       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6474         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6475 
6476     if (isNull(ArgA)) // adopt type of the other pointer
6477       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6478 
6479     if (isNull(ArgB))
6480       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6481 
6482     TheCall->setArg(0, ArgExprA.get());
6483     TheCall->setArg(1, ArgExprB.get());
6484     TheCall->setType(Context.LongLongTy);
6485     return false;
6486   }
6487   assert(false && "Unhandled ARM MTE intrinsic");
6488   return true;
6489 }
6490 
6491 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6492 /// TheCall is an ARM/AArch64 special register string literal.
6493 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6494                                     int ArgNum, unsigned ExpectedFieldNum,
6495                                     bool AllowName) {
6496   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6497                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6498                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6499                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6500                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6501                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6502   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6503                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6504                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6505                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6506                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6507                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6508   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6509 
6510   // We can't check the value of a dependent argument.
6511   Expr *Arg = TheCall->getArg(ArgNum);
6512   if (Arg->isTypeDependent() || Arg->isValueDependent())
6513     return false;
6514 
6515   // Check if the argument is a string literal.
6516   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6517     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6518            << Arg->getSourceRange();
6519 
6520   // Check the type of special register given.
6521   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6522   SmallVector<StringRef, 6> Fields;
6523   Reg.split(Fields, ":");
6524 
6525   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6526     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6527            << Arg->getSourceRange();
6528 
6529   // If the string is the name of a register then we cannot check that it is
6530   // valid here but if the string is of one the forms described in ACLE then we
6531   // can check that the supplied fields are integers and within the valid
6532   // ranges.
6533   if (Fields.size() > 1) {
6534     bool FiveFields = Fields.size() == 5;
6535 
6536     bool ValidString = true;
6537     if (IsARMBuiltin) {
6538       ValidString &= Fields[0].startswith_lower("cp") ||
6539                      Fields[0].startswith_lower("p");
6540       if (ValidString)
6541         Fields[0] =
6542           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6543 
6544       ValidString &= Fields[2].startswith_lower("c");
6545       if (ValidString)
6546         Fields[2] = Fields[2].drop_front(1);
6547 
6548       if (FiveFields) {
6549         ValidString &= Fields[3].startswith_lower("c");
6550         if (ValidString)
6551           Fields[3] = Fields[3].drop_front(1);
6552       }
6553     }
6554 
6555     SmallVector<int, 5> Ranges;
6556     if (FiveFields)
6557       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6558     else
6559       Ranges.append({15, 7, 15});
6560 
6561     for (unsigned i=0; i<Fields.size(); ++i) {
6562       int IntField;
6563       ValidString &= !Fields[i].getAsInteger(10, IntField);
6564       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6565     }
6566 
6567     if (!ValidString)
6568       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6569              << Arg->getSourceRange();
6570   } else if (IsAArch64Builtin && Fields.size() == 1) {
6571     // If the register name is one of those that appear in the condition below
6572     // and the special register builtin being used is one of the write builtins,
6573     // then we require that the argument provided for writing to the register
6574     // is an integer constant expression. This is because it will be lowered to
6575     // an MSR (immediate) instruction, so we need to know the immediate at
6576     // compile time.
6577     if (TheCall->getNumArgs() != 2)
6578       return false;
6579 
6580     std::string RegLower = Reg.lower();
6581     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6582         RegLower != "pan" && RegLower != "uao")
6583       return false;
6584 
6585     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6586   }
6587 
6588   return false;
6589 }
6590 
6591 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6592 /// This checks that the target supports __builtin_longjmp and
6593 /// that val is a constant 1.
6594 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6595   if (!Context.getTargetInfo().hasSjLjLowering())
6596     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6597            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6598 
6599   Expr *Arg = TheCall->getArg(1);
6600   llvm::APSInt Result;
6601 
6602   // TODO: This is less than ideal. Overload this to take a value.
6603   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6604     return true;
6605 
6606   if (Result != 1)
6607     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6608            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6609 
6610   return false;
6611 }
6612 
6613 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6614 /// This checks that the target supports __builtin_setjmp.
6615 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6616   if (!Context.getTargetInfo().hasSjLjLowering())
6617     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6618            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6619   return false;
6620 }
6621 
6622 namespace {
6623 
6624 class UncoveredArgHandler {
6625   enum { Unknown = -1, AllCovered = -2 };
6626 
6627   signed FirstUncoveredArg = Unknown;
6628   SmallVector<const Expr *, 4> DiagnosticExprs;
6629 
6630 public:
6631   UncoveredArgHandler() = default;
6632 
6633   bool hasUncoveredArg() const {
6634     return (FirstUncoveredArg >= 0);
6635   }
6636 
6637   unsigned getUncoveredArg() const {
6638     assert(hasUncoveredArg() && "no uncovered argument");
6639     return FirstUncoveredArg;
6640   }
6641 
6642   void setAllCovered() {
6643     // A string has been found with all arguments covered, so clear out
6644     // the diagnostics.
6645     DiagnosticExprs.clear();
6646     FirstUncoveredArg = AllCovered;
6647   }
6648 
6649   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6650     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6651 
6652     // Don't update if a previous string covers all arguments.
6653     if (FirstUncoveredArg == AllCovered)
6654       return;
6655 
6656     // UncoveredArgHandler tracks the highest uncovered argument index
6657     // and with it all the strings that match this index.
6658     if (NewFirstUncoveredArg == FirstUncoveredArg)
6659       DiagnosticExprs.push_back(StrExpr);
6660     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6661       DiagnosticExprs.clear();
6662       DiagnosticExprs.push_back(StrExpr);
6663       FirstUncoveredArg = NewFirstUncoveredArg;
6664     }
6665   }
6666 
6667   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6668 };
6669 
6670 enum StringLiteralCheckType {
6671   SLCT_NotALiteral,
6672   SLCT_UncheckedLiteral,
6673   SLCT_CheckedLiteral
6674 };
6675 
6676 } // namespace
6677 
6678 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6679                                      BinaryOperatorKind BinOpKind,
6680                                      bool AddendIsRight) {
6681   unsigned BitWidth = Offset.getBitWidth();
6682   unsigned AddendBitWidth = Addend.getBitWidth();
6683   // There might be negative interim results.
6684   if (Addend.isUnsigned()) {
6685     Addend = Addend.zext(++AddendBitWidth);
6686     Addend.setIsSigned(true);
6687   }
6688   // Adjust the bit width of the APSInts.
6689   if (AddendBitWidth > BitWidth) {
6690     Offset = Offset.sext(AddendBitWidth);
6691     BitWidth = AddendBitWidth;
6692   } else if (BitWidth > AddendBitWidth) {
6693     Addend = Addend.sext(BitWidth);
6694   }
6695 
6696   bool Ov = false;
6697   llvm::APSInt ResOffset = Offset;
6698   if (BinOpKind == BO_Add)
6699     ResOffset = Offset.sadd_ov(Addend, Ov);
6700   else {
6701     assert(AddendIsRight && BinOpKind == BO_Sub &&
6702            "operator must be add or sub with addend on the right");
6703     ResOffset = Offset.ssub_ov(Addend, Ov);
6704   }
6705 
6706   // We add an offset to a pointer here so we should support an offset as big as
6707   // possible.
6708   if (Ov) {
6709     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6710            "index (intermediate) result too big");
6711     Offset = Offset.sext(2 * BitWidth);
6712     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6713     return;
6714   }
6715 
6716   Offset = ResOffset;
6717 }
6718 
6719 namespace {
6720 
6721 // This is a wrapper class around StringLiteral to support offsetted string
6722 // literals as format strings. It takes the offset into account when returning
6723 // the string and its length or the source locations to display notes correctly.
6724 class FormatStringLiteral {
6725   const StringLiteral *FExpr;
6726   int64_t Offset;
6727 
6728  public:
6729   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6730       : FExpr(fexpr), Offset(Offset) {}
6731 
6732   StringRef getString() const {
6733     return FExpr->getString().drop_front(Offset);
6734   }
6735 
6736   unsigned getByteLength() const {
6737     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6738   }
6739 
6740   unsigned getLength() const { return FExpr->getLength() - Offset; }
6741   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6742 
6743   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6744 
6745   QualType getType() const { return FExpr->getType(); }
6746 
6747   bool isAscii() const { return FExpr->isAscii(); }
6748   bool isWide() const { return FExpr->isWide(); }
6749   bool isUTF8() const { return FExpr->isUTF8(); }
6750   bool isUTF16() const { return FExpr->isUTF16(); }
6751   bool isUTF32() const { return FExpr->isUTF32(); }
6752   bool isPascal() const { return FExpr->isPascal(); }
6753 
6754   SourceLocation getLocationOfByte(
6755       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6756       const TargetInfo &Target, unsigned *StartToken = nullptr,
6757       unsigned *StartTokenByteOffset = nullptr) const {
6758     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6759                                     StartToken, StartTokenByteOffset);
6760   }
6761 
6762   SourceLocation getBeginLoc() const LLVM_READONLY {
6763     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6764   }
6765 
6766   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6767 };
6768 
6769 }  // namespace
6770 
6771 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6772                               const Expr *OrigFormatExpr,
6773                               ArrayRef<const Expr *> Args,
6774                               bool HasVAListArg, unsigned format_idx,
6775                               unsigned firstDataArg,
6776                               Sema::FormatStringType Type,
6777                               bool inFunctionCall,
6778                               Sema::VariadicCallType CallType,
6779                               llvm::SmallBitVector &CheckedVarArgs,
6780                               UncoveredArgHandler &UncoveredArg,
6781                               bool IgnoreStringsWithoutSpecifiers);
6782 
6783 // Determine if an expression is a string literal or constant string.
6784 // If this function returns false on the arguments to a function expecting a
6785 // format string, we will usually need to emit a warning.
6786 // True string literals are then checked by CheckFormatString.
6787 static StringLiteralCheckType
6788 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6789                       bool HasVAListArg, unsigned format_idx,
6790                       unsigned firstDataArg, Sema::FormatStringType Type,
6791                       Sema::VariadicCallType CallType, bool InFunctionCall,
6792                       llvm::SmallBitVector &CheckedVarArgs,
6793                       UncoveredArgHandler &UncoveredArg,
6794                       llvm::APSInt Offset,
6795                       bool IgnoreStringsWithoutSpecifiers = false) {
6796   if (S.isConstantEvaluated())
6797     return SLCT_NotALiteral;
6798  tryAgain:
6799   assert(Offset.isSigned() && "invalid offset");
6800 
6801   if (E->isTypeDependent() || E->isValueDependent())
6802     return SLCT_NotALiteral;
6803 
6804   E = E->IgnoreParenCasts();
6805 
6806   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6807     // Technically -Wformat-nonliteral does not warn about this case.
6808     // The behavior of printf and friends in this case is implementation
6809     // dependent.  Ideally if the format string cannot be null then
6810     // it should have a 'nonnull' attribute in the function prototype.
6811     return SLCT_UncheckedLiteral;
6812 
6813   switch (E->getStmtClass()) {
6814   case Stmt::BinaryConditionalOperatorClass:
6815   case Stmt::ConditionalOperatorClass: {
6816     // The expression is a literal if both sub-expressions were, and it was
6817     // completely checked only if both sub-expressions were checked.
6818     const AbstractConditionalOperator *C =
6819         cast<AbstractConditionalOperator>(E);
6820 
6821     // Determine whether it is necessary to check both sub-expressions, for
6822     // example, because the condition expression is a constant that can be
6823     // evaluated at compile time.
6824     bool CheckLeft = true, CheckRight = true;
6825 
6826     bool Cond;
6827     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6828                                                  S.isConstantEvaluated())) {
6829       if (Cond)
6830         CheckRight = false;
6831       else
6832         CheckLeft = false;
6833     }
6834 
6835     // We need to maintain the offsets for the right and the left hand side
6836     // separately to check if every possible indexed expression is a valid
6837     // string literal. They might have different offsets for different string
6838     // literals in the end.
6839     StringLiteralCheckType Left;
6840     if (!CheckLeft)
6841       Left = SLCT_UncheckedLiteral;
6842     else {
6843       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6844                                    HasVAListArg, format_idx, firstDataArg,
6845                                    Type, CallType, InFunctionCall,
6846                                    CheckedVarArgs, UncoveredArg, Offset,
6847                                    IgnoreStringsWithoutSpecifiers);
6848       if (Left == SLCT_NotALiteral || !CheckRight) {
6849         return Left;
6850       }
6851     }
6852 
6853     StringLiteralCheckType Right = checkFormatStringExpr(
6854         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6855         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6856         IgnoreStringsWithoutSpecifiers);
6857 
6858     return (CheckLeft && Left < Right) ? Left : Right;
6859   }
6860 
6861   case Stmt::ImplicitCastExprClass:
6862     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6863     goto tryAgain;
6864 
6865   case Stmt::OpaqueValueExprClass:
6866     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6867       E = src;
6868       goto tryAgain;
6869     }
6870     return SLCT_NotALiteral;
6871 
6872   case Stmt::PredefinedExprClass:
6873     // While __func__, etc., are technically not string literals, they
6874     // cannot contain format specifiers and thus are not a security
6875     // liability.
6876     return SLCT_UncheckedLiteral;
6877 
6878   case Stmt::DeclRefExprClass: {
6879     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6880 
6881     // As an exception, do not flag errors for variables binding to
6882     // const string literals.
6883     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6884       bool isConstant = false;
6885       QualType T = DR->getType();
6886 
6887       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6888         isConstant = AT->getElementType().isConstant(S.Context);
6889       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6890         isConstant = T.isConstant(S.Context) &&
6891                      PT->getPointeeType().isConstant(S.Context);
6892       } else if (T->isObjCObjectPointerType()) {
6893         // In ObjC, there is usually no "const ObjectPointer" type,
6894         // so don't check if the pointee type is constant.
6895         isConstant = T.isConstant(S.Context);
6896       }
6897 
6898       if (isConstant) {
6899         if (const Expr *Init = VD->getAnyInitializer()) {
6900           // Look through initializers like const char c[] = { "foo" }
6901           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6902             if (InitList->isStringLiteralInit())
6903               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6904           }
6905           return checkFormatStringExpr(S, Init, Args,
6906                                        HasVAListArg, format_idx,
6907                                        firstDataArg, Type, CallType,
6908                                        /*InFunctionCall*/ false, CheckedVarArgs,
6909                                        UncoveredArg, Offset);
6910         }
6911       }
6912 
6913       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6914       // special check to see if the format string is a function parameter
6915       // of the function calling the printf function.  If the function
6916       // has an attribute indicating it is a printf-like function, then we
6917       // should suppress warnings concerning non-literals being used in a call
6918       // to a vprintf function.  For example:
6919       //
6920       // void
6921       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6922       //      va_list ap;
6923       //      va_start(ap, fmt);
6924       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6925       //      ...
6926       // }
6927       if (HasVAListArg) {
6928         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6929           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6930             int PVIndex = PV->getFunctionScopeIndex() + 1;
6931             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6932               // adjust for implicit parameter
6933               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6934                 if (MD->isInstance())
6935                   ++PVIndex;
6936               // We also check if the formats are compatible.
6937               // We can't pass a 'scanf' string to a 'printf' function.
6938               if (PVIndex == PVFormat->getFormatIdx() &&
6939                   Type == S.GetFormatStringType(PVFormat))
6940                 return SLCT_UncheckedLiteral;
6941             }
6942           }
6943         }
6944       }
6945     }
6946 
6947     return SLCT_NotALiteral;
6948   }
6949 
6950   case Stmt::CallExprClass:
6951   case Stmt::CXXMemberCallExprClass: {
6952     const CallExpr *CE = cast<CallExpr>(E);
6953     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6954       bool IsFirst = true;
6955       StringLiteralCheckType CommonResult;
6956       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6957         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6958         StringLiteralCheckType Result = checkFormatStringExpr(
6959             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6960             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6961             IgnoreStringsWithoutSpecifiers);
6962         if (IsFirst) {
6963           CommonResult = Result;
6964           IsFirst = false;
6965         }
6966       }
6967       if (!IsFirst)
6968         return CommonResult;
6969 
6970       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6971         unsigned BuiltinID = FD->getBuiltinID();
6972         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6973             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6974           const Expr *Arg = CE->getArg(0);
6975           return checkFormatStringExpr(S, Arg, Args,
6976                                        HasVAListArg, format_idx,
6977                                        firstDataArg, Type, CallType,
6978                                        InFunctionCall, CheckedVarArgs,
6979                                        UncoveredArg, Offset,
6980                                        IgnoreStringsWithoutSpecifiers);
6981         }
6982       }
6983     }
6984 
6985     return SLCT_NotALiteral;
6986   }
6987   case Stmt::ObjCMessageExprClass: {
6988     const auto *ME = cast<ObjCMessageExpr>(E);
6989     if (const auto *MD = ME->getMethodDecl()) {
6990       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6991         // As a special case heuristic, if we're using the method -[NSBundle
6992         // localizedStringForKey:value:table:], ignore any key strings that lack
6993         // format specifiers. The idea is that if the key doesn't have any
6994         // format specifiers then its probably just a key to map to the
6995         // localized strings. If it does have format specifiers though, then its
6996         // likely that the text of the key is the format string in the
6997         // programmer's language, and should be checked.
6998         const ObjCInterfaceDecl *IFace;
6999         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7000             IFace->getIdentifier()->isStr("NSBundle") &&
7001             MD->getSelector().isKeywordSelector(
7002                 {"localizedStringForKey", "value", "table"})) {
7003           IgnoreStringsWithoutSpecifiers = true;
7004         }
7005 
7006         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7007         return checkFormatStringExpr(
7008             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7009             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7010             IgnoreStringsWithoutSpecifiers);
7011       }
7012     }
7013 
7014     return SLCT_NotALiteral;
7015   }
7016   case Stmt::ObjCStringLiteralClass:
7017   case Stmt::StringLiteralClass: {
7018     const StringLiteral *StrE = nullptr;
7019 
7020     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7021       StrE = ObjCFExpr->getString();
7022     else
7023       StrE = cast<StringLiteral>(E);
7024 
7025     if (StrE) {
7026       if (Offset.isNegative() || Offset > StrE->getLength()) {
7027         // TODO: It would be better to have an explicit warning for out of
7028         // bounds literals.
7029         return SLCT_NotALiteral;
7030       }
7031       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7032       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7033                         firstDataArg, Type, InFunctionCall, CallType,
7034                         CheckedVarArgs, UncoveredArg,
7035                         IgnoreStringsWithoutSpecifiers);
7036       return SLCT_CheckedLiteral;
7037     }
7038 
7039     return SLCT_NotALiteral;
7040   }
7041   case Stmt::BinaryOperatorClass: {
7042     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7043 
7044     // A string literal + an int offset is still a string literal.
7045     if (BinOp->isAdditiveOp()) {
7046       Expr::EvalResult LResult, RResult;
7047 
7048       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7049           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7050       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7051           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7052 
7053       if (LIsInt != RIsInt) {
7054         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7055 
7056         if (LIsInt) {
7057           if (BinOpKind == BO_Add) {
7058             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7059             E = BinOp->getRHS();
7060             goto tryAgain;
7061           }
7062         } else {
7063           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7064           E = BinOp->getLHS();
7065           goto tryAgain;
7066         }
7067       }
7068     }
7069 
7070     return SLCT_NotALiteral;
7071   }
7072   case Stmt::UnaryOperatorClass: {
7073     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7074     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7075     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7076       Expr::EvalResult IndexResult;
7077       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7078                                        Expr::SE_NoSideEffects,
7079                                        S.isConstantEvaluated())) {
7080         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7081                    /*RHS is int*/ true);
7082         E = ASE->getBase();
7083         goto tryAgain;
7084       }
7085     }
7086 
7087     return SLCT_NotALiteral;
7088   }
7089 
7090   default:
7091     return SLCT_NotALiteral;
7092   }
7093 }
7094 
7095 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7096   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7097       .Case("scanf", FST_Scanf)
7098       .Cases("printf", "printf0", FST_Printf)
7099       .Cases("NSString", "CFString", FST_NSString)
7100       .Case("strftime", FST_Strftime)
7101       .Case("strfmon", FST_Strfmon)
7102       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7103       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7104       .Case("os_trace", FST_OSLog)
7105       .Case("os_log", FST_OSLog)
7106       .Default(FST_Unknown);
7107 }
7108 
7109 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7110 /// functions) for correct use of format strings.
7111 /// Returns true if a format string has been fully checked.
7112 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7113                                 ArrayRef<const Expr *> Args,
7114                                 bool IsCXXMember,
7115                                 VariadicCallType CallType,
7116                                 SourceLocation Loc, SourceRange Range,
7117                                 llvm::SmallBitVector &CheckedVarArgs) {
7118   FormatStringInfo FSI;
7119   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7120     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7121                                 FSI.FirstDataArg, GetFormatStringType(Format),
7122                                 CallType, Loc, Range, CheckedVarArgs);
7123   return false;
7124 }
7125 
7126 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7127                                 bool HasVAListArg, unsigned format_idx,
7128                                 unsigned firstDataArg, FormatStringType Type,
7129                                 VariadicCallType CallType,
7130                                 SourceLocation Loc, SourceRange Range,
7131                                 llvm::SmallBitVector &CheckedVarArgs) {
7132   // CHECK: printf/scanf-like function is called with no format string.
7133   if (format_idx >= Args.size()) {
7134     Diag(Loc, diag::warn_missing_format_string) << Range;
7135     return false;
7136   }
7137 
7138   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7139 
7140   // CHECK: format string is not a string literal.
7141   //
7142   // Dynamically generated format strings are difficult to
7143   // automatically vet at compile time.  Requiring that format strings
7144   // are string literals: (1) permits the checking of format strings by
7145   // the compiler and thereby (2) can practically remove the source of
7146   // many format string exploits.
7147 
7148   // Format string can be either ObjC string (e.g. @"%d") or
7149   // C string (e.g. "%d")
7150   // ObjC string uses the same format specifiers as C string, so we can use
7151   // the same format string checking logic for both ObjC and C strings.
7152   UncoveredArgHandler UncoveredArg;
7153   StringLiteralCheckType CT =
7154       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7155                             format_idx, firstDataArg, Type, CallType,
7156                             /*IsFunctionCall*/ true, CheckedVarArgs,
7157                             UncoveredArg,
7158                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7159 
7160   // Generate a diagnostic where an uncovered argument is detected.
7161   if (UncoveredArg.hasUncoveredArg()) {
7162     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7163     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7164     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7165   }
7166 
7167   if (CT != SLCT_NotALiteral)
7168     // Literal format string found, check done!
7169     return CT == SLCT_CheckedLiteral;
7170 
7171   // Strftime is particular as it always uses a single 'time' argument,
7172   // so it is safe to pass a non-literal string.
7173   if (Type == FST_Strftime)
7174     return false;
7175 
7176   // Do not emit diag when the string param is a macro expansion and the
7177   // format is either NSString or CFString. This is a hack to prevent
7178   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7179   // which are usually used in place of NS and CF string literals.
7180   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7181   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7182     return false;
7183 
7184   // If there are no arguments specified, warn with -Wformat-security, otherwise
7185   // warn only with -Wformat-nonliteral.
7186   if (Args.size() == firstDataArg) {
7187     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7188       << OrigFormatExpr->getSourceRange();
7189     switch (Type) {
7190     default:
7191       break;
7192     case FST_Kprintf:
7193     case FST_FreeBSDKPrintf:
7194     case FST_Printf:
7195       Diag(FormatLoc, diag::note_format_security_fixit)
7196         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7197       break;
7198     case FST_NSString:
7199       Diag(FormatLoc, diag::note_format_security_fixit)
7200         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7201       break;
7202     }
7203   } else {
7204     Diag(FormatLoc, diag::warn_format_nonliteral)
7205       << OrigFormatExpr->getSourceRange();
7206   }
7207   return false;
7208 }
7209 
7210 namespace {
7211 
7212 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7213 protected:
7214   Sema &S;
7215   const FormatStringLiteral *FExpr;
7216   const Expr *OrigFormatExpr;
7217   const Sema::FormatStringType FSType;
7218   const unsigned FirstDataArg;
7219   const unsigned NumDataArgs;
7220   const char *Beg; // Start of format string.
7221   const bool HasVAListArg;
7222   ArrayRef<const Expr *> Args;
7223   unsigned FormatIdx;
7224   llvm::SmallBitVector CoveredArgs;
7225   bool usesPositionalArgs = false;
7226   bool atFirstArg = true;
7227   bool inFunctionCall;
7228   Sema::VariadicCallType CallType;
7229   llvm::SmallBitVector &CheckedVarArgs;
7230   UncoveredArgHandler &UncoveredArg;
7231 
7232 public:
7233   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7234                      const Expr *origFormatExpr,
7235                      const Sema::FormatStringType type, unsigned firstDataArg,
7236                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7237                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7238                      bool inFunctionCall, Sema::VariadicCallType callType,
7239                      llvm::SmallBitVector &CheckedVarArgs,
7240                      UncoveredArgHandler &UncoveredArg)
7241       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7242         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7243         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7244         inFunctionCall(inFunctionCall), CallType(callType),
7245         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7246     CoveredArgs.resize(numDataArgs);
7247     CoveredArgs.reset();
7248   }
7249 
7250   void DoneProcessing();
7251 
7252   void HandleIncompleteSpecifier(const char *startSpecifier,
7253                                  unsigned specifierLen) override;
7254 
7255   void HandleInvalidLengthModifier(
7256                            const analyze_format_string::FormatSpecifier &FS,
7257                            const analyze_format_string::ConversionSpecifier &CS,
7258                            const char *startSpecifier, unsigned specifierLen,
7259                            unsigned DiagID);
7260 
7261   void HandleNonStandardLengthModifier(
7262                     const analyze_format_string::FormatSpecifier &FS,
7263                     const char *startSpecifier, unsigned specifierLen);
7264 
7265   void HandleNonStandardConversionSpecifier(
7266                     const analyze_format_string::ConversionSpecifier &CS,
7267                     const char *startSpecifier, unsigned specifierLen);
7268 
7269   void HandlePosition(const char *startPos, unsigned posLen) override;
7270 
7271   void HandleInvalidPosition(const char *startSpecifier,
7272                              unsigned specifierLen,
7273                              analyze_format_string::PositionContext p) override;
7274 
7275   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7276 
7277   void HandleNullChar(const char *nullCharacter) override;
7278 
7279   template <typename Range>
7280   static void
7281   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7282                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7283                        bool IsStringLocation, Range StringRange,
7284                        ArrayRef<FixItHint> Fixit = None);
7285 
7286 protected:
7287   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7288                                         const char *startSpec,
7289                                         unsigned specifierLen,
7290                                         const char *csStart, unsigned csLen);
7291 
7292   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7293                                          const char *startSpec,
7294                                          unsigned specifierLen);
7295 
7296   SourceRange getFormatStringRange();
7297   CharSourceRange getSpecifierRange(const char *startSpecifier,
7298                                     unsigned specifierLen);
7299   SourceLocation getLocationOfByte(const char *x);
7300 
7301   const Expr *getDataArg(unsigned i) const;
7302 
7303   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7304                     const analyze_format_string::ConversionSpecifier &CS,
7305                     const char *startSpecifier, unsigned specifierLen,
7306                     unsigned argIndex);
7307 
7308   template <typename Range>
7309   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7310                             bool IsStringLocation, Range StringRange,
7311                             ArrayRef<FixItHint> Fixit = None);
7312 };
7313 
7314 } // namespace
7315 
7316 SourceRange CheckFormatHandler::getFormatStringRange() {
7317   return OrigFormatExpr->getSourceRange();
7318 }
7319 
7320 CharSourceRange CheckFormatHandler::
7321 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7322   SourceLocation Start = getLocationOfByte(startSpecifier);
7323   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7324 
7325   // Advance the end SourceLocation by one due to half-open ranges.
7326   End = End.getLocWithOffset(1);
7327 
7328   return CharSourceRange::getCharRange(Start, End);
7329 }
7330 
7331 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7332   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7333                                   S.getLangOpts(), S.Context.getTargetInfo());
7334 }
7335 
7336 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7337                                                    unsigned specifierLen){
7338   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7339                        getLocationOfByte(startSpecifier),
7340                        /*IsStringLocation*/true,
7341                        getSpecifierRange(startSpecifier, specifierLen));
7342 }
7343 
7344 void CheckFormatHandler::HandleInvalidLengthModifier(
7345     const analyze_format_string::FormatSpecifier &FS,
7346     const analyze_format_string::ConversionSpecifier &CS,
7347     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7348   using namespace analyze_format_string;
7349 
7350   const LengthModifier &LM = FS.getLengthModifier();
7351   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7352 
7353   // See if we know how to fix this length modifier.
7354   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7355   if (FixedLM) {
7356     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7357                          getLocationOfByte(LM.getStart()),
7358                          /*IsStringLocation*/true,
7359                          getSpecifierRange(startSpecifier, specifierLen));
7360 
7361     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7362       << FixedLM->toString()
7363       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7364 
7365   } else {
7366     FixItHint Hint;
7367     if (DiagID == diag::warn_format_nonsensical_length)
7368       Hint = FixItHint::CreateRemoval(LMRange);
7369 
7370     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7371                          getLocationOfByte(LM.getStart()),
7372                          /*IsStringLocation*/true,
7373                          getSpecifierRange(startSpecifier, specifierLen),
7374                          Hint);
7375   }
7376 }
7377 
7378 void CheckFormatHandler::HandleNonStandardLengthModifier(
7379     const analyze_format_string::FormatSpecifier &FS,
7380     const char *startSpecifier, unsigned specifierLen) {
7381   using namespace analyze_format_string;
7382 
7383   const LengthModifier &LM = FS.getLengthModifier();
7384   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7385 
7386   // See if we know how to fix this length modifier.
7387   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7388   if (FixedLM) {
7389     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7390                            << LM.toString() << 0,
7391                          getLocationOfByte(LM.getStart()),
7392                          /*IsStringLocation*/true,
7393                          getSpecifierRange(startSpecifier, specifierLen));
7394 
7395     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7396       << FixedLM->toString()
7397       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7398 
7399   } else {
7400     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7401                            << LM.toString() << 0,
7402                          getLocationOfByte(LM.getStart()),
7403                          /*IsStringLocation*/true,
7404                          getSpecifierRange(startSpecifier, specifierLen));
7405   }
7406 }
7407 
7408 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7409     const analyze_format_string::ConversionSpecifier &CS,
7410     const char *startSpecifier, unsigned specifierLen) {
7411   using namespace analyze_format_string;
7412 
7413   // See if we know how to fix this conversion specifier.
7414   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7415   if (FixedCS) {
7416     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7417                           << CS.toString() << /*conversion specifier*/1,
7418                          getLocationOfByte(CS.getStart()),
7419                          /*IsStringLocation*/true,
7420                          getSpecifierRange(startSpecifier, specifierLen));
7421 
7422     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7423     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7424       << FixedCS->toString()
7425       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7426   } else {
7427     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7428                           << CS.toString() << /*conversion specifier*/1,
7429                          getLocationOfByte(CS.getStart()),
7430                          /*IsStringLocation*/true,
7431                          getSpecifierRange(startSpecifier, specifierLen));
7432   }
7433 }
7434 
7435 void CheckFormatHandler::HandlePosition(const char *startPos,
7436                                         unsigned posLen) {
7437   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7438                                getLocationOfByte(startPos),
7439                                /*IsStringLocation*/true,
7440                                getSpecifierRange(startPos, posLen));
7441 }
7442 
7443 void
7444 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7445                                      analyze_format_string::PositionContext p) {
7446   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7447                          << (unsigned) p,
7448                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7449                        getSpecifierRange(startPos, posLen));
7450 }
7451 
7452 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7453                                             unsigned posLen) {
7454   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7455                                getLocationOfByte(startPos),
7456                                /*IsStringLocation*/true,
7457                                getSpecifierRange(startPos, posLen));
7458 }
7459 
7460 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7461   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7462     // The presence of a null character is likely an error.
7463     EmitFormatDiagnostic(
7464       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7465       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7466       getFormatStringRange());
7467   }
7468 }
7469 
7470 // Note that this may return NULL if there was an error parsing or building
7471 // one of the argument expressions.
7472 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7473   return Args[FirstDataArg + i];
7474 }
7475 
7476 void CheckFormatHandler::DoneProcessing() {
7477   // Does the number of data arguments exceed the number of
7478   // format conversions in the format string?
7479   if (!HasVAListArg) {
7480       // Find any arguments that weren't covered.
7481     CoveredArgs.flip();
7482     signed notCoveredArg = CoveredArgs.find_first();
7483     if (notCoveredArg >= 0) {
7484       assert((unsigned)notCoveredArg < NumDataArgs);
7485       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7486     } else {
7487       UncoveredArg.setAllCovered();
7488     }
7489   }
7490 }
7491 
7492 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7493                                    const Expr *ArgExpr) {
7494   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7495          "Invalid state");
7496 
7497   if (!ArgExpr)
7498     return;
7499 
7500   SourceLocation Loc = ArgExpr->getBeginLoc();
7501 
7502   if (S.getSourceManager().isInSystemMacro(Loc))
7503     return;
7504 
7505   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7506   for (auto E : DiagnosticExprs)
7507     PDiag << E->getSourceRange();
7508 
7509   CheckFormatHandler::EmitFormatDiagnostic(
7510                                   S, IsFunctionCall, DiagnosticExprs[0],
7511                                   PDiag, Loc, /*IsStringLocation*/false,
7512                                   DiagnosticExprs[0]->getSourceRange());
7513 }
7514 
7515 bool
7516 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7517                                                      SourceLocation Loc,
7518                                                      const char *startSpec,
7519                                                      unsigned specifierLen,
7520                                                      const char *csStart,
7521                                                      unsigned csLen) {
7522   bool keepGoing = true;
7523   if (argIndex < NumDataArgs) {
7524     // Consider the argument coverered, even though the specifier doesn't
7525     // make sense.
7526     CoveredArgs.set(argIndex);
7527   }
7528   else {
7529     // If argIndex exceeds the number of data arguments we
7530     // don't issue a warning because that is just a cascade of warnings (and
7531     // they may have intended '%%' anyway). We don't want to continue processing
7532     // the format string after this point, however, as we will like just get
7533     // gibberish when trying to match arguments.
7534     keepGoing = false;
7535   }
7536 
7537   StringRef Specifier(csStart, csLen);
7538 
7539   // If the specifier in non-printable, it could be the first byte of a UTF-8
7540   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7541   // hex value.
7542   std::string CodePointStr;
7543   if (!llvm::sys::locale::isPrint(*csStart)) {
7544     llvm::UTF32 CodePoint;
7545     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7546     const llvm::UTF8 *E =
7547         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7548     llvm::ConversionResult Result =
7549         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7550 
7551     if (Result != llvm::conversionOK) {
7552       unsigned char FirstChar = *csStart;
7553       CodePoint = (llvm::UTF32)FirstChar;
7554     }
7555 
7556     llvm::raw_string_ostream OS(CodePointStr);
7557     if (CodePoint < 256)
7558       OS << "\\x" << llvm::format("%02x", CodePoint);
7559     else if (CodePoint <= 0xFFFF)
7560       OS << "\\u" << llvm::format("%04x", CodePoint);
7561     else
7562       OS << "\\U" << llvm::format("%08x", CodePoint);
7563     OS.flush();
7564     Specifier = CodePointStr;
7565   }
7566 
7567   EmitFormatDiagnostic(
7568       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7569       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7570 
7571   return keepGoing;
7572 }
7573 
7574 void
7575 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7576                                                       const char *startSpec,
7577                                                       unsigned specifierLen) {
7578   EmitFormatDiagnostic(
7579     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7580     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7581 }
7582 
7583 bool
7584 CheckFormatHandler::CheckNumArgs(
7585   const analyze_format_string::FormatSpecifier &FS,
7586   const analyze_format_string::ConversionSpecifier &CS,
7587   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7588 
7589   if (argIndex >= NumDataArgs) {
7590     PartialDiagnostic PDiag = FS.usesPositionalArg()
7591       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7592            << (argIndex+1) << NumDataArgs)
7593       : S.PDiag(diag::warn_printf_insufficient_data_args);
7594     EmitFormatDiagnostic(
7595       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7596       getSpecifierRange(startSpecifier, specifierLen));
7597 
7598     // Since more arguments than conversion tokens are given, by extension
7599     // all arguments are covered, so mark this as so.
7600     UncoveredArg.setAllCovered();
7601     return false;
7602   }
7603   return true;
7604 }
7605 
7606 template<typename Range>
7607 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7608                                               SourceLocation Loc,
7609                                               bool IsStringLocation,
7610                                               Range StringRange,
7611                                               ArrayRef<FixItHint> FixIt) {
7612   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7613                        Loc, IsStringLocation, StringRange, FixIt);
7614 }
7615 
7616 /// If the format string is not within the function call, emit a note
7617 /// so that the function call and string are in diagnostic messages.
7618 ///
7619 /// \param InFunctionCall if true, the format string is within the function
7620 /// call and only one diagnostic message will be produced.  Otherwise, an
7621 /// extra note will be emitted pointing to location of the format string.
7622 ///
7623 /// \param ArgumentExpr the expression that is passed as the format string
7624 /// argument in the function call.  Used for getting locations when two
7625 /// diagnostics are emitted.
7626 ///
7627 /// \param PDiag the callee should already have provided any strings for the
7628 /// diagnostic message.  This function only adds locations and fixits
7629 /// to diagnostics.
7630 ///
7631 /// \param Loc primary location for diagnostic.  If two diagnostics are
7632 /// required, one will be at Loc and a new SourceLocation will be created for
7633 /// the other one.
7634 ///
7635 /// \param IsStringLocation if true, Loc points to the format string should be
7636 /// used for the note.  Otherwise, Loc points to the argument list and will
7637 /// be used with PDiag.
7638 ///
7639 /// \param StringRange some or all of the string to highlight.  This is
7640 /// templated so it can accept either a CharSourceRange or a SourceRange.
7641 ///
7642 /// \param FixIt optional fix it hint for the format string.
7643 template <typename Range>
7644 void CheckFormatHandler::EmitFormatDiagnostic(
7645     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7646     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7647     Range StringRange, ArrayRef<FixItHint> FixIt) {
7648   if (InFunctionCall) {
7649     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7650     D << StringRange;
7651     D << FixIt;
7652   } else {
7653     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7654       << ArgumentExpr->getSourceRange();
7655 
7656     const Sema::SemaDiagnosticBuilder &Note =
7657       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7658              diag::note_format_string_defined);
7659 
7660     Note << StringRange;
7661     Note << FixIt;
7662   }
7663 }
7664 
7665 //===--- CHECK: Printf format string checking ------------------------------===//
7666 
7667 namespace {
7668 
7669 class CheckPrintfHandler : public CheckFormatHandler {
7670 public:
7671   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7672                      const Expr *origFormatExpr,
7673                      const Sema::FormatStringType type, unsigned firstDataArg,
7674                      unsigned numDataArgs, bool isObjC, const char *beg,
7675                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7676                      unsigned formatIdx, bool inFunctionCall,
7677                      Sema::VariadicCallType CallType,
7678                      llvm::SmallBitVector &CheckedVarArgs,
7679                      UncoveredArgHandler &UncoveredArg)
7680       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7681                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7682                            inFunctionCall, CallType, CheckedVarArgs,
7683                            UncoveredArg) {}
7684 
7685   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7686 
7687   /// Returns true if '%@' specifiers are allowed in the format string.
7688   bool allowsObjCArg() const {
7689     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7690            FSType == Sema::FST_OSTrace;
7691   }
7692 
7693   bool HandleInvalidPrintfConversionSpecifier(
7694                                       const analyze_printf::PrintfSpecifier &FS,
7695                                       const char *startSpecifier,
7696                                       unsigned specifierLen) override;
7697 
7698   void handleInvalidMaskType(StringRef MaskType) override;
7699 
7700   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7701                              const char *startSpecifier,
7702                              unsigned specifierLen) override;
7703   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7704                        const char *StartSpecifier,
7705                        unsigned SpecifierLen,
7706                        const Expr *E);
7707 
7708   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7709                     const char *startSpecifier, unsigned specifierLen);
7710   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7711                            const analyze_printf::OptionalAmount &Amt,
7712                            unsigned type,
7713                            const char *startSpecifier, unsigned specifierLen);
7714   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7715                   const analyze_printf::OptionalFlag &flag,
7716                   const char *startSpecifier, unsigned specifierLen);
7717   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7718                          const analyze_printf::OptionalFlag &ignoredFlag,
7719                          const analyze_printf::OptionalFlag &flag,
7720                          const char *startSpecifier, unsigned specifierLen);
7721   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7722                            const Expr *E);
7723 
7724   void HandleEmptyObjCModifierFlag(const char *startFlag,
7725                                    unsigned flagLen) override;
7726 
7727   void HandleInvalidObjCModifierFlag(const char *startFlag,
7728                                             unsigned flagLen) override;
7729 
7730   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7731                                            const char *flagsEnd,
7732                                            const char *conversionPosition)
7733                                              override;
7734 };
7735 
7736 } // namespace
7737 
7738 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7739                                       const analyze_printf::PrintfSpecifier &FS,
7740                                       const char *startSpecifier,
7741                                       unsigned specifierLen) {
7742   const analyze_printf::PrintfConversionSpecifier &CS =
7743     FS.getConversionSpecifier();
7744 
7745   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7746                                           getLocationOfByte(CS.getStart()),
7747                                           startSpecifier, specifierLen,
7748                                           CS.getStart(), CS.getLength());
7749 }
7750 
7751 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7752   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7753 }
7754 
7755 bool CheckPrintfHandler::HandleAmount(
7756                                const analyze_format_string::OptionalAmount &Amt,
7757                                unsigned k, const char *startSpecifier,
7758                                unsigned specifierLen) {
7759   if (Amt.hasDataArgument()) {
7760     if (!HasVAListArg) {
7761       unsigned argIndex = Amt.getArgIndex();
7762       if (argIndex >= NumDataArgs) {
7763         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7764                                << k,
7765                              getLocationOfByte(Amt.getStart()),
7766                              /*IsStringLocation*/true,
7767                              getSpecifierRange(startSpecifier, specifierLen));
7768         // Don't do any more checking.  We will just emit
7769         // spurious errors.
7770         return false;
7771       }
7772 
7773       // Type check the data argument.  It should be an 'int'.
7774       // Although not in conformance with C99, we also allow the argument to be
7775       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7776       // doesn't emit a warning for that case.
7777       CoveredArgs.set(argIndex);
7778       const Expr *Arg = getDataArg(argIndex);
7779       if (!Arg)
7780         return false;
7781 
7782       QualType T = Arg->getType();
7783 
7784       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7785       assert(AT.isValid());
7786 
7787       if (!AT.matchesType(S.Context, T)) {
7788         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7789                                << k << AT.getRepresentativeTypeName(S.Context)
7790                                << T << Arg->getSourceRange(),
7791                              getLocationOfByte(Amt.getStart()),
7792                              /*IsStringLocation*/true,
7793                              getSpecifierRange(startSpecifier, specifierLen));
7794         // Don't do any more checking.  We will just emit
7795         // spurious errors.
7796         return false;
7797       }
7798     }
7799   }
7800   return true;
7801 }
7802 
7803 void CheckPrintfHandler::HandleInvalidAmount(
7804                                       const analyze_printf::PrintfSpecifier &FS,
7805                                       const analyze_printf::OptionalAmount &Amt,
7806                                       unsigned type,
7807                                       const char *startSpecifier,
7808                                       unsigned specifierLen) {
7809   const analyze_printf::PrintfConversionSpecifier &CS =
7810     FS.getConversionSpecifier();
7811 
7812   FixItHint fixit =
7813     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7814       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7815                                  Amt.getConstantLength()))
7816       : FixItHint();
7817 
7818   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7819                          << type << CS.toString(),
7820                        getLocationOfByte(Amt.getStart()),
7821                        /*IsStringLocation*/true,
7822                        getSpecifierRange(startSpecifier, specifierLen),
7823                        fixit);
7824 }
7825 
7826 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7827                                     const analyze_printf::OptionalFlag &flag,
7828                                     const char *startSpecifier,
7829                                     unsigned specifierLen) {
7830   // Warn about pointless flag with a fixit removal.
7831   const analyze_printf::PrintfConversionSpecifier &CS =
7832     FS.getConversionSpecifier();
7833   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7834                          << flag.toString() << CS.toString(),
7835                        getLocationOfByte(flag.getPosition()),
7836                        /*IsStringLocation*/true,
7837                        getSpecifierRange(startSpecifier, specifierLen),
7838                        FixItHint::CreateRemoval(
7839                          getSpecifierRange(flag.getPosition(), 1)));
7840 }
7841 
7842 void CheckPrintfHandler::HandleIgnoredFlag(
7843                                 const analyze_printf::PrintfSpecifier &FS,
7844                                 const analyze_printf::OptionalFlag &ignoredFlag,
7845                                 const analyze_printf::OptionalFlag &flag,
7846                                 const char *startSpecifier,
7847                                 unsigned specifierLen) {
7848   // Warn about ignored flag with a fixit removal.
7849   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7850                          << ignoredFlag.toString() << flag.toString(),
7851                        getLocationOfByte(ignoredFlag.getPosition()),
7852                        /*IsStringLocation*/true,
7853                        getSpecifierRange(startSpecifier, specifierLen),
7854                        FixItHint::CreateRemoval(
7855                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7856 }
7857 
7858 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7859                                                      unsigned flagLen) {
7860   // Warn about an empty flag.
7861   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7862                        getLocationOfByte(startFlag),
7863                        /*IsStringLocation*/true,
7864                        getSpecifierRange(startFlag, flagLen));
7865 }
7866 
7867 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7868                                                        unsigned flagLen) {
7869   // Warn about an invalid flag.
7870   auto Range = getSpecifierRange(startFlag, flagLen);
7871   StringRef flag(startFlag, flagLen);
7872   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7873                       getLocationOfByte(startFlag),
7874                       /*IsStringLocation*/true,
7875                       Range, FixItHint::CreateRemoval(Range));
7876 }
7877 
7878 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7879     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7880     // Warn about using '[...]' without a '@' conversion.
7881     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7882     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7883     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7884                          getLocationOfByte(conversionPosition),
7885                          /*IsStringLocation*/true,
7886                          Range, FixItHint::CreateRemoval(Range));
7887 }
7888 
7889 // Determines if the specified is a C++ class or struct containing
7890 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7891 // "c_str()").
7892 template<typename MemberKind>
7893 static llvm::SmallPtrSet<MemberKind*, 1>
7894 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7895   const RecordType *RT = Ty->getAs<RecordType>();
7896   llvm::SmallPtrSet<MemberKind*, 1> Results;
7897 
7898   if (!RT)
7899     return Results;
7900   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7901   if (!RD || !RD->getDefinition())
7902     return Results;
7903 
7904   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7905                  Sema::LookupMemberName);
7906   R.suppressDiagnostics();
7907 
7908   // We just need to include all members of the right kind turned up by the
7909   // filter, at this point.
7910   if (S.LookupQualifiedName(R, RT->getDecl()))
7911     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7912       NamedDecl *decl = (*I)->getUnderlyingDecl();
7913       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7914         Results.insert(FK);
7915     }
7916   return Results;
7917 }
7918 
7919 /// Check if we could call '.c_str()' on an object.
7920 ///
7921 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7922 /// allow the call, or if it would be ambiguous).
7923 bool Sema::hasCStrMethod(const Expr *E) {
7924   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7925 
7926   MethodSet Results =
7927       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7928   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7929        MI != ME; ++MI)
7930     if ((*MI)->getMinRequiredArguments() == 0)
7931       return true;
7932   return false;
7933 }
7934 
7935 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7936 // better diagnostic if so. AT is assumed to be valid.
7937 // Returns true when a c_str() conversion method is found.
7938 bool CheckPrintfHandler::checkForCStrMembers(
7939     const analyze_printf::ArgType &AT, const Expr *E) {
7940   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7941 
7942   MethodSet Results =
7943       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7944 
7945   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7946        MI != ME; ++MI) {
7947     const CXXMethodDecl *Method = *MI;
7948     if (Method->getMinRequiredArguments() == 0 &&
7949         AT.matchesType(S.Context, Method->getReturnType())) {
7950       // FIXME: Suggest parens if the expression needs them.
7951       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7952       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7953           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7954       return true;
7955     }
7956   }
7957 
7958   return false;
7959 }
7960 
7961 bool
7962 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7963                                             &FS,
7964                                           const char *startSpecifier,
7965                                           unsigned specifierLen) {
7966   using namespace analyze_format_string;
7967   using namespace analyze_printf;
7968 
7969   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7970 
7971   if (FS.consumesDataArgument()) {
7972     if (atFirstArg) {
7973         atFirstArg = false;
7974         usesPositionalArgs = FS.usesPositionalArg();
7975     }
7976     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7977       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7978                                         startSpecifier, specifierLen);
7979       return false;
7980     }
7981   }
7982 
7983   // First check if the field width, precision, and conversion specifier
7984   // have matching data arguments.
7985   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7986                     startSpecifier, specifierLen)) {
7987     return false;
7988   }
7989 
7990   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7991                     startSpecifier, specifierLen)) {
7992     return false;
7993   }
7994 
7995   if (!CS.consumesDataArgument()) {
7996     // FIXME: Technically specifying a precision or field width here
7997     // makes no sense.  Worth issuing a warning at some point.
7998     return true;
7999   }
8000 
8001   // Consume the argument.
8002   unsigned argIndex = FS.getArgIndex();
8003   if (argIndex < NumDataArgs) {
8004     // The check to see if the argIndex is valid will come later.
8005     // We set the bit here because we may exit early from this
8006     // function if we encounter some other error.
8007     CoveredArgs.set(argIndex);
8008   }
8009 
8010   // FreeBSD kernel extensions.
8011   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8012       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8013     // We need at least two arguments.
8014     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8015       return false;
8016 
8017     // Claim the second argument.
8018     CoveredArgs.set(argIndex + 1);
8019 
8020     // Type check the first argument (int for %b, pointer for %D)
8021     const Expr *Ex = getDataArg(argIndex);
8022     const analyze_printf::ArgType &AT =
8023       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8024         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8025     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8026       EmitFormatDiagnostic(
8027           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8028               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8029               << false << Ex->getSourceRange(),
8030           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8031           getSpecifierRange(startSpecifier, specifierLen));
8032 
8033     // Type check the second argument (char * for both %b and %D)
8034     Ex = getDataArg(argIndex + 1);
8035     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8036     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8037       EmitFormatDiagnostic(
8038           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8039               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8040               << false << Ex->getSourceRange(),
8041           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8042           getSpecifierRange(startSpecifier, specifierLen));
8043 
8044      return true;
8045   }
8046 
8047   // Check for using an Objective-C specific conversion specifier
8048   // in a non-ObjC literal.
8049   if (!allowsObjCArg() && CS.isObjCArg()) {
8050     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8051                                                   specifierLen);
8052   }
8053 
8054   // %P can only be used with os_log.
8055   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8056     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8057                                                   specifierLen);
8058   }
8059 
8060   // %n is not allowed with os_log.
8061   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8062     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8063                          getLocationOfByte(CS.getStart()),
8064                          /*IsStringLocation*/ false,
8065                          getSpecifierRange(startSpecifier, specifierLen));
8066 
8067     return true;
8068   }
8069 
8070   // Only scalars are allowed for os_trace.
8071   if (FSType == Sema::FST_OSTrace &&
8072       (CS.getKind() == ConversionSpecifier::PArg ||
8073        CS.getKind() == ConversionSpecifier::sArg ||
8074        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8075     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8076                                                   specifierLen);
8077   }
8078 
8079   // Check for use of public/private annotation outside of os_log().
8080   if (FSType != Sema::FST_OSLog) {
8081     if (FS.isPublic().isSet()) {
8082       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8083                                << "public",
8084                            getLocationOfByte(FS.isPublic().getPosition()),
8085                            /*IsStringLocation*/ false,
8086                            getSpecifierRange(startSpecifier, specifierLen));
8087     }
8088     if (FS.isPrivate().isSet()) {
8089       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8090                                << "private",
8091                            getLocationOfByte(FS.isPrivate().getPosition()),
8092                            /*IsStringLocation*/ false,
8093                            getSpecifierRange(startSpecifier, specifierLen));
8094     }
8095   }
8096 
8097   // Check for invalid use of field width
8098   if (!FS.hasValidFieldWidth()) {
8099     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8100         startSpecifier, specifierLen);
8101   }
8102 
8103   // Check for invalid use of precision
8104   if (!FS.hasValidPrecision()) {
8105     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8106         startSpecifier, specifierLen);
8107   }
8108 
8109   // Precision is mandatory for %P specifier.
8110   if (CS.getKind() == ConversionSpecifier::PArg &&
8111       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8112     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8113                          getLocationOfByte(startSpecifier),
8114                          /*IsStringLocation*/ false,
8115                          getSpecifierRange(startSpecifier, specifierLen));
8116   }
8117 
8118   // Check each flag does not conflict with any other component.
8119   if (!FS.hasValidThousandsGroupingPrefix())
8120     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8121   if (!FS.hasValidLeadingZeros())
8122     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8123   if (!FS.hasValidPlusPrefix())
8124     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8125   if (!FS.hasValidSpacePrefix())
8126     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8127   if (!FS.hasValidAlternativeForm())
8128     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8129   if (!FS.hasValidLeftJustified())
8130     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8131 
8132   // Check that flags are not ignored by another flag
8133   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8134     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8135         startSpecifier, specifierLen);
8136   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8137     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8138             startSpecifier, specifierLen);
8139 
8140   // Check the length modifier is valid with the given conversion specifier.
8141   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8142                                  S.getLangOpts()))
8143     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8144                                 diag::warn_format_nonsensical_length);
8145   else if (!FS.hasStandardLengthModifier())
8146     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8147   else if (!FS.hasStandardLengthConversionCombination())
8148     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8149                                 diag::warn_format_non_standard_conversion_spec);
8150 
8151   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8152     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8153 
8154   // The remaining checks depend on the data arguments.
8155   if (HasVAListArg)
8156     return true;
8157 
8158   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8159     return false;
8160 
8161   const Expr *Arg = getDataArg(argIndex);
8162   if (!Arg)
8163     return true;
8164 
8165   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8166 }
8167 
8168 static bool requiresParensToAddCast(const Expr *E) {
8169   // FIXME: We should have a general way to reason about operator
8170   // precedence and whether parens are actually needed here.
8171   // Take care of a few common cases where they aren't.
8172   const Expr *Inside = E->IgnoreImpCasts();
8173   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8174     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8175 
8176   switch (Inside->getStmtClass()) {
8177   case Stmt::ArraySubscriptExprClass:
8178   case Stmt::CallExprClass:
8179   case Stmt::CharacterLiteralClass:
8180   case Stmt::CXXBoolLiteralExprClass:
8181   case Stmt::DeclRefExprClass:
8182   case Stmt::FloatingLiteralClass:
8183   case Stmt::IntegerLiteralClass:
8184   case Stmt::MemberExprClass:
8185   case Stmt::ObjCArrayLiteralClass:
8186   case Stmt::ObjCBoolLiteralExprClass:
8187   case Stmt::ObjCBoxedExprClass:
8188   case Stmt::ObjCDictionaryLiteralClass:
8189   case Stmt::ObjCEncodeExprClass:
8190   case Stmt::ObjCIvarRefExprClass:
8191   case Stmt::ObjCMessageExprClass:
8192   case Stmt::ObjCPropertyRefExprClass:
8193   case Stmt::ObjCStringLiteralClass:
8194   case Stmt::ObjCSubscriptRefExprClass:
8195   case Stmt::ParenExprClass:
8196   case Stmt::StringLiteralClass:
8197   case Stmt::UnaryOperatorClass:
8198     return false;
8199   default:
8200     return true;
8201   }
8202 }
8203 
8204 static std::pair<QualType, StringRef>
8205 shouldNotPrintDirectly(const ASTContext &Context,
8206                        QualType IntendedTy,
8207                        const Expr *E) {
8208   // Use a 'while' to peel off layers of typedefs.
8209   QualType TyTy = IntendedTy;
8210   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8211     StringRef Name = UserTy->getDecl()->getName();
8212     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8213       .Case("CFIndex", Context.getNSIntegerType())
8214       .Case("NSInteger", Context.getNSIntegerType())
8215       .Case("NSUInteger", Context.getNSUIntegerType())
8216       .Case("SInt32", Context.IntTy)
8217       .Case("UInt32", Context.UnsignedIntTy)
8218       .Default(QualType());
8219 
8220     if (!CastTy.isNull())
8221       return std::make_pair(CastTy, Name);
8222 
8223     TyTy = UserTy->desugar();
8224   }
8225 
8226   // Strip parens if necessary.
8227   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8228     return shouldNotPrintDirectly(Context,
8229                                   PE->getSubExpr()->getType(),
8230                                   PE->getSubExpr());
8231 
8232   // If this is a conditional expression, then its result type is constructed
8233   // via usual arithmetic conversions and thus there might be no necessary
8234   // typedef sugar there.  Recurse to operands to check for NSInteger &
8235   // Co. usage condition.
8236   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8237     QualType TrueTy, FalseTy;
8238     StringRef TrueName, FalseName;
8239 
8240     std::tie(TrueTy, TrueName) =
8241       shouldNotPrintDirectly(Context,
8242                              CO->getTrueExpr()->getType(),
8243                              CO->getTrueExpr());
8244     std::tie(FalseTy, FalseName) =
8245       shouldNotPrintDirectly(Context,
8246                              CO->getFalseExpr()->getType(),
8247                              CO->getFalseExpr());
8248 
8249     if (TrueTy == FalseTy)
8250       return std::make_pair(TrueTy, TrueName);
8251     else if (TrueTy.isNull())
8252       return std::make_pair(FalseTy, FalseName);
8253     else if (FalseTy.isNull())
8254       return std::make_pair(TrueTy, TrueName);
8255   }
8256 
8257   return std::make_pair(QualType(), StringRef());
8258 }
8259 
8260 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8261 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8262 /// type do not count.
8263 static bool
8264 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8265   QualType From = ICE->getSubExpr()->getType();
8266   QualType To = ICE->getType();
8267   // It's an integer promotion if the destination type is the promoted
8268   // source type.
8269   if (ICE->getCastKind() == CK_IntegralCast &&
8270       From->isPromotableIntegerType() &&
8271       S.Context.getPromotedIntegerType(From) == To)
8272     return true;
8273   // Look through vector types, since we do default argument promotion for
8274   // those in OpenCL.
8275   if (const auto *VecTy = From->getAs<ExtVectorType>())
8276     From = VecTy->getElementType();
8277   if (const auto *VecTy = To->getAs<ExtVectorType>())
8278     To = VecTy->getElementType();
8279   // It's a floating promotion if the source type is a lower rank.
8280   return ICE->getCastKind() == CK_FloatingCast &&
8281          S.Context.getFloatingTypeOrder(From, To) < 0;
8282 }
8283 
8284 bool
8285 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8286                                     const char *StartSpecifier,
8287                                     unsigned SpecifierLen,
8288                                     const Expr *E) {
8289   using namespace analyze_format_string;
8290   using namespace analyze_printf;
8291 
8292   // Now type check the data expression that matches the
8293   // format specifier.
8294   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8295   if (!AT.isValid())
8296     return true;
8297 
8298   QualType ExprTy = E->getType();
8299   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8300     ExprTy = TET->getUnderlyingExpr()->getType();
8301   }
8302 
8303   // Diagnose attempts to print a boolean value as a character. Unlike other
8304   // -Wformat diagnostics, this is fine from a type perspective, but it still
8305   // doesn't make sense.
8306   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8307       E->isKnownToHaveBooleanValue()) {
8308     const CharSourceRange &CSR =
8309         getSpecifierRange(StartSpecifier, SpecifierLen);
8310     SmallString<4> FSString;
8311     llvm::raw_svector_ostream os(FSString);
8312     FS.toString(os);
8313     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8314                              << FSString,
8315                          E->getExprLoc(), false, CSR);
8316     return true;
8317   }
8318 
8319   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8320   if (Match == analyze_printf::ArgType::Match)
8321     return true;
8322 
8323   // Look through argument promotions for our error message's reported type.
8324   // This includes the integral and floating promotions, but excludes array
8325   // and function pointer decay (seeing that an argument intended to be a
8326   // string has type 'char [6]' is probably more confusing than 'char *') and
8327   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8328   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8329     if (isArithmeticArgumentPromotion(S, ICE)) {
8330       E = ICE->getSubExpr();
8331       ExprTy = E->getType();
8332 
8333       // Check if we didn't match because of an implicit cast from a 'char'
8334       // or 'short' to an 'int'.  This is done because printf is a varargs
8335       // function.
8336       if (ICE->getType() == S.Context.IntTy ||
8337           ICE->getType() == S.Context.UnsignedIntTy) {
8338         // All further checking is done on the subexpression
8339         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8340             AT.matchesType(S.Context, ExprTy);
8341         if (ImplicitMatch == analyze_printf::ArgType::Match)
8342           return true;
8343         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8344             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8345           Match = ImplicitMatch;
8346       }
8347     }
8348   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8349     // Special case for 'a', which has type 'int' in C.
8350     // Note, however, that we do /not/ want to treat multibyte constants like
8351     // 'MooV' as characters! This form is deprecated but still exists.
8352     if (ExprTy == S.Context.IntTy)
8353       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8354         ExprTy = S.Context.CharTy;
8355   }
8356 
8357   // Look through enums to their underlying type.
8358   bool IsEnum = false;
8359   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8360     ExprTy = EnumTy->getDecl()->getIntegerType();
8361     IsEnum = true;
8362   }
8363 
8364   // %C in an Objective-C context prints a unichar, not a wchar_t.
8365   // If the argument is an integer of some kind, believe the %C and suggest
8366   // a cast instead of changing the conversion specifier.
8367   QualType IntendedTy = ExprTy;
8368   if (isObjCContext() &&
8369       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8370     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8371         !ExprTy->isCharType()) {
8372       // 'unichar' is defined as a typedef of unsigned short, but we should
8373       // prefer using the typedef if it is visible.
8374       IntendedTy = S.Context.UnsignedShortTy;
8375 
8376       // While we are here, check if the value is an IntegerLiteral that happens
8377       // to be within the valid range.
8378       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8379         const llvm::APInt &V = IL->getValue();
8380         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8381           return true;
8382       }
8383 
8384       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8385                           Sema::LookupOrdinaryName);
8386       if (S.LookupName(Result, S.getCurScope())) {
8387         NamedDecl *ND = Result.getFoundDecl();
8388         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8389           if (TD->getUnderlyingType() == IntendedTy)
8390             IntendedTy = S.Context.getTypedefType(TD);
8391       }
8392     }
8393   }
8394 
8395   // Special-case some of Darwin's platform-independence types by suggesting
8396   // casts to primitive types that are known to be large enough.
8397   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8398   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8399     QualType CastTy;
8400     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8401     if (!CastTy.isNull()) {
8402       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8403       // (long in ASTContext). Only complain to pedants.
8404       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8405           (AT.isSizeT() || AT.isPtrdiffT()) &&
8406           AT.matchesType(S.Context, CastTy))
8407         Match = ArgType::NoMatchPedantic;
8408       IntendedTy = CastTy;
8409       ShouldNotPrintDirectly = true;
8410     }
8411   }
8412 
8413   // We may be able to offer a FixItHint if it is a supported type.
8414   PrintfSpecifier fixedFS = FS;
8415   bool Success =
8416       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8417 
8418   if (Success) {
8419     // Get the fix string from the fixed format specifier
8420     SmallString<16> buf;
8421     llvm::raw_svector_ostream os(buf);
8422     fixedFS.toString(os);
8423 
8424     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8425 
8426     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8427       unsigned Diag;
8428       switch (Match) {
8429       case ArgType::Match: llvm_unreachable("expected non-matching");
8430       case ArgType::NoMatchPedantic:
8431         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8432         break;
8433       case ArgType::NoMatchTypeConfusion:
8434         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8435         break;
8436       case ArgType::NoMatch:
8437         Diag = diag::warn_format_conversion_argument_type_mismatch;
8438         break;
8439       }
8440 
8441       // In this case, the specifier is wrong and should be changed to match
8442       // the argument.
8443       EmitFormatDiagnostic(S.PDiag(Diag)
8444                                << AT.getRepresentativeTypeName(S.Context)
8445                                << IntendedTy << IsEnum << E->getSourceRange(),
8446                            E->getBeginLoc(),
8447                            /*IsStringLocation*/ false, SpecRange,
8448                            FixItHint::CreateReplacement(SpecRange, os.str()));
8449     } else {
8450       // The canonical type for formatting this value is different from the
8451       // actual type of the expression. (This occurs, for example, with Darwin's
8452       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8453       // should be printed as 'long' for 64-bit compatibility.)
8454       // Rather than emitting a normal format/argument mismatch, we want to
8455       // add a cast to the recommended type (and correct the format string
8456       // if necessary).
8457       SmallString<16> CastBuf;
8458       llvm::raw_svector_ostream CastFix(CastBuf);
8459       CastFix << "(";
8460       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8461       CastFix << ")";
8462 
8463       SmallVector<FixItHint,4> Hints;
8464       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8465         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8466 
8467       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8468         // If there's already a cast present, just replace it.
8469         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8470         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8471 
8472       } else if (!requiresParensToAddCast(E)) {
8473         // If the expression has high enough precedence,
8474         // just write the C-style cast.
8475         Hints.push_back(
8476             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8477       } else {
8478         // Otherwise, add parens around the expression as well as the cast.
8479         CastFix << "(";
8480         Hints.push_back(
8481             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8482 
8483         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8484         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8485       }
8486 
8487       if (ShouldNotPrintDirectly) {
8488         // The expression has a type that should not be printed directly.
8489         // We extract the name from the typedef because we don't want to show
8490         // the underlying type in the diagnostic.
8491         StringRef Name;
8492         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8493           Name = TypedefTy->getDecl()->getName();
8494         else
8495           Name = CastTyName;
8496         unsigned Diag = Match == ArgType::NoMatchPedantic
8497                             ? diag::warn_format_argument_needs_cast_pedantic
8498                             : diag::warn_format_argument_needs_cast;
8499         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8500                                            << E->getSourceRange(),
8501                              E->getBeginLoc(), /*IsStringLocation=*/false,
8502                              SpecRange, Hints);
8503       } else {
8504         // In this case, the expression could be printed using a different
8505         // specifier, but we've decided that the specifier is probably correct
8506         // and we should cast instead. Just use the normal warning message.
8507         EmitFormatDiagnostic(
8508             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8509                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8510                 << E->getSourceRange(),
8511             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8512       }
8513     }
8514   } else {
8515     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8516                                                    SpecifierLen);
8517     // Since the warning for passing non-POD types to variadic functions
8518     // was deferred until now, we emit a warning for non-POD
8519     // arguments here.
8520     switch (S.isValidVarArgType(ExprTy)) {
8521     case Sema::VAK_Valid:
8522     case Sema::VAK_ValidInCXX11: {
8523       unsigned Diag;
8524       switch (Match) {
8525       case ArgType::Match: llvm_unreachable("expected non-matching");
8526       case ArgType::NoMatchPedantic:
8527         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8528         break;
8529       case ArgType::NoMatchTypeConfusion:
8530         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8531         break;
8532       case ArgType::NoMatch:
8533         Diag = diag::warn_format_conversion_argument_type_mismatch;
8534         break;
8535       }
8536 
8537       EmitFormatDiagnostic(
8538           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8539                         << IsEnum << CSR << E->getSourceRange(),
8540           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8541       break;
8542     }
8543     case Sema::VAK_Undefined:
8544     case Sema::VAK_MSVCUndefined:
8545       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8546                                << S.getLangOpts().CPlusPlus11 << ExprTy
8547                                << CallType
8548                                << AT.getRepresentativeTypeName(S.Context) << CSR
8549                                << E->getSourceRange(),
8550                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8551       checkForCStrMembers(AT, E);
8552       break;
8553 
8554     case Sema::VAK_Invalid:
8555       if (ExprTy->isObjCObjectType())
8556         EmitFormatDiagnostic(
8557             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8558                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8559                 << AT.getRepresentativeTypeName(S.Context) << CSR
8560                 << E->getSourceRange(),
8561             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8562       else
8563         // FIXME: If this is an initializer list, suggest removing the braces
8564         // or inserting a cast to the target type.
8565         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8566             << isa<InitListExpr>(E) << ExprTy << CallType
8567             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8568       break;
8569     }
8570 
8571     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8572            "format string specifier index out of range");
8573     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8574   }
8575 
8576   return true;
8577 }
8578 
8579 //===--- CHECK: Scanf format string checking ------------------------------===//
8580 
8581 namespace {
8582 
8583 class CheckScanfHandler : public CheckFormatHandler {
8584 public:
8585   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8586                     const Expr *origFormatExpr, Sema::FormatStringType type,
8587                     unsigned firstDataArg, unsigned numDataArgs,
8588                     const char *beg, bool hasVAListArg,
8589                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8590                     bool inFunctionCall, Sema::VariadicCallType CallType,
8591                     llvm::SmallBitVector &CheckedVarArgs,
8592                     UncoveredArgHandler &UncoveredArg)
8593       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8594                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8595                            inFunctionCall, CallType, CheckedVarArgs,
8596                            UncoveredArg) {}
8597 
8598   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8599                             const char *startSpecifier,
8600                             unsigned specifierLen) override;
8601 
8602   bool HandleInvalidScanfConversionSpecifier(
8603           const analyze_scanf::ScanfSpecifier &FS,
8604           const char *startSpecifier,
8605           unsigned specifierLen) override;
8606 
8607   void HandleIncompleteScanList(const char *start, const char *end) override;
8608 };
8609 
8610 } // namespace
8611 
8612 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8613                                                  const char *end) {
8614   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8615                        getLocationOfByte(end), /*IsStringLocation*/true,
8616                        getSpecifierRange(start, end - start));
8617 }
8618 
8619 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8620                                         const analyze_scanf::ScanfSpecifier &FS,
8621                                         const char *startSpecifier,
8622                                         unsigned specifierLen) {
8623   const analyze_scanf::ScanfConversionSpecifier &CS =
8624     FS.getConversionSpecifier();
8625 
8626   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8627                                           getLocationOfByte(CS.getStart()),
8628                                           startSpecifier, specifierLen,
8629                                           CS.getStart(), CS.getLength());
8630 }
8631 
8632 bool CheckScanfHandler::HandleScanfSpecifier(
8633                                        const analyze_scanf::ScanfSpecifier &FS,
8634                                        const char *startSpecifier,
8635                                        unsigned specifierLen) {
8636   using namespace analyze_scanf;
8637   using namespace analyze_format_string;
8638 
8639   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8640 
8641   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8642   // be used to decide if we are using positional arguments consistently.
8643   if (FS.consumesDataArgument()) {
8644     if (atFirstArg) {
8645       atFirstArg = false;
8646       usesPositionalArgs = FS.usesPositionalArg();
8647     }
8648     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8649       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8650                                         startSpecifier, specifierLen);
8651       return false;
8652     }
8653   }
8654 
8655   // Check if the field with is non-zero.
8656   const OptionalAmount &Amt = FS.getFieldWidth();
8657   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8658     if (Amt.getConstantAmount() == 0) {
8659       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8660                                                    Amt.getConstantLength());
8661       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8662                            getLocationOfByte(Amt.getStart()),
8663                            /*IsStringLocation*/true, R,
8664                            FixItHint::CreateRemoval(R));
8665     }
8666   }
8667 
8668   if (!FS.consumesDataArgument()) {
8669     // FIXME: Technically specifying a precision or field width here
8670     // makes no sense.  Worth issuing a warning at some point.
8671     return true;
8672   }
8673 
8674   // Consume the argument.
8675   unsigned argIndex = FS.getArgIndex();
8676   if (argIndex < NumDataArgs) {
8677       // The check to see if the argIndex is valid will come later.
8678       // We set the bit here because we may exit early from this
8679       // function if we encounter some other error.
8680     CoveredArgs.set(argIndex);
8681   }
8682 
8683   // Check the length modifier is valid with the given conversion specifier.
8684   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8685                                  S.getLangOpts()))
8686     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8687                                 diag::warn_format_nonsensical_length);
8688   else if (!FS.hasStandardLengthModifier())
8689     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8690   else if (!FS.hasStandardLengthConversionCombination())
8691     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8692                                 diag::warn_format_non_standard_conversion_spec);
8693 
8694   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8695     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8696 
8697   // The remaining checks depend on the data arguments.
8698   if (HasVAListArg)
8699     return true;
8700 
8701   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8702     return false;
8703 
8704   // Check that the argument type matches the format specifier.
8705   const Expr *Ex = getDataArg(argIndex);
8706   if (!Ex)
8707     return true;
8708 
8709   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8710 
8711   if (!AT.isValid()) {
8712     return true;
8713   }
8714 
8715   analyze_format_string::ArgType::MatchKind Match =
8716       AT.matchesType(S.Context, Ex->getType());
8717   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8718   if (Match == analyze_format_string::ArgType::Match)
8719     return true;
8720 
8721   ScanfSpecifier fixedFS = FS;
8722   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8723                                  S.getLangOpts(), S.Context);
8724 
8725   unsigned Diag =
8726       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8727                : diag::warn_format_conversion_argument_type_mismatch;
8728 
8729   if (Success) {
8730     // Get the fix string from the fixed format specifier.
8731     SmallString<128> buf;
8732     llvm::raw_svector_ostream os(buf);
8733     fixedFS.toString(os);
8734 
8735     EmitFormatDiagnostic(
8736         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8737                       << Ex->getType() << false << Ex->getSourceRange(),
8738         Ex->getBeginLoc(),
8739         /*IsStringLocation*/ false,
8740         getSpecifierRange(startSpecifier, specifierLen),
8741         FixItHint::CreateReplacement(
8742             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8743   } else {
8744     EmitFormatDiagnostic(S.PDiag(Diag)
8745                              << AT.getRepresentativeTypeName(S.Context)
8746                              << Ex->getType() << false << Ex->getSourceRange(),
8747                          Ex->getBeginLoc(),
8748                          /*IsStringLocation*/ false,
8749                          getSpecifierRange(startSpecifier, specifierLen));
8750   }
8751 
8752   return true;
8753 }
8754 
8755 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8756                               const Expr *OrigFormatExpr,
8757                               ArrayRef<const Expr *> Args,
8758                               bool HasVAListArg, unsigned format_idx,
8759                               unsigned firstDataArg,
8760                               Sema::FormatStringType Type,
8761                               bool inFunctionCall,
8762                               Sema::VariadicCallType CallType,
8763                               llvm::SmallBitVector &CheckedVarArgs,
8764                               UncoveredArgHandler &UncoveredArg,
8765                               bool IgnoreStringsWithoutSpecifiers) {
8766   // CHECK: is the format string a wide literal?
8767   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8768     CheckFormatHandler::EmitFormatDiagnostic(
8769         S, inFunctionCall, Args[format_idx],
8770         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8771         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8772     return;
8773   }
8774 
8775   // Str - The format string.  NOTE: this is NOT null-terminated!
8776   StringRef StrRef = FExpr->getString();
8777   const char *Str = StrRef.data();
8778   // Account for cases where the string literal is truncated in a declaration.
8779   const ConstantArrayType *T =
8780     S.Context.getAsConstantArrayType(FExpr->getType());
8781   assert(T && "String literal not of constant array type!");
8782   size_t TypeSize = T->getSize().getZExtValue();
8783   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8784   const unsigned numDataArgs = Args.size() - firstDataArg;
8785 
8786   if (IgnoreStringsWithoutSpecifiers &&
8787       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8788           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8789     return;
8790 
8791   // Emit a warning if the string literal is truncated and does not contain an
8792   // embedded null character.
8793   if (TypeSize <= StrRef.size() &&
8794       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8795     CheckFormatHandler::EmitFormatDiagnostic(
8796         S, inFunctionCall, Args[format_idx],
8797         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8798         FExpr->getBeginLoc(),
8799         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8800     return;
8801   }
8802 
8803   // CHECK: empty format string?
8804   if (StrLen == 0 && numDataArgs > 0) {
8805     CheckFormatHandler::EmitFormatDiagnostic(
8806         S, inFunctionCall, Args[format_idx],
8807         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8808         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8809     return;
8810   }
8811 
8812   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8813       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8814       Type == Sema::FST_OSTrace) {
8815     CheckPrintfHandler H(
8816         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8817         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8818         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8819         CheckedVarArgs, UncoveredArg);
8820 
8821     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8822                                                   S.getLangOpts(),
8823                                                   S.Context.getTargetInfo(),
8824                                             Type == Sema::FST_FreeBSDKPrintf))
8825       H.DoneProcessing();
8826   } else if (Type == Sema::FST_Scanf) {
8827     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8828                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8829                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8830 
8831     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8832                                                  S.getLangOpts(),
8833                                                  S.Context.getTargetInfo()))
8834       H.DoneProcessing();
8835   } // TODO: handle other formats
8836 }
8837 
8838 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8839   // Str - The format string.  NOTE: this is NOT null-terminated!
8840   StringRef StrRef = FExpr->getString();
8841   const char *Str = StrRef.data();
8842   // Account for cases where the string literal is truncated in a declaration.
8843   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8844   assert(T && "String literal not of constant array type!");
8845   size_t TypeSize = T->getSize().getZExtValue();
8846   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8847   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8848                                                          getLangOpts(),
8849                                                          Context.getTargetInfo());
8850 }
8851 
8852 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8853 
8854 // Returns the related absolute value function that is larger, of 0 if one
8855 // does not exist.
8856 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8857   switch (AbsFunction) {
8858   default:
8859     return 0;
8860 
8861   case Builtin::BI__builtin_abs:
8862     return Builtin::BI__builtin_labs;
8863   case Builtin::BI__builtin_labs:
8864     return Builtin::BI__builtin_llabs;
8865   case Builtin::BI__builtin_llabs:
8866     return 0;
8867 
8868   case Builtin::BI__builtin_fabsf:
8869     return Builtin::BI__builtin_fabs;
8870   case Builtin::BI__builtin_fabs:
8871     return Builtin::BI__builtin_fabsl;
8872   case Builtin::BI__builtin_fabsl:
8873     return 0;
8874 
8875   case Builtin::BI__builtin_cabsf:
8876     return Builtin::BI__builtin_cabs;
8877   case Builtin::BI__builtin_cabs:
8878     return Builtin::BI__builtin_cabsl;
8879   case Builtin::BI__builtin_cabsl:
8880     return 0;
8881 
8882   case Builtin::BIabs:
8883     return Builtin::BIlabs;
8884   case Builtin::BIlabs:
8885     return Builtin::BIllabs;
8886   case Builtin::BIllabs:
8887     return 0;
8888 
8889   case Builtin::BIfabsf:
8890     return Builtin::BIfabs;
8891   case Builtin::BIfabs:
8892     return Builtin::BIfabsl;
8893   case Builtin::BIfabsl:
8894     return 0;
8895 
8896   case Builtin::BIcabsf:
8897    return Builtin::BIcabs;
8898   case Builtin::BIcabs:
8899     return Builtin::BIcabsl;
8900   case Builtin::BIcabsl:
8901     return 0;
8902   }
8903 }
8904 
8905 // Returns the argument type of the absolute value function.
8906 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8907                                              unsigned AbsType) {
8908   if (AbsType == 0)
8909     return QualType();
8910 
8911   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8912   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8913   if (Error != ASTContext::GE_None)
8914     return QualType();
8915 
8916   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8917   if (!FT)
8918     return QualType();
8919 
8920   if (FT->getNumParams() != 1)
8921     return QualType();
8922 
8923   return FT->getParamType(0);
8924 }
8925 
8926 // Returns the best absolute value function, or zero, based on type and
8927 // current absolute value function.
8928 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8929                                    unsigned AbsFunctionKind) {
8930   unsigned BestKind = 0;
8931   uint64_t ArgSize = Context.getTypeSize(ArgType);
8932   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8933        Kind = getLargerAbsoluteValueFunction(Kind)) {
8934     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8935     if (Context.getTypeSize(ParamType) >= ArgSize) {
8936       if (BestKind == 0)
8937         BestKind = Kind;
8938       else if (Context.hasSameType(ParamType, ArgType)) {
8939         BestKind = Kind;
8940         break;
8941       }
8942     }
8943   }
8944   return BestKind;
8945 }
8946 
8947 enum AbsoluteValueKind {
8948   AVK_Integer,
8949   AVK_Floating,
8950   AVK_Complex
8951 };
8952 
8953 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8954   if (T->isIntegralOrEnumerationType())
8955     return AVK_Integer;
8956   if (T->isRealFloatingType())
8957     return AVK_Floating;
8958   if (T->isAnyComplexType())
8959     return AVK_Complex;
8960 
8961   llvm_unreachable("Type not integer, floating, or complex");
8962 }
8963 
8964 // Changes the absolute value function to a different type.  Preserves whether
8965 // the function is a builtin.
8966 static unsigned changeAbsFunction(unsigned AbsKind,
8967                                   AbsoluteValueKind ValueKind) {
8968   switch (ValueKind) {
8969   case AVK_Integer:
8970     switch (AbsKind) {
8971     default:
8972       return 0;
8973     case Builtin::BI__builtin_fabsf:
8974     case Builtin::BI__builtin_fabs:
8975     case Builtin::BI__builtin_fabsl:
8976     case Builtin::BI__builtin_cabsf:
8977     case Builtin::BI__builtin_cabs:
8978     case Builtin::BI__builtin_cabsl:
8979       return Builtin::BI__builtin_abs;
8980     case Builtin::BIfabsf:
8981     case Builtin::BIfabs:
8982     case Builtin::BIfabsl:
8983     case Builtin::BIcabsf:
8984     case Builtin::BIcabs:
8985     case Builtin::BIcabsl:
8986       return Builtin::BIabs;
8987     }
8988   case AVK_Floating:
8989     switch (AbsKind) {
8990     default:
8991       return 0;
8992     case Builtin::BI__builtin_abs:
8993     case Builtin::BI__builtin_labs:
8994     case Builtin::BI__builtin_llabs:
8995     case Builtin::BI__builtin_cabsf:
8996     case Builtin::BI__builtin_cabs:
8997     case Builtin::BI__builtin_cabsl:
8998       return Builtin::BI__builtin_fabsf;
8999     case Builtin::BIabs:
9000     case Builtin::BIlabs:
9001     case Builtin::BIllabs:
9002     case Builtin::BIcabsf:
9003     case Builtin::BIcabs:
9004     case Builtin::BIcabsl:
9005       return Builtin::BIfabsf;
9006     }
9007   case AVK_Complex:
9008     switch (AbsKind) {
9009     default:
9010       return 0;
9011     case Builtin::BI__builtin_abs:
9012     case Builtin::BI__builtin_labs:
9013     case Builtin::BI__builtin_llabs:
9014     case Builtin::BI__builtin_fabsf:
9015     case Builtin::BI__builtin_fabs:
9016     case Builtin::BI__builtin_fabsl:
9017       return Builtin::BI__builtin_cabsf;
9018     case Builtin::BIabs:
9019     case Builtin::BIlabs:
9020     case Builtin::BIllabs:
9021     case Builtin::BIfabsf:
9022     case Builtin::BIfabs:
9023     case Builtin::BIfabsl:
9024       return Builtin::BIcabsf;
9025     }
9026   }
9027   llvm_unreachable("Unable to convert function");
9028 }
9029 
9030 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9031   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9032   if (!FnInfo)
9033     return 0;
9034 
9035   switch (FDecl->getBuiltinID()) {
9036   default:
9037     return 0;
9038   case Builtin::BI__builtin_abs:
9039   case Builtin::BI__builtin_fabs:
9040   case Builtin::BI__builtin_fabsf:
9041   case Builtin::BI__builtin_fabsl:
9042   case Builtin::BI__builtin_labs:
9043   case Builtin::BI__builtin_llabs:
9044   case Builtin::BI__builtin_cabs:
9045   case Builtin::BI__builtin_cabsf:
9046   case Builtin::BI__builtin_cabsl:
9047   case Builtin::BIabs:
9048   case Builtin::BIlabs:
9049   case Builtin::BIllabs:
9050   case Builtin::BIfabs:
9051   case Builtin::BIfabsf:
9052   case Builtin::BIfabsl:
9053   case Builtin::BIcabs:
9054   case Builtin::BIcabsf:
9055   case Builtin::BIcabsl:
9056     return FDecl->getBuiltinID();
9057   }
9058   llvm_unreachable("Unknown Builtin type");
9059 }
9060 
9061 // If the replacement is valid, emit a note with replacement function.
9062 // Additionally, suggest including the proper header if not already included.
9063 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9064                             unsigned AbsKind, QualType ArgType) {
9065   bool EmitHeaderHint = true;
9066   const char *HeaderName = nullptr;
9067   const char *FunctionName = nullptr;
9068   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9069     FunctionName = "std::abs";
9070     if (ArgType->isIntegralOrEnumerationType()) {
9071       HeaderName = "cstdlib";
9072     } else if (ArgType->isRealFloatingType()) {
9073       HeaderName = "cmath";
9074     } else {
9075       llvm_unreachable("Invalid Type");
9076     }
9077 
9078     // Lookup all std::abs
9079     if (NamespaceDecl *Std = S.getStdNamespace()) {
9080       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9081       R.suppressDiagnostics();
9082       S.LookupQualifiedName(R, Std);
9083 
9084       for (const auto *I : R) {
9085         const FunctionDecl *FDecl = nullptr;
9086         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9087           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9088         } else {
9089           FDecl = dyn_cast<FunctionDecl>(I);
9090         }
9091         if (!FDecl)
9092           continue;
9093 
9094         // Found std::abs(), check that they are the right ones.
9095         if (FDecl->getNumParams() != 1)
9096           continue;
9097 
9098         // Check that the parameter type can handle the argument.
9099         QualType ParamType = FDecl->getParamDecl(0)->getType();
9100         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9101             S.Context.getTypeSize(ArgType) <=
9102                 S.Context.getTypeSize(ParamType)) {
9103           // Found a function, don't need the header hint.
9104           EmitHeaderHint = false;
9105           break;
9106         }
9107       }
9108     }
9109   } else {
9110     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9111     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9112 
9113     if (HeaderName) {
9114       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9115       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9116       R.suppressDiagnostics();
9117       S.LookupName(R, S.getCurScope());
9118 
9119       if (R.isSingleResult()) {
9120         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9121         if (FD && FD->getBuiltinID() == AbsKind) {
9122           EmitHeaderHint = false;
9123         } else {
9124           return;
9125         }
9126       } else if (!R.empty()) {
9127         return;
9128       }
9129     }
9130   }
9131 
9132   S.Diag(Loc, diag::note_replace_abs_function)
9133       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9134 
9135   if (!HeaderName)
9136     return;
9137 
9138   if (!EmitHeaderHint)
9139     return;
9140 
9141   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9142                                                     << FunctionName;
9143 }
9144 
9145 template <std::size_t StrLen>
9146 static bool IsStdFunction(const FunctionDecl *FDecl,
9147                           const char (&Str)[StrLen]) {
9148   if (!FDecl)
9149     return false;
9150   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9151     return false;
9152   if (!FDecl->isInStdNamespace())
9153     return false;
9154 
9155   return true;
9156 }
9157 
9158 // Warn when using the wrong abs() function.
9159 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9160                                       const FunctionDecl *FDecl) {
9161   if (Call->getNumArgs() != 1)
9162     return;
9163 
9164   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9165   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9166   if (AbsKind == 0 && !IsStdAbs)
9167     return;
9168 
9169   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9170   QualType ParamType = Call->getArg(0)->getType();
9171 
9172   // Unsigned types cannot be negative.  Suggest removing the absolute value
9173   // function call.
9174   if (ArgType->isUnsignedIntegerType()) {
9175     const char *FunctionName =
9176         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9177     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9178     Diag(Call->getExprLoc(), diag::note_remove_abs)
9179         << FunctionName
9180         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9181     return;
9182   }
9183 
9184   // Taking the absolute value of a pointer is very suspicious, they probably
9185   // wanted to index into an array, dereference a pointer, call a function, etc.
9186   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9187     unsigned DiagType = 0;
9188     if (ArgType->isFunctionType())
9189       DiagType = 1;
9190     else if (ArgType->isArrayType())
9191       DiagType = 2;
9192 
9193     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9194     return;
9195   }
9196 
9197   // std::abs has overloads which prevent most of the absolute value problems
9198   // from occurring.
9199   if (IsStdAbs)
9200     return;
9201 
9202   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9203   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9204 
9205   // The argument and parameter are the same kind.  Check if they are the right
9206   // size.
9207   if (ArgValueKind == ParamValueKind) {
9208     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9209       return;
9210 
9211     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9212     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9213         << FDecl << ArgType << ParamType;
9214 
9215     if (NewAbsKind == 0)
9216       return;
9217 
9218     emitReplacement(*this, Call->getExprLoc(),
9219                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9220     return;
9221   }
9222 
9223   // ArgValueKind != ParamValueKind
9224   // The wrong type of absolute value function was used.  Attempt to find the
9225   // proper one.
9226   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9227   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9228   if (NewAbsKind == 0)
9229     return;
9230 
9231   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9232       << FDecl << ParamValueKind << ArgValueKind;
9233 
9234   emitReplacement(*this, Call->getExprLoc(),
9235                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9236 }
9237 
9238 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9239 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9240                                 const FunctionDecl *FDecl) {
9241   if (!Call || !FDecl) return;
9242 
9243   // Ignore template specializations and macros.
9244   if (inTemplateInstantiation()) return;
9245   if (Call->getExprLoc().isMacroID()) return;
9246 
9247   // Only care about the one template argument, two function parameter std::max
9248   if (Call->getNumArgs() != 2) return;
9249   if (!IsStdFunction(FDecl, "max")) return;
9250   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9251   if (!ArgList) return;
9252   if (ArgList->size() != 1) return;
9253 
9254   // Check that template type argument is unsigned integer.
9255   const auto& TA = ArgList->get(0);
9256   if (TA.getKind() != TemplateArgument::Type) return;
9257   QualType ArgType = TA.getAsType();
9258   if (!ArgType->isUnsignedIntegerType()) return;
9259 
9260   // See if either argument is a literal zero.
9261   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9262     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9263     if (!MTE) return false;
9264     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9265     if (!Num) return false;
9266     if (Num->getValue() != 0) return false;
9267     return true;
9268   };
9269 
9270   const Expr *FirstArg = Call->getArg(0);
9271   const Expr *SecondArg = Call->getArg(1);
9272   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9273   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9274 
9275   // Only warn when exactly one argument is zero.
9276   if (IsFirstArgZero == IsSecondArgZero) return;
9277 
9278   SourceRange FirstRange = FirstArg->getSourceRange();
9279   SourceRange SecondRange = SecondArg->getSourceRange();
9280 
9281   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9282 
9283   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9284       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9285 
9286   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9287   SourceRange RemovalRange;
9288   if (IsFirstArgZero) {
9289     RemovalRange = SourceRange(FirstRange.getBegin(),
9290                                SecondRange.getBegin().getLocWithOffset(-1));
9291   } else {
9292     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9293                                SecondRange.getEnd());
9294   }
9295 
9296   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9297         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9298         << FixItHint::CreateRemoval(RemovalRange);
9299 }
9300 
9301 //===--- CHECK: Standard memory functions ---------------------------------===//
9302 
9303 /// Takes the expression passed to the size_t parameter of functions
9304 /// such as memcmp, strncat, etc and warns if it's a comparison.
9305 ///
9306 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9307 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9308                                            IdentifierInfo *FnName,
9309                                            SourceLocation FnLoc,
9310                                            SourceLocation RParenLoc) {
9311   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9312   if (!Size)
9313     return false;
9314 
9315   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9316   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9317     return false;
9318 
9319   SourceRange SizeRange = Size->getSourceRange();
9320   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9321       << SizeRange << FnName;
9322   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9323       << FnName
9324       << FixItHint::CreateInsertion(
9325              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9326       << FixItHint::CreateRemoval(RParenLoc);
9327   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9328       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9329       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9330                                     ")");
9331 
9332   return true;
9333 }
9334 
9335 /// Determine whether the given type is or contains a dynamic class type
9336 /// (e.g., whether it has a vtable).
9337 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9338                                                      bool &IsContained) {
9339   // Look through array types while ignoring qualifiers.
9340   const Type *Ty = T->getBaseElementTypeUnsafe();
9341   IsContained = false;
9342 
9343   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9344   RD = RD ? RD->getDefinition() : nullptr;
9345   if (!RD || RD->isInvalidDecl())
9346     return nullptr;
9347 
9348   if (RD->isDynamicClass())
9349     return RD;
9350 
9351   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9352   // It's impossible for a class to transitively contain itself by value, so
9353   // infinite recursion is impossible.
9354   for (auto *FD : RD->fields()) {
9355     bool SubContained;
9356     if (const CXXRecordDecl *ContainedRD =
9357             getContainedDynamicClass(FD->getType(), SubContained)) {
9358       IsContained = true;
9359       return ContainedRD;
9360     }
9361   }
9362 
9363   return nullptr;
9364 }
9365 
9366 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9367   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9368     if (Unary->getKind() == UETT_SizeOf)
9369       return Unary;
9370   return nullptr;
9371 }
9372 
9373 /// If E is a sizeof expression, returns its argument expression,
9374 /// otherwise returns NULL.
9375 static const Expr *getSizeOfExprArg(const Expr *E) {
9376   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9377     if (!SizeOf->isArgumentType())
9378       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9379   return nullptr;
9380 }
9381 
9382 /// If E is a sizeof expression, returns its argument type.
9383 static QualType getSizeOfArgType(const Expr *E) {
9384   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9385     return SizeOf->getTypeOfArgument();
9386   return QualType();
9387 }
9388 
9389 namespace {
9390 
9391 struct SearchNonTrivialToInitializeField
9392     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9393   using Super =
9394       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9395 
9396   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9397 
9398   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9399                      SourceLocation SL) {
9400     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9401       asDerived().visitArray(PDIK, AT, SL);
9402       return;
9403     }
9404 
9405     Super::visitWithKind(PDIK, FT, SL);
9406   }
9407 
9408   void visitARCStrong(QualType FT, SourceLocation SL) {
9409     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9410   }
9411   void visitARCWeak(QualType FT, SourceLocation SL) {
9412     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9413   }
9414   void visitStruct(QualType FT, SourceLocation SL) {
9415     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9416       visit(FD->getType(), FD->getLocation());
9417   }
9418   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9419                   const ArrayType *AT, SourceLocation SL) {
9420     visit(getContext().getBaseElementType(AT), SL);
9421   }
9422   void visitTrivial(QualType FT, SourceLocation SL) {}
9423 
9424   static void diag(QualType RT, const Expr *E, Sema &S) {
9425     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9426   }
9427 
9428   ASTContext &getContext() { return S.getASTContext(); }
9429 
9430   const Expr *E;
9431   Sema &S;
9432 };
9433 
9434 struct SearchNonTrivialToCopyField
9435     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9436   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9437 
9438   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9439 
9440   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9441                      SourceLocation SL) {
9442     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9443       asDerived().visitArray(PCK, AT, SL);
9444       return;
9445     }
9446 
9447     Super::visitWithKind(PCK, FT, SL);
9448   }
9449 
9450   void visitARCStrong(QualType FT, SourceLocation SL) {
9451     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9452   }
9453   void visitARCWeak(QualType FT, SourceLocation SL) {
9454     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9455   }
9456   void visitStruct(QualType FT, SourceLocation SL) {
9457     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9458       visit(FD->getType(), FD->getLocation());
9459   }
9460   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9461                   SourceLocation SL) {
9462     visit(getContext().getBaseElementType(AT), SL);
9463   }
9464   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9465                 SourceLocation SL) {}
9466   void visitTrivial(QualType FT, SourceLocation SL) {}
9467   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9468 
9469   static void diag(QualType RT, const Expr *E, Sema &S) {
9470     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9471   }
9472 
9473   ASTContext &getContext() { return S.getASTContext(); }
9474 
9475   const Expr *E;
9476   Sema &S;
9477 };
9478 
9479 }
9480 
9481 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9482 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9483   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9484 
9485   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9486     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9487       return false;
9488 
9489     return doesExprLikelyComputeSize(BO->getLHS()) ||
9490            doesExprLikelyComputeSize(BO->getRHS());
9491   }
9492 
9493   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9494 }
9495 
9496 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9497 ///
9498 /// \code
9499 ///   #define MACRO 0
9500 ///   foo(MACRO);
9501 ///   foo(0);
9502 /// \endcode
9503 ///
9504 /// This should return true for the first call to foo, but not for the second
9505 /// (regardless of whether foo is a macro or function).
9506 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9507                                         SourceLocation CallLoc,
9508                                         SourceLocation ArgLoc) {
9509   if (!CallLoc.isMacroID())
9510     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9511 
9512   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9513          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9514 }
9515 
9516 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9517 /// last two arguments transposed.
9518 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9519   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9520     return;
9521 
9522   const Expr *SizeArg =
9523     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9524 
9525   auto isLiteralZero = [](const Expr *E) {
9526     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9527   };
9528 
9529   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9530   SourceLocation CallLoc = Call->getRParenLoc();
9531   SourceManager &SM = S.getSourceManager();
9532   if (isLiteralZero(SizeArg) &&
9533       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9534 
9535     SourceLocation DiagLoc = SizeArg->getExprLoc();
9536 
9537     // Some platforms #define bzero to __builtin_memset. See if this is the
9538     // case, and if so, emit a better diagnostic.
9539     if (BId == Builtin::BIbzero ||
9540         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9541                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9542       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9543       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9544     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9545       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9546       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9547     }
9548     return;
9549   }
9550 
9551   // If the second argument to a memset is a sizeof expression and the third
9552   // isn't, this is also likely an error. This should catch
9553   // 'memset(buf, sizeof(buf), 0xff)'.
9554   if (BId == Builtin::BImemset &&
9555       doesExprLikelyComputeSize(Call->getArg(1)) &&
9556       !doesExprLikelyComputeSize(Call->getArg(2))) {
9557     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9558     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9559     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9560     return;
9561   }
9562 }
9563 
9564 /// Check for dangerous or invalid arguments to memset().
9565 ///
9566 /// This issues warnings on known problematic, dangerous or unspecified
9567 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9568 /// function calls.
9569 ///
9570 /// \param Call The call expression to diagnose.
9571 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9572                                    unsigned BId,
9573                                    IdentifierInfo *FnName) {
9574   assert(BId != 0);
9575 
9576   // It is possible to have a non-standard definition of memset.  Validate
9577   // we have enough arguments, and if not, abort further checking.
9578   unsigned ExpectedNumArgs =
9579       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9580   if (Call->getNumArgs() < ExpectedNumArgs)
9581     return;
9582 
9583   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9584                       BId == Builtin::BIstrndup ? 1 : 2);
9585   unsigned LenArg =
9586       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9587   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9588 
9589   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9590                                      Call->getBeginLoc(), Call->getRParenLoc()))
9591     return;
9592 
9593   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9594   CheckMemaccessSize(*this, BId, Call);
9595 
9596   // We have special checking when the length is a sizeof expression.
9597   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9598   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9599   llvm::FoldingSetNodeID SizeOfArgID;
9600 
9601   // Although widely used, 'bzero' is not a standard function. Be more strict
9602   // with the argument types before allowing diagnostics and only allow the
9603   // form bzero(ptr, sizeof(...)).
9604   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9605   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9606     return;
9607 
9608   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9609     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9610     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9611 
9612     QualType DestTy = Dest->getType();
9613     QualType PointeeTy;
9614     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9615       PointeeTy = DestPtrTy->getPointeeType();
9616 
9617       // Never warn about void type pointers. This can be used to suppress
9618       // false positives.
9619       if (PointeeTy->isVoidType())
9620         continue;
9621 
9622       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9623       // actually comparing the expressions for equality. Because computing the
9624       // expression IDs can be expensive, we only do this if the diagnostic is
9625       // enabled.
9626       if (SizeOfArg &&
9627           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9628                            SizeOfArg->getExprLoc())) {
9629         // We only compute IDs for expressions if the warning is enabled, and
9630         // cache the sizeof arg's ID.
9631         if (SizeOfArgID == llvm::FoldingSetNodeID())
9632           SizeOfArg->Profile(SizeOfArgID, Context, true);
9633         llvm::FoldingSetNodeID DestID;
9634         Dest->Profile(DestID, Context, true);
9635         if (DestID == SizeOfArgID) {
9636           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9637           //       over sizeof(src) as well.
9638           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9639           StringRef ReadableName = FnName->getName();
9640 
9641           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9642             if (UnaryOp->getOpcode() == UO_AddrOf)
9643               ActionIdx = 1; // If its an address-of operator, just remove it.
9644           if (!PointeeTy->isIncompleteType() &&
9645               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9646             ActionIdx = 2; // If the pointee's size is sizeof(char),
9647                            // suggest an explicit length.
9648 
9649           // If the function is defined as a builtin macro, do not show macro
9650           // expansion.
9651           SourceLocation SL = SizeOfArg->getExprLoc();
9652           SourceRange DSR = Dest->getSourceRange();
9653           SourceRange SSR = SizeOfArg->getSourceRange();
9654           SourceManager &SM = getSourceManager();
9655 
9656           if (SM.isMacroArgExpansion(SL)) {
9657             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9658             SL = SM.getSpellingLoc(SL);
9659             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9660                              SM.getSpellingLoc(DSR.getEnd()));
9661             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9662                              SM.getSpellingLoc(SSR.getEnd()));
9663           }
9664 
9665           DiagRuntimeBehavior(SL, SizeOfArg,
9666                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9667                                 << ReadableName
9668                                 << PointeeTy
9669                                 << DestTy
9670                                 << DSR
9671                                 << SSR);
9672           DiagRuntimeBehavior(SL, SizeOfArg,
9673                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9674                                 << ActionIdx
9675                                 << SSR);
9676 
9677           break;
9678         }
9679       }
9680 
9681       // Also check for cases where the sizeof argument is the exact same
9682       // type as the memory argument, and where it points to a user-defined
9683       // record type.
9684       if (SizeOfArgTy != QualType()) {
9685         if (PointeeTy->isRecordType() &&
9686             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9687           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9688                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9689                                 << FnName << SizeOfArgTy << ArgIdx
9690                                 << PointeeTy << Dest->getSourceRange()
9691                                 << LenExpr->getSourceRange());
9692           break;
9693         }
9694       }
9695     } else if (DestTy->isArrayType()) {
9696       PointeeTy = DestTy;
9697     }
9698 
9699     if (PointeeTy == QualType())
9700       continue;
9701 
9702     // Always complain about dynamic classes.
9703     bool IsContained;
9704     if (const CXXRecordDecl *ContainedRD =
9705             getContainedDynamicClass(PointeeTy, IsContained)) {
9706 
9707       unsigned OperationType = 0;
9708       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9709       // "overwritten" if we're warning about the destination for any call
9710       // but memcmp; otherwise a verb appropriate to the call.
9711       if (ArgIdx != 0 || IsCmp) {
9712         if (BId == Builtin::BImemcpy)
9713           OperationType = 1;
9714         else if(BId == Builtin::BImemmove)
9715           OperationType = 2;
9716         else if (IsCmp)
9717           OperationType = 3;
9718       }
9719 
9720       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9721                           PDiag(diag::warn_dyn_class_memaccess)
9722                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9723                               << IsContained << ContainedRD << OperationType
9724                               << Call->getCallee()->getSourceRange());
9725     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9726              BId != Builtin::BImemset)
9727       DiagRuntimeBehavior(
9728         Dest->getExprLoc(), Dest,
9729         PDiag(diag::warn_arc_object_memaccess)
9730           << ArgIdx << FnName << PointeeTy
9731           << Call->getCallee()->getSourceRange());
9732     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9733       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9734           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9735         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9736                             PDiag(diag::warn_cstruct_memaccess)
9737                                 << ArgIdx << FnName << PointeeTy << 0);
9738         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9739       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9740                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9741         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9742                             PDiag(diag::warn_cstruct_memaccess)
9743                                 << ArgIdx << FnName << PointeeTy << 1);
9744         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9745       } else {
9746         continue;
9747       }
9748     } else
9749       continue;
9750 
9751     DiagRuntimeBehavior(
9752       Dest->getExprLoc(), Dest,
9753       PDiag(diag::note_bad_memaccess_silence)
9754         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9755     break;
9756   }
9757 }
9758 
9759 // A little helper routine: ignore addition and subtraction of integer literals.
9760 // This intentionally does not ignore all integer constant expressions because
9761 // we don't want to remove sizeof().
9762 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9763   Ex = Ex->IgnoreParenCasts();
9764 
9765   while (true) {
9766     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9767     if (!BO || !BO->isAdditiveOp())
9768       break;
9769 
9770     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9771     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9772 
9773     if (isa<IntegerLiteral>(RHS))
9774       Ex = LHS;
9775     else if (isa<IntegerLiteral>(LHS))
9776       Ex = RHS;
9777     else
9778       break;
9779   }
9780 
9781   return Ex;
9782 }
9783 
9784 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9785                                                       ASTContext &Context) {
9786   // Only handle constant-sized or VLAs, but not flexible members.
9787   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9788     // Only issue the FIXIT for arrays of size > 1.
9789     if (CAT->getSize().getSExtValue() <= 1)
9790       return false;
9791   } else if (!Ty->isVariableArrayType()) {
9792     return false;
9793   }
9794   return true;
9795 }
9796 
9797 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9798 // be the size of the source, instead of the destination.
9799 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9800                                     IdentifierInfo *FnName) {
9801 
9802   // Don't crash if the user has the wrong number of arguments
9803   unsigned NumArgs = Call->getNumArgs();
9804   if ((NumArgs != 3) && (NumArgs != 4))
9805     return;
9806 
9807   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9808   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9809   const Expr *CompareWithSrc = nullptr;
9810 
9811   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9812                                      Call->getBeginLoc(), Call->getRParenLoc()))
9813     return;
9814 
9815   // Look for 'strlcpy(dst, x, sizeof(x))'
9816   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9817     CompareWithSrc = Ex;
9818   else {
9819     // Look for 'strlcpy(dst, x, strlen(x))'
9820     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9821       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9822           SizeCall->getNumArgs() == 1)
9823         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9824     }
9825   }
9826 
9827   if (!CompareWithSrc)
9828     return;
9829 
9830   // Determine if the argument to sizeof/strlen is equal to the source
9831   // argument.  In principle there's all kinds of things you could do
9832   // here, for instance creating an == expression and evaluating it with
9833   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9834   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9835   if (!SrcArgDRE)
9836     return;
9837 
9838   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9839   if (!CompareWithSrcDRE ||
9840       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9841     return;
9842 
9843   const Expr *OriginalSizeArg = Call->getArg(2);
9844   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9845       << OriginalSizeArg->getSourceRange() << FnName;
9846 
9847   // Output a FIXIT hint if the destination is an array (rather than a
9848   // pointer to an array).  This could be enhanced to handle some
9849   // pointers if we know the actual size, like if DstArg is 'array+2'
9850   // we could say 'sizeof(array)-2'.
9851   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9852   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9853     return;
9854 
9855   SmallString<128> sizeString;
9856   llvm::raw_svector_ostream OS(sizeString);
9857   OS << "sizeof(";
9858   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9859   OS << ")";
9860 
9861   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9862       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9863                                       OS.str());
9864 }
9865 
9866 /// Check if two expressions refer to the same declaration.
9867 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9868   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9869     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9870       return D1->getDecl() == D2->getDecl();
9871   return false;
9872 }
9873 
9874 static const Expr *getStrlenExprArg(const Expr *E) {
9875   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9876     const FunctionDecl *FD = CE->getDirectCallee();
9877     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9878       return nullptr;
9879     return CE->getArg(0)->IgnoreParenCasts();
9880   }
9881   return nullptr;
9882 }
9883 
9884 // Warn on anti-patterns as the 'size' argument to strncat.
9885 // The correct size argument should look like following:
9886 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9887 void Sema::CheckStrncatArguments(const CallExpr *CE,
9888                                  IdentifierInfo *FnName) {
9889   // Don't crash if the user has the wrong number of arguments.
9890   if (CE->getNumArgs() < 3)
9891     return;
9892   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9893   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9894   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9895 
9896   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9897                                      CE->getRParenLoc()))
9898     return;
9899 
9900   // Identify common expressions, which are wrongly used as the size argument
9901   // to strncat and may lead to buffer overflows.
9902   unsigned PatternType = 0;
9903   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9904     // - sizeof(dst)
9905     if (referToTheSameDecl(SizeOfArg, DstArg))
9906       PatternType = 1;
9907     // - sizeof(src)
9908     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9909       PatternType = 2;
9910   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9911     if (BE->getOpcode() == BO_Sub) {
9912       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9913       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9914       // - sizeof(dst) - strlen(dst)
9915       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9916           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9917         PatternType = 1;
9918       // - sizeof(src) - (anything)
9919       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9920         PatternType = 2;
9921     }
9922   }
9923 
9924   if (PatternType == 0)
9925     return;
9926 
9927   // Generate the diagnostic.
9928   SourceLocation SL = LenArg->getBeginLoc();
9929   SourceRange SR = LenArg->getSourceRange();
9930   SourceManager &SM = getSourceManager();
9931 
9932   // If the function is defined as a builtin macro, do not show macro expansion.
9933   if (SM.isMacroArgExpansion(SL)) {
9934     SL = SM.getSpellingLoc(SL);
9935     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9936                      SM.getSpellingLoc(SR.getEnd()));
9937   }
9938 
9939   // Check if the destination is an array (rather than a pointer to an array).
9940   QualType DstTy = DstArg->getType();
9941   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9942                                                                     Context);
9943   if (!isKnownSizeArray) {
9944     if (PatternType == 1)
9945       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9946     else
9947       Diag(SL, diag::warn_strncat_src_size) << SR;
9948     return;
9949   }
9950 
9951   if (PatternType == 1)
9952     Diag(SL, diag::warn_strncat_large_size) << SR;
9953   else
9954     Diag(SL, diag::warn_strncat_src_size) << SR;
9955 
9956   SmallString<128> sizeString;
9957   llvm::raw_svector_ostream OS(sizeString);
9958   OS << "sizeof(";
9959   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9960   OS << ") - ";
9961   OS << "strlen(";
9962   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9963   OS << ") - 1";
9964 
9965   Diag(SL, diag::note_strncat_wrong_size)
9966     << FixItHint::CreateReplacement(SR, OS.str());
9967 }
9968 
9969 void
9970 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9971                          SourceLocation ReturnLoc,
9972                          bool isObjCMethod,
9973                          const AttrVec *Attrs,
9974                          const FunctionDecl *FD) {
9975   // Check if the return value is null but should not be.
9976   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9977        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9978       CheckNonNullExpr(*this, RetValExp))
9979     Diag(ReturnLoc, diag::warn_null_ret)
9980       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9981 
9982   // C++11 [basic.stc.dynamic.allocation]p4:
9983   //   If an allocation function declared with a non-throwing
9984   //   exception-specification fails to allocate storage, it shall return
9985   //   a null pointer. Any other allocation function that fails to allocate
9986   //   storage shall indicate failure only by throwing an exception [...]
9987   if (FD) {
9988     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9989     if (Op == OO_New || Op == OO_Array_New) {
9990       const FunctionProtoType *Proto
9991         = FD->getType()->castAs<FunctionProtoType>();
9992       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9993           CheckNonNullExpr(*this, RetValExp))
9994         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9995           << FD << getLangOpts().CPlusPlus11;
9996     }
9997   }
9998 }
9999 
10000 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10001 
10002 /// Check for comparisons of floating point operands using != and ==.
10003 /// Issue a warning if these are no self-comparisons, as they are not likely
10004 /// to do what the programmer intended.
10005 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10006   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10007   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10008 
10009   // Special case: check for x == x (which is OK).
10010   // Do not emit warnings for such cases.
10011   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10012     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10013       if (DRL->getDecl() == DRR->getDecl())
10014         return;
10015 
10016   // Special case: check for comparisons against literals that can be exactly
10017   //  represented by APFloat.  In such cases, do not emit a warning.  This
10018   //  is a heuristic: often comparison against such literals are used to
10019   //  detect if a value in a variable has not changed.  This clearly can
10020   //  lead to false negatives.
10021   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10022     if (FLL->isExact())
10023       return;
10024   } else
10025     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10026       if (FLR->isExact())
10027         return;
10028 
10029   // Check for comparisons with builtin types.
10030   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10031     if (CL->getBuiltinCallee())
10032       return;
10033 
10034   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10035     if (CR->getBuiltinCallee())
10036       return;
10037 
10038   // Emit the diagnostic.
10039   Diag(Loc, diag::warn_floatingpoint_eq)
10040     << LHS->getSourceRange() << RHS->getSourceRange();
10041 }
10042 
10043 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10044 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10045 
10046 namespace {
10047 
10048 /// Structure recording the 'active' range of an integer-valued
10049 /// expression.
10050 struct IntRange {
10051   /// The number of bits active in the int.
10052   unsigned Width;
10053 
10054   /// True if the int is known not to have negative values.
10055   bool NonNegative;
10056 
10057   IntRange(unsigned Width, bool NonNegative)
10058       : Width(Width), NonNegative(NonNegative) {}
10059 
10060   /// Returns the range of the bool type.
10061   static IntRange forBoolType() {
10062     return IntRange(1, true);
10063   }
10064 
10065   /// Returns the range of an opaque value of the given integral type.
10066   static IntRange forValueOfType(ASTContext &C, QualType T) {
10067     return forValueOfCanonicalType(C,
10068                           T->getCanonicalTypeInternal().getTypePtr());
10069   }
10070 
10071   /// Returns the range of an opaque value of a canonical integral type.
10072   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10073     assert(T->isCanonicalUnqualified());
10074 
10075     if (const VectorType *VT = dyn_cast<VectorType>(T))
10076       T = VT->getElementType().getTypePtr();
10077     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10078       T = CT->getElementType().getTypePtr();
10079     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10080       T = AT->getValueType().getTypePtr();
10081 
10082     if (!C.getLangOpts().CPlusPlus) {
10083       // For enum types in C code, use the underlying datatype.
10084       if (const EnumType *ET = dyn_cast<EnumType>(T))
10085         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10086     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10087       // For enum types in C++, use the known bit width of the enumerators.
10088       EnumDecl *Enum = ET->getDecl();
10089       // In C++11, enums can have a fixed underlying type. Use this type to
10090       // compute the range.
10091       if (Enum->isFixed()) {
10092         return IntRange(C.getIntWidth(QualType(T, 0)),
10093                         !ET->isSignedIntegerOrEnumerationType());
10094       }
10095 
10096       unsigned NumPositive = Enum->getNumPositiveBits();
10097       unsigned NumNegative = Enum->getNumNegativeBits();
10098 
10099       if (NumNegative == 0)
10100         return IntRange(NumPositive, true/*NonNegative*/);
10101       else
10102         return IntRange(std::max(NumPositive + 1, NumNegative),
10103                         false/*NonNegative*/);
10104     }
10105 
10106     const BuiltinType *BT = cast<BuiltinType>(T);
10107     assert(BT->isInteger());
10108 
10109     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10110   }
10111 
10112   /// Returns the "target" range of a canonical integral type, i.e.
10113   /// the range of values expressible in the type.
10114   ///
10115   /// This matches forValueOfCanonicalType except that enums have the
10116   /// full range of their type, not the range of their enumerators.
10117   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10118     assert(T->isCanonicalUnqualified());
10119 
10120     if (const VectorType *VT = dyn_cast<VectorType>(T))
10121       T = VT->getElementType().getTypePtr();
10122     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10123       T = CT->getElementType().getTypePtr();
10124     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10125       T = AT->getValueType().getTypePtr();
10126     if (const EnumType *ET = dyn_cast<EnumType>(T))
10127       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10128 
10129     const BuiltinType *BT = cast<BuiltinType>(T);
10130     assert(BT->isInteger());
10131 
10132     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10133   }
10134 
10135   /// Returns the supremum of two ranges: i.e. their conservative merge.
10136   static IntRange join(IntRange L, IntRange R) {
10137     return IntRange(std::max(L.Width, R.Width),
10138                     L.NonNegative && R.NonNegative);
10139   }
10140 
10141   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10142   static IntRange meet(IntRange L, IntRange R) {
10143     return IntRange(std::min(L.Width, R.Width),
10144                     L.NonNegative || R.NonNegative);
10145   }
10146 };
10147 
10148 } // namespace
10149 
10150 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10151                               unsigned MaxWidth) {
10152   if (value.isSigned() && value.isNegative())
10153     return IntRange(value.getMinSignedBits(), false);
10154 
10155   if (value.getBitWidth() > MaxWidth)
10156     value = value.trunc(MaxWidth);
10157 
10158   // isNonNegative() just checks the sign bit without considering
10159   // signedness.
10160   return IntRange(value.getActiveBits(), true);
10161 }
10162 
10163 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10164                               unsigned MaxWidth) {
10165   if (result.isInt())
10166     return GetValueRange(C, result.getInt(), MaxWidth);
10167 
10168   if (result.isVector()) {
10169     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10170     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10171       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10172       R = IntRange::join(R, El);
10173     }
10174     return R;
10175   }
10176 
10177   if (result.isComplexInt()) {
10178     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10179     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10180     return IntRange::join(R, I);
10181   }
10182 
10183   // This can happen with lossless casts to intptr_t of "based" lvalues.
10184   // Assume it might use arbitrary bits.
10185   // FIXME: The only reason we need to pass the type in here is to get
10186   // the sign right on this one case.  It would be nice if APValue
10187   // preserved this.
10188   assert(result.isLValue() || result.isAddrLabelDiff());
10189   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10190 }
10191 
10192 static QualType GetExprType(const Expr *E) {
10193   QualType Ty = E->getType();
10194   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10195     Ty = AtomicRHS->getValueType();
10196   return Ty;
10197 }
10198 
10199 /// Pseudo-evaluate the given integer expression, estimating the
10200 /// range of values it might take.
10201 ///
10202 /// \param MaxWidth - the width to which the value will be truncated
10203 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10204                              bool InConstantContext) {
10205   E = E->IgnoreParens();
10206 
10207   // Try a full evaluation first.
10208   Expr::EvalResult result;
10209   if (E->EvaluateAsRValue(result, C, InConstantContext))
10210     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10211 
10212   // I think we only want to look through implicit casts here; if the
10213   // user has an explicit widening cast, we should treat the value as
10214   // being of the new, wider type.
10215   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10216     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10217       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10218 
10219     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10220 
10221     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10222                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10223 
10224     // Assume that non-integer casts can span the full range of the type.
10225     if (!isIntegerCast)
10226       return OutputTypeRange;
10227 
10228     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10229                                      std::min(MaxWidth, OutputTypeRange.Width),
10230                                      InConstantContext);
10231 
10232     // Bail out if the subexpr's range is as wide as the cast type.
10233     if (SubRange.Width >= OutputTypeRange.Width)
10234       return OutputTypeRange;
10235 
10236     // Otherwise, we take the smaller width, and we're non-negative if
10237     // either the output type or the subexpr is.
10238     return IntRange(SubRange.Width,
10239                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10240   }
10241 
10242   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10243     // If we can fold the condition, just take that operand.
10244     bool CondResult;
10245     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10246       return GetExprRange(C,
10247                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10248                           MaxWidth, InConstantContext);
10249 
10250     // Otherwise, conservatively merge.
10251     IntRange L =
10252         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10253     IntRange R =
10254         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10255     return IntRange::join(L, R);
10256   }
10257 
10258   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10259     switch (BO->getOpcode()) {
10260     case BO_Cmp:
10261       llvm_unreachable("builtin <=> should have class type");
10262 
10263     // Boolean-valued operations are single-bit and positive.
10264     case BO_LAnd:
10265     case BO_LOr:
10266     case BO_LT:
10267     case BO_GT:
10268     case BO_LE:
10269     case BO_GE:
10270     case BO_EQ:
10271     case BO_NE:
10272       return IntRange::forBoolType();
10273 
10274     // The type of the assignments is the type of the LHS, so the RHS
10275     // is not necessarily the same type.
10276     case BO_MulAssign:
10277     case BO_DivAssign:
10278     case BO_RemAssign:
10279     case BO_AddAssign:
10280     case BO_SubAssign:
10281     case BO_XorAssign:
10282     case BO_OrAssign:
10283       // TODO: bitfields?
10284       return IntRange::forValueOfType(C, GetExprType(E));
10285 
10286     // Simple assignments just pass through the RHS, which will have
10287     // been coerced to the LHS type.
10288     case BO_Assign:
10289       // TODO: bitfields?
10290       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10291 
10292     // Operations with opaque sources are black-listed.
10293     case BO_PtrMemD:
10294     case BO_PtrMemI:
10295       return IntRange::forValueOfType(C, GetExprType(E));
10296 
10297     // Bitwise-and uses the *infinum* of the two source ranges.
10298     case BO_And:
10299     case BO_AndAssign:
10300       return IntRange::meet(
10301           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10302           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10303 
10304     // Left shift gets black-listed based on a judgement call.
10305     case BO_Shl:
10306       // ...except that we want to treat '1 << (blah)' as logically
10307       // positive.  It's an important idiom.
10308       if (IntegerLiteral *I
10309             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10310         if (I->getValue() == 1) {
10311           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10312           return IntRange(R.Width, /*NonNegative*/ true);
10313         }
10314       }
10315       LLVM_FALLTHROUGH;
10316 
10317     case BO_ShlAssign:
10318       return IntRange::forValueOfType(C, GetExprType(E));
10319 
10320     // Right shift by a constant can narrow its left argument.
10321     case BO_Shr:
10322     case BO_ShrAssign: {
10323       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10324 
10325       // If the shift amount is a positive constant, drop the width by
10326       // that much.
10327       llvm::APSInt shift;
10328       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10329           shift.isNonNegative()) {
10330         unsigned zext = shift.getZExtValue();
10331         if (zext >= L.Width)
10332           L.Width = (L.NonNegative ? 0 : 1);
10333         else
10334           L.Width -= zext;
10335       }
10336 
10337       return L;
10338     }
10339 
10340     // Comma acts as its right operand.
10341     case BO_Comma:
10342       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10343 
10344     // Black-list pointer subtractions.
10345     case BO_Sub:
10346       if (BO->getLHS()->getType()->isPointerType())
10347         return IntRange::forValueOfType(C, GetExprType(E));
10348       break;
10349 
10350     // The width of a division result is mostly determined by the size
10351     // of the LHS.
10352     case BO_Div: {
10353       // Don't 'pre-truncate' the operands.
10354       unsigned opWidth = C.getIntWidth(GetExprType(E));
10355       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10356 
10357       // If the divisor is constant, use that.
10358       llvm::APSInt divisor;
10359       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10360         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10361         if (log2 >= L.Width)
10362           L.Width = (L.NonNegative ? 0 : 1);
10363         else
10364           L.Width = std::min(L.Width - log2, MaxWidth);
10365         return L;
10366       }
10367 
10368       // Otherwise, just use the LHS's width.
10369       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10370       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10371     }
10372 
10373     // The result of a remainder can't be larger than the result of
10374     // either side.
10375     case BO_Rem: {
10376       // Don't 'pre-truncate' the operands.
10377       unsigned opWidth = C.getIntWidth(GetExprType(E));
10378       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10379       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10380 
10381       IntRange meet = IntRange::meet(L, R);
10382       meet.Width = std::min(meet.Width, MaxWidth);
10383       return meet;
10384     }
10385 
10386     // The default behavior is okay for these.
10387     case BO_Mul:
10388     case BO_Add:
10389     case BO_Xor:
10390     case BO_Or:
10391       break;
10392     }
10393 
10394     // The default case is to treat the operation as if it were closed
10395     // on the narrowest type that encompasses both operands.
10396     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10397     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10398     return IntRange::join(L, R);
10399   }
10400 
10401   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10402     switch (UO->getOpcode()) {
10403     // Boolean-valued operations are white-listed.
10404     case UO_LNot:
10405       return IntRange::forBoolType();
10406 
10407     // Operations with opaque sources are black-listed.
10408     case UO_Deref:
10409     case UO_AddrOf: // should be impossible
10410       return IntRange::forValueOfType(C, GetExprType(E));
10411 
10412     default:
10413       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10414     }
10415   }
10416 
10417   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10418     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10419 
10420   if (const auto *BitField = E->getSourceBitField())
10421     return IntRange(BitField->getBitWidthValue(C),
10422                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10423 
10424   return IntRange::forValueOfType(C, GetExprType(E));
10425 }
10426 
10427 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10428                              bool InConstantContext) {
10429   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10430 }
10431 
10432 /// Checks whether the given value, which currently has the given
10433 /// source semantics, has the same value when coerced through the
10434 /// target semantics.
10435 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10436                                  const llvm::fltSemantics &Src,
10437                                  const llvm::fltSemantics &Tgt) {
10438   llvm::APFloat truncated = value;
10439 
10440   bool ignored;
10441   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10442   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10443 
10444   return truncated.bitwiseIsEqual(value);
10445 }
10446 
10447 /// Checks whether the given value, which currently has the given
10448 /// source semantics, has the same value when coerced through the
10449 /// target semantics.
10450 ///
10451 /// The value might be a vector of floats (or a complex number).
10452 static bool IsSameFloatAfterCast(const APValue &value,
10453                                  const llvm::fltSemantics &Src,
10454                                  const llvm::fltSemantics &Tgt) {
10455   if (value.isFloat())
10456     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10457 
10458   if (value.isVector()) {
10459     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10460       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10461         return false;
10462     return true;
10463   }
10464 
10465   assert(value.isComplexFloat());
10466   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10467           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10468 }
10469 
10470 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10471                                        bool IsListInit = false);
10472 
10473 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10474   // Suppress cases where we are comparing against an enum constant.
10475   if (const DeclRefExpr *DR =
10476       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10477     if (isa<EnumConstantDecl>(DR->getDecl()))
10478       return true;
10479 
10480   // Suppress cases where the value is expanded from a macro, unless that macro
10481   // is how a language represents a boolean literal. This is the case in both C
10482   // and Objective-C.
10483   SourceLocation BeginLoc = E->getBeginLoc();
10484   if (BeginLoc.isMacroID()) {
10485     StringRef MacroName = Lexer::getImmediateMacroName(
10486         BeginLoc, S.getSourceManager(), S.getLangOpts());
10487     return MacroName != "YES" && MacroName != "NO" &&
10488            MacroName != "true" && MacroName != "false";
10489   }
10490 
10491   return false;
10492 }
10493 
10494 static bool isKnownToHaveUnsignedValue(Expr *E) {
10495   return E->getType()->isIntegerType() &&
10496          (!E->getType()->isSignedIntegerType() ||
10497           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10498 }
10499 
10500 namespace {
10501 /// The promoted range of values of a type. In general this has the
10502 /// following structure:
10503 ///
10504 ///     |-----------| . . . |-----------|
10505 ///     ^           ^       ^           ^
10506 ///    Min       HoleMin  HoleMax      Max
10507 ///
10508 /// ... where there is only a hole if a signed type is promoted to unsigned
10509 /// (in which case Min and Max are the smallest and largest representable
10510 /// values).
10511 struct PromotedRange {
10512   // Min, or HoleMax if there is a hole.
10513   llvm::APSInt PromotedMin;
10514   // Max, or HoleMin if there is a hole.
10515   llvm::APSInt PromotedMax;
10516 
10517   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10518     if (R.Width == 0)
10519       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10520     else if (R.Width >= BitWidth && !Unsigned) {
10521       // Promotion made the type *narrower*. This happens when promoting
10522       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10523       // Treat all values of 'signed int' as being in range for now.
10524       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10525       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10526     } else {
10527       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10528                         .extOrTrunc(BitWidth);
10529       PromotedMin.setIsUnsigned(Unsigned);
10530 
10531       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10532                         .extOrTrunc(BitWidth);
10533       PromotedMax.setIsUnsigned(Unsigned);
10534     }
10535   }
10536 
10537   // Determine whether this range is contiguous (has no hole).
10538   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10539 
10540   // Where a constant value is within the range.
10541   enum ComparisonResult {
10542     LT = 0x1,
10543     LE = 0x2,
10544     GT = 0x4,
10545     GE = 0x8,
10546     EQ = 0x10,
10547     NE = 0x20,
10548     InRangeFlag = 0x40,
10549 
10550     Less = LE | LT | NE,
10551     Min = LE | InRangeFlag,
10552     InRange = InRangeFlag,
10553     Max = GE | InRangeFlag,
10554     Greater = GE | GT | NE,
10555 
10556     OnlyValue = LE | GE | EQ | InRangeFlag,
10557     InHole = NE
10558   };
10559 
10560   ComparisonResult compare(const llvm::APSInt &Value) const {
10561     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10562            Value.isUnsigned() == PromotedMin.isUnsigned());
10563     if (!isContiguous()) {
10564       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10565       if (Value.isMinValue()) return Min;
10566       if (Value.isMaxValue()) return Max;
10567       if (Value >= PromotedMin) return InRange;
10568       if (Value <= PromotedMax) return InRange;
10569       return InHole;
10570     }
10571 
10572     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10573     case -1: return Less;
10574     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10575     case 1:
10576       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10577       case -1: return InRange;
10578       case 0: return Max;
10579       case 1: return Greater;
10580       }
10581     }
10582 
10583     llvm_unreachable("impossible compare result");
10584   }
10585 
10586   static llvm::Optional<StringRef>
10587   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10588     if (Op == BO_Cmp) {
10589       ComparisonResult LTFlag = LT, GTFlag = GT;
10590       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10591 
10592       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10593       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10594       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10595       return llvm::None;
10596     }
10597 
10598     ComparisonResult TrueFlag, FalseFlag;
10599     if (Op == BO_EQ) {
10600       TrueFlag = EQ;
10601       FalseFlag = NE;
10602     } else if (Op == BO_NE) {
10603       TrueFlag = NE;
10604       FalseFlag = EQ;
10605     } else {
10606       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10607         TrueFlag = LT;
10608         FalseFlag = GE;
10609       } else {
10610         TrueFlag = GT;
10611         FalseFlag = LE;
10612       }
10613       if (Op == BO_GE || Op == BO_LE)
10614         std::swap(TrueFlag, FalseFlag);
10615     }
10616     if (R & TrueFlag)
10617       return StringRef("true");
10618     if (R & FalseFlag)
10619       return StringRef("false");
10620     return llvm::None;
10621   }
10622 };
10623 }
10624 
10625 static bool HasEnumType(Expr *E) {
10626   // Strip off implicit integral promotions.
10627   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10628     if (ICE->getCastKind() != CK_IntegralCast &&
10629         ICE->getCastKind() != CK_NoOp)
10630       break;
10631     E = ICE->getSubExpr();
10632   }
10633 
10634   return E->getType()->isEnumeralType();
10635 }
10636 
10637 static int classifyConstantValue(Expr *Constant) {
10638   // The values of this enumeration are used in the diagnostics
10639   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10640   enum ConstantValueKind {
10641     Miscellaneous = 0,
10642     LiteralTrue,
10643     LiteralFalse
10644   };
10645   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10646     return BL->getValue() ? ConstantValueKind::LiteralTrue
10647                           : ConstantValueKind::LiteralFalse;
10648   return ConstantValueKind::Miscellaneous;
10649 }
10650 
10651 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10652                                         Expr *Constant, Expr *Other,
10653                                         const llvm::APSInt &Value,
10654                                         bool RhsConstant) {
10655   if (S.inTemplateInstantiation())
10656     return false;
10657 
10658   Expr *OriginalOther = Other;
10659 
10660   Constant = Constant->IgnoreParenImpCasts();
10661   Other = Other->IgnoreParenImpCasts();
10662 
10663   // Suppress warnings on tautological comparisons between values of the same
10664   // enumeration type. There are only two ways we could warn on this:
10665   //  - If the constant is outside the range of representable values of
10666   //    the enumeration. In such a case, we should warn about the cast
10667   //    to enumeration type, not about the comparison.
10668   //  - If the constant is the maximum / minimum in-range value. For an
10669   //    enumeratin type, such comparisons can be meaningful and useful.
10670   if (Constant->getType()->isEnumeralType() &&
10671       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10672     return false;
10673 
10674   // TODO: Investigate using GetExprRange() to get tighter bounds
10675   // on the bit ranges.
10676   QualType OtherT = Other->getType();
10677   if (const auto *AT = OtherT->getAs<AtomicType>())
10678     OtherT = AT->getValueType();
10679   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10680 
10681   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10682   // (Namely, macOS).
10683   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10684                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10685                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10686 
10687   // Whether we're treating Other as being a bool because of the form of
10688   // expression despite it having another type (typically 'int' in C).
10689   bool OtherIsBooleanDespiteType =
10690       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10691   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10692     OtherRange = IntRange::forBoolType();
10693 
10694   // Determine the promoted range of the other type and see if a comparison of
10695   // the constant against that range is tautological.
10696   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10697                                    Value.isUnsigned());
10698   auto Cmp = OtherPromotedRange.compare(Value);
10699   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10700   if (!Result)
10701     return false;
10702 
10703   // Suppress the diagnostic for an in-range comparison if the constant comes
10704   // from a macro or enumerator. We don't want to diagnose
10705   //
10706   //   some_long_value <= INT_MAX
10707   //
10708   // when sizeof(int) == sizeof(long).
10709   bool InRange = Cmp & PromotedRange::InRangeFlag;
10710   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10711     return false;
10712 
10713   // If this is a comparison to an enum constant, include that
10714   // constant in the diagnostic.
10715   const EnumConstantDecl *ED = nullptr;
10716   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10717     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10718 
10719   // Should be enough for uint128 (39 decimal digits)
10720   SmallString<64> PrettySourceValue;
10721   llvm::raw_svector_ostream OS(PrettySourceValue);
10722   if (ED) {
10723     OS << '\'' << *ED << "' (" << Value << ")";
10724   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10725                Constant->IgnoreParenImpCasts())) {
10726     OS << (BL->getValue() ? "YES" : "NO");
10727   } else {
10728     OS << Value;
10729   }
10730 
10731   if (IsObjCSignedCharBool) {
10732     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10733                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10734                               << OS.str() << *Result);
10735     return true;
10736   }
10737 
10738   // FIXME: We use a somewhat different formatting for the in-range cases and
10739   // cases involving boolean values for historical reasons. We should pick a
10740   // consistent way of presenting these diagnostics.
10741   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10742 
10743     S.DiagRuntimeBehavior(
10744         E->getOperatorLoc(), E,
10745         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10746                          : diag::warn_tautological_bool_compare)
10747             << OS.str() << classifyConstantValue(Constant) << OtherT
10748             << OtherIsBooleanDespiteType << *Result
10749             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10750   } else {
10751     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10752                         ? (HasEnumType(OriginalOther)
10753                                ? diag::warn_unsigned_enum_always_true_comparison
10754                                : diag::warn_unsigned_always_true_comparison)
10755                         : diag::warn_tautological_constant_compare;
10756 
10757     S.Diag(E->getOperatorLoc(), Diag)
10758         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10759         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10760   }
10761 
10762   return true;
10763 }
10764 
10765 /// Analyze the operands of the given comparison.  Implements the
10766 /// fallback case from AnalyzeComparison.
10767 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10768   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10769   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10770 }
10771 
10772 /// Implements -Wsign-compare.
10773 ///
10774 /// \param E the binary operator to check for warnings
10775 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10776   // The type the comparison is being performed in.
10777   QualType T = E->getLHS()->getType();
10778 
10779   // Only analyze comparison operators where both sides have been converted to
10780   // the same type.
10781   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10782     return AnalyzeImpConvsInComparison(S, E);
10783 
10784   // Don't analyze value-dependent comparisons directly.
10785   if (E->isValueDependent())
10786     return AnalyzeImpConvsInComparison(S, E);
10787 
10788   Expr *LHS = E->getLHS();
10789   Expr *RHS = E->getRHS();
10790 
10791   if (T->isIntegralType(S.Context)) {
10792     llvm::APSInt RHSValue;
10793     llvm::APSInt LHSValue;
10794 
10795     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10796     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10797 
10798     // We don't care about expressions whose result is a constant.
10799     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10800       return AnalyzeImpConvsInComparison(S, E);
10801 
10802     // We only care about expressions where just one side is literal
10803     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10804       // Is the constant on the RHS or LHS?
10805       const bool RhsConstant = IsRHSIntegralLiteral;
10806       Expr *Const = RhsConstant ? RHS : LHS;
10807       Expr *Other = RhsConstant ? LHS : RHS;
10808       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10809 
10810       // Check whether an integer constant comparison results in a value
10811       // of 'true' or 'false'.
10812       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10813         return AnalyzeImpConvsInComparison(S, E);
10814     }
10815   }
10816 
10817   if (!T->hasUnsignedIntegerRepresentation()) {
10818     // We don't do anything special if this isn't an unsigned integral
10819     // comparison:  we're only interested in integral comparisons, and
10820     // signed comparisons only happen in cases we don't care to warn about.
10821     return AnalyzeImpConvsInComparison(S, E);
10822   }
10823 
10824   LHS = LHS->IgnoreParenImpCasts();
10825   RHS = RHS->IgnoreParenImpCasts();
10826 
10827   if (!S.getLangOpts().CPlusPlus) {
10828     // Avoid warning about comparison of integers with different signs when
10829     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10830     // the type of `E`.
10831     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10832       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10833     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10834       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10835   }
10836 
10837   // Check to see if one of the (unmodified) operands is of different
10838   // signedness.
10839   Expr *signedOperand, *unsignedOperand;
10840   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10841     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10842            "unsigned comparison between two signed integer expressions?");
10843     signedOperand = LHS;
10844     unsignedOperand = RHS;
10845   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10846     signedOperand = RHS;
10847     unsignedOperand = LHS;
10848   } else {
10849     return AnalyzeImpConvsInComparison(S, E);
10850   }
10851 
10852   // Otherwise, calculate the effective range of the signed operand.
10853   IntRange signedRange =
10854       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10855 
10856   // Go ahead and analyze implicit conversions in the operands.  Note
10857   // that we skip the implicit conversions on both sides.
10858   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10859   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10860 
10861   // If the signed range is non-negative, -Wsign-compare won't fire.
10862   if (signedRange.NonNegative)
10863     return;
10864 
10865   // For (in)equality comparisons, if the unsigned operand is a
10866   // constant which cannot collide with a overflowed signed operand,
10867   // then reinterpreting the signed operand as unsigned will not
10868   // change the result of the comparison.
10869   if (E->isEqualityOp()) {
10870     unsigned comparisonWidth = S.Context.getIntWidth(T);
10871     IntRange unsignedRange =
10872         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10873 
10874     // We should never be unable to prove that the unsigned operand is
10875     // non-negative.
10876     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10877 
10878     if (unsignedRange.Width < comparisonWidth)
10879       return;
10880   }
10881 
10882   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10883                         S.PDiag(diag::warn_mixed_sign_comparison)
10884                             << LHS->getType() << RHS->getType()
10885                             << LHS->getSourceRange() << RHS->getSourceRange());
10886 }
10887 
10888 /// Analyzes an attempt to assign the given value to a bitfield.
10889 ///
10890 /// Returns true if there was something fishy about the attempt.
10891 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10892                                       SourceLocation InitLoc) {
10893   assert(Bitfield->isBitField());
10894   if (Bitfield->isInvalidDecl())
10895     return false;
10896 
10897   // White-list bool bitfields.
10898   QualType BitfieldType = Bitfield->getType();
10899   if (BitfieldType->isBooleanType())
10900      return false;
10901 
10902   if (BitfieldType->isEnumeralType()) {
10903     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10904     // If the underlying enum type was not explicitly specified as an unsigned
10905     // type and the enum contain only positive values, MSVC++ will cause an
10906     // inconsistency by storing this as a signed type.
10907     if (S.getLangOpts().CPlusPlus11 &&
10908         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10909         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10910         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10911       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10912         << BitfieldEnumDecl->getNameAsString();
10913     }
10914   }
10915 
10916   if (Bitfield->getType()->isBooleanType())
10917     return false;
10918 
10919   // Ignore value- or type-dependent expressions.
10920   if (Bitfield->getBitWidth()->isValueDependent() ||
10921       Bitfield->getBitWidth()->isTypeDependent() ||
10922       Init->isValueDependent() ||
10923       Init->isTypeDependent())
10924     return false;
10925 
10926   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10927   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10928 
10929   Expr::EvalResult Result;
10930   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10931                                    Expr::SE_AllowSideEffects)) {
10932     // The RHS is not constant.  If the RHS has an enum type, make sure the
10933     // bitfield is wide enough to hold all the values of the enum without
10934     // truncation.
10935     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10936       EnumDecl *ED = EnumTy->getDecl();
10937       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10938 
10939       // Enum types are implicitly signed on Windows, so check if there are any
10940       // negative enumerators to see if the enum was intended to be signed or
10941       // not.
10942       bool SignedEnum = ED->getNumNegativeBits() > 0;
10943 
10944       // Check for surprising sign changes when assigning enum values to a
10945       // bitfield of different signedness.  If the bitfield is signed and we
10946       // have exactly the right number of bits to store this unsigned enum,
10947       // suggest changing the enum to an unsigned type. This typically happens
10948       // on Windows where unfixed enums always use an underlying type of 'int'.
10949       unsigned DiagID = 0;
10950       if (SignedEnum && !SignedBitfield) {
10951         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10952       } else if (SignedBitfield && !SignedEnum &&
10953                  ED->getNumPositiveBits() == FieldWidth) {
10954         DiagID = diag::warn_signed_bitfield_enum_conversion;
10955       }
10956 
10957       if (DiagID) {
10958         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10959         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10960         SourceRange TypeRange =
10961             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10962         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10963             << SignedEnum << TypeRange;
10964       }
10965 
10966       // Compute the required bitwidth. If the enum has negative values, we need
10967       // one more bit than the normal number of positive bits to represent the
10968       // sign bit.
10969       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10970                                                   ED->getNumNegativeBits())
10971                                        : ED->getNumPositiveBits();
10972 
10973       // Check the bitwidth.
10974       if (BitsNeeded > FieldWidth) {
10975         Expr *WidthExpr = Bitfield->getBitWidth();
10976         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10977             << Bitfield << ED;
10978         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10979             << BitsNeeded << ED << WidthExpr->getSourceRange();
10980       }
10981     }
10982 
10983     return false;
10984   }
10985 
10986   llvm::APSInt Value = Result.Val.getInt();
10987 
10988   unsigned OriginalWidth = Value.getBitWidth();
10989 
10990   if (!Value.isSigned() || Value.isNegative())
10991     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10992       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10993         OriginalWidth = Value.getMinSignedBits();
10994 
10995   if (OriginalWidth <= FieldWidth)
10996     return false;
10997 
10998   // Compute the value which the bitfield will contain.
10999   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11000   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11001 
11002   // Check whether the stored value is equal to the original value.
11003   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11004   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11005     return false;
11006 
11007   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11008   // therefore don't strictly fit into a signed bitfield of width 1.
11009   if (FieldWidth == 1 && Value == 1)
11010     return false;
11011 
11012   std::string PrettyValue = Value.toString(10);
11013   std::string PrettyTrunc = TruncatedValue.toString(10);
11014 
11015   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11016     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11017     << Init->getSourceRange();
11018 
11019   return true;
11020 }
11021 
11022 /// Analyze the given simple or compound assignment for warning-worthy
11023 /// operations.
11024 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11025   // Just recurse on the LHS.
11026   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11027 
11028   // We want to recurse on the RHS as normal unless we're assigning to
11029   // a bitfield.
11030   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11031     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11032                                   E->getOperatorLoc())) {
11033       // Recurse, ignoring any implicit conversions on the RHS.
11034       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11035                                         E->getOperatorLoc());
11036     }
11037   }
11038 
11039   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11040 
11041   // Diagnose implicitly sequentially-consistent atomic assignment.
11042   if (E->getLHS()->getType()->isAtomicType())
11043     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11044 }
11045 
11046 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11047 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11048                             SourceLocation CContext, unsigned diag,
11049                             bool pruneControlFlow = false) {
11050   if (pruneControlFlow) {
11051     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11052                           S.PDiag(diag)
11053                               << SourceType << T << E->getSourceRange()
11054                               << SourceRange(CContext));
11055     return;
11056   }
11057   S.Diag(E->getExprLoc(), diag)
11058     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11059 }
11060 
11061 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11062 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11063                             SourceLocation CContext,
11064                             unsigned diag, bool pruneControlFlow = false) {
11065   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11066 }
11067 
11068 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11069   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11070       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11071 }
11072 
11073 static void adornObjCBoolConversionDiagWithTernaryFixit(
11074     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11075   Expr *Ignored = SourceExpr->IgnoreImplicit();
11076   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11077     Ignored = OVE->getSourceExpr();
11078   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11079                      isa<BinaryOperator>(Ignored) ||
11080                      isa<CXXOperatorCallExpr>(Ignored);
11081   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11082   if (NeedsParens)
11083     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11084             << FixItHint::CreateInsertion(EndLoc, ")");
11085   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11086 }
11087 
11088 /// Diagnose an implicit cast from a floating point value to an integer value.
11089 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11090                                     SourceLocation CContext) {
11091   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11092   const bool PruneWarnings = S.inTemplateInstantiation();
11093 
11094   Expr *InnerE = E->IgnoreParenImpCasts();
11095   // We also want to warn on, e.g., "int i = -1.234"
11096   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11097     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11098       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11099 
11100   const bool IsLiteral =
11101       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11102 
11103   llvm::APFloat Value(0.0);
11104   bool IsConstant =
11105     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11106   if (!IsConstant) {
11107     if (isObjCSignedCharBool(S, T)) {
11108       return adornObjCBoolConversionDiagWithTernaryFixit(
11109           S, E,
11110           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11111               << E->getType());
11112     }
11113 
11114     return DiagnoseImpCast(S, E, T, CContext,
11115                            diag::warn_impcast_float_integer, PruneWarnings);
11116   }
11117 
11118   bool isExact = false;
11119 
11120   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11121                             T->hasUnsignedIntegerRepresentation());
11122   llvm::APFloat::opStatus Result = Value.convertToInteger(
11123       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11124 
11125   // FIXME: Force the precision of the source value down so we don't print
11126   // digits which are usually useless (we don't really care here if we
11127   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11128   // would automatically print the shortest representation, but it's a bit
11129   // tricky to implement.
11130   SmallString<16> PrettySourceValue;
11131   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11132   precision = (precision * 59 + 195) / 196;
11133   Value.toString(PrettySourceValue, precision);
11134 
11135   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11136     return adornObjCBoolConversionDiagWithTernaryFixit(
11137         S, E,
11138         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11139             << PrettySourceValue);
11140   }
11141 
11142   if (Result == llvm::APFloat::opOK && isExact) {
11143     if (IsLiteral) return;
11144     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11145                            PruneWarnings);
11146   }
11147 
11148   // Conversion of a floating-point value to a non-bool integer where the
11149   // integral part cannot be represented by the integer type is undefined.
11150   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11151     return DiagnoseImpCast(
11152         S, E, T, CContext,
11153         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11154                   : diag::warn_impcast_float_to_integer_out_of_range,
11155         PruneWarnings);
11156 
11157   unsigned DiagID = 0;
11158   if (IsLiteral) {
11159     // Warn on floating point literal to integer.
11160     DiagID = diag::warn_impcast_literal_float_to_integer;
11161   } else if (IntegerValue == 0) {
11162     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11163       return DiagnoseImpCast(S, E, T, CContext,
11164                              diag::warn_impcast_float_integer, PruneWarnings);
11165     }
11166     // Warn on non-zero to zero conversion.
11167     DiagID = diag::warn_impcast_float_to_integer_zero;
11168   } else {
11169     if (IntegerValue.isUnsigned()) {
11170       if (!IntegerValue.isMaxValue()) {
11171         return DiagnoseImpCast(S, E, T, CContext,
11172                                diag::warn_impcast_float_integer, PruneWarnings);
11173       }
11174     } else {  // IntegerValue.isSigned()
11175       if (!IntegerValue.isMaxSignedValue() &&
11176           !IntegerValue.isMinSignedValue()) {
11177         return DiagnoseImpCast(S, E, T, CContext,
11178                                diag::warn_impcast_float_integer, PruneWarnings);
11179       }
11180     }
11181     // Warn on evaluatable floating point expression to integer conversion.
11182     DiagID = diag::warn_impcast_float_to_integer;
11183   }
11184 
11185   SmallString<16> PrettyTargetValue;
11186   if (IsBool)
11187     PrettyTargetValue = Value.isZero() ? "false" : "true";
11188   else
11189     IntegerValue.toString(PrettyTargetValue);
11190 
11191   if (PruneWarnings) {
11192     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11193                           S.PDiag(DiagID)
11194                               << E->getType() << T.getUnqualifiedType()
11195                               << PrettySourceValue << PrettyTargetValue
11196                               << E->getSourceRange() << SourceRange(CContext));
11197   } else {
11198     S.Diag(E->getExprLoc(), DiagID)
11199         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11200         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11201   }
11202 }
11203 
11204 /// Analyze the given compound assignment for the possible losing of
11205 /// floating-point precision.
11206 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11207   assert(isa<CompoundAssignOperator>(E) &&
11208          "Must be compound assignment operation");
11209   // Recurse on the LHS and RHS in here
11210   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11211   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11212 
11213   if (E->getLHS()->getType()->isAtomicType())
11214     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11215 
11216   // Now check the outermost expression
11217   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11218   const auto *RBT = cast<CompoundAssignOperator>(E)
11219                         ->getComputationResultType()
11220                         ->getAs<BuiltinType>();
11221 
11222   // The below checks assume source is floating point.
11223   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11224 
11225   // If source is floating point but target is an integer.
11226   if (ResultBT->isInteger())
11227     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11228                            E->getExprLoc(), diag::warn_impcast_float_integer);
11229 
11230   if (!ResultBT->isFloatingPoint())
11231     return;
11232 
11233   // If both source and target are floating points, warn about losing precision.
11234   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11235       QualType(ResultBT, 0), QualType(RBT, 0));
11236   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11237     // warn about dropping FP rank.
11238     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11239                     diag::warn_impcast_float_result_precision);
11240 }
11241 
11242 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11243                                       IntRange Range) {
11244   if (!Range.Width) return "0";
11245 
11246   llvm::APSInt ValueInRange = Value;
11247   ValueInRange.setIsSigned(!Range.NonNegative);
11248   ValueInRange = ValueInRange.trunc(Range.Width);
11249   return ValueInRange.toString(10);
11250 }
11251 
11252 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11253   if (!isa<ImplicitCastExpr>(Ex))
11254     return false;
11255 
11256   Expr *InnerE = Ex->IgnoreParenImpCasts();
11257   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11258   const Type *Source =
11259     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11260   if (Target->isDependentType())
11261     return false;
11262 
11263   const BuiltinType *FloatCandidateBT =
11264     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11265   const Type *BoolCandidateType = ToBool ? Target : Source;
11266 
11267   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11268           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11269 }
11270 
11271 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11272                                              SourceLocation CC) {
11273   unsigned NumArgs = TheCall->getNumArgs();
11274   for (unsigned i = 0; i < NumArgs; ++i) {
11275     Expr *CurrA = TheCall->getArg(i);
11276     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11277       continue;
11278 
11279     bool IsSwapped = ((i > 0) &&
11280         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11281     IsSwapped |= ((i < (NumArgs - 1)) &&
11282         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11283     if (IsSwapped) {
11284       // Warn on this floating-point to bool conversion.
11285       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11286                       CurrA->getType(), CC,
11287                       diag::warn_impcast_floating_point_to_bool);
11288     }
11289   }
11290 }
11291 
11292 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11293                                    SourceLocation CC) {
11294   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11295                         E->getExprLoc()))
11296     return;
11297 
11298   // Don't warn on functions which have return type nullptr_t.
11299   if (isa<CallExpr>(E))
11300     return;
11301 
11302   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11303   const Expr::NullPointerConstantKind NullKind =
11304       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11305   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11306     return;
11307 
11308   // Return if target type is a safe conversion.
11309   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11310       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11311     return;
11312 
11313   SourceLocation Loc = E->getSourceRange().getBegin();
11314 
11315   // Venture through the macro stacks to get to the source of macro arguments.
11316   // The new location is a better location than the complete location that was
11317   // passed in.
11318   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11319   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11320 
11321   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11322   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11323     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11324         Loc, S.SourceMgr, S.getLangOpts());
11325     if (MacroName == "NULL")
11326       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11327   }
11328 
11329   // Only warn if the null and context location are in the same macro expansion.
11330   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11331     return;
11332 
11333   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11334       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11335       << FixItHint::CreateReplacement(Loc,
11336                                       S.getFixItZeroLiteralForType(T, Loc));
11337 }
11338 
11339 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11340                                   ObjCArrayLiteral *ArrayLiteral);
11341 
11342 static void
11343 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11344                            ObjCDictionaryLiteral *DictionaryLiteral);
11345 
11346 /// Check a single element within a collection literal against the
11347 /// target element type.
11348 static void checkObjCCollectionLiteralElement(Sema &S,
11349                                               QualType TargetElementType,
11350                                               Expr *Element,
11351                                               unsigned ElementKind) {
11352   // Skip a bitcast to 'id' or qualified 'id'.
11353   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11354     if (ICE->getCastKind() == CK_BitCast &&
11355         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11356       Element = ICE->getSubExpr();
11357   }
11358 
11359   QualType ElementType = Element->getType();
11360   ExprResult ElementResult(Element);
11361   if (ElementType->getAs<ObjCObjectPointerType>() &&
11362       S.CheckSingleAssignmentConstraints(TargetElementType,
11363                                          ElementResult,
11364                                          false, false)
11365         != Sema::Compatible) {
11366     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11367         << ElementType << ElementKind << TargetElementType
11368         << Element->getSourceRange();
11369   }
11370 
11371   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11372     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11373   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11374     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11375 }
11376 
11377 /// Check an Objective-C array literal being converted to the given
11378 /// target type.
11379 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11380                                   ObjCArrayLiteral *ArrayLiteral) {
11381   if (!S.NSArrayDecl)
11382     return;
11383 
11384   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11385   if (!TargetObjCPtr)
11386     return;
11387 
11388   if (TargetObjCPtr->isUnspecialized() ||
11389       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11390         != S.NSArrayDecl->getCanonicalDecl())
11391     return;
11392 
11393   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11394   if (TypeArgs.size() != 1)
11395     return;
11396 
11397   QualType TargetElementType = TypeArgs[0];
11398   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11399     checkObjCCollectionLiteralElement(S, TargetElementType,
11400                                       ArrayLiteral->getElement(I),
11401                                       0);
11402   }
11403 }
11404 
11405 /// Check an Objective-C dictionary literal being converted to the given
11406 /// target type.
11407 static void
11408 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11409                            ObjCDictionaryLiteral *DictionaryLiteral) {
11410   if (!S.NSDictionaryDecl)
11411     return;
11412 
11413   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11414   if (!TargetObjCPtr)
11415     return;
11416 
11417   if (TargetObjCPtr->isUnspecialized() ||
11418       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11419         != S.NSDictionaryDecl->getCanonicalDecl())
11420     return;
11421 
11422   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11423   if (TypeArgs.size() != 2)
11424     return;
11425 
11426   QualType TargetKeyType = TypeArgs[0];
11427   QualType TargetObjectType = TypeArgs[1];
11428   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11429     auto Element = DictionaryLiteral->getKeyValueElement(I);
11430     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11431     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11432   }
11433 }
11434 
11435 // Helper function to filter out cases for constant width constant conversion.
11436 // Don't warn on char array initialization or for non-decimal values.
11437 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11438                                           SourceLocation CC) {
11439   // If initializing from a constant, and the constant starts with '0',
11440   // then it is a binary, octal, or hexadecimal.  Allow these constants
11441   // to fill all the bits, even if there is a sign change.
11442   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11443     const char FirstLiteralCharacter =
11444         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11445     if (FirstLiteralCharacter == '0')
11446       return false;
11447   }
11448 
11449   // If the CC location points to a '{', and the type is char, then assume
11450   // assume it is an array initialization.
11451   if (CC.isValid() && T->isCharType()) {
11452     const char FirstContextCharacter =
11453         S.getSourceManager().getCharacterData(CC)[0];
11454     if (FirstContextCharacter == '{')
11455       return false;
11456   }
11457 
11458   return true;
11459 }
11460 
11461 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11462   const auto *IL = dyn_cast<IntegerLiteral>(E);
11463   if (!IL) {
11464     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11465       if (UO->getOpcode() == UO_Minus)
11466         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11467     }
11468   }
11469 
11470   return IL;
11471 }
11472 
11473 static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
11474                                           Expr *LHS, Expr *RHS) {
11475   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
11476   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
11477 
11478   const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
11479   if (!LHSEnumType)
11480     return;
11481   const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
11482   if (!RHSEnumType)
11483     return;
11484 
11485   // Ignore anonymous enums.
11486   if (!LHSEnumType->getDecl()->hasNameForLinkage())
11487     return;
11488   if (!RHSEnumType->getDecl()->hasNameForLinkage())
11489     return;
11490 
11491   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
11492     return;
11493 
11494   S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
11495       << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
11496       << RHS->getSourceRange();
11497 }
11498 
11499 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11500   E = E->IgnoreParenImpCasts();
11501   SourceLocation ExprLoc = E->getExprLoc();
11502 
11503   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11504     BinaryOperator::Opcode Opc = BO->getOpcode();
11505     Expr::EvalResult Result;
11506     // Do not diagnose unsigned shifts.
11507     if (Opc == BO_Shl) {
11508       const auto *LHS = getIntegerLiteral(BO->getLHS());
11509       const auto *RHS = getIntegerLiteral(BO->getRHS());
11510       if (LHS && LHS->getValue() == 0)
11511         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11512       else if (!E->isValueDependent() && LHS && RHS &&
11513                RHS->getValue().isNonNegative() &&
11514                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11515         S.Diag(ExprLoc, diag::warn_left_shift_always)
11516             << (Result.Val.getInt() != 0);
11517       else if (E->getType()->isSignedIntegerType())
11518         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11519     }
11520   }
11521 
11522   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11523     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11524     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11525     if (!LHS || !RHS)
11526       return;
11527     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11528         (RHS->getValue() == 0 || RHS->getValue() == 1))
11529       // Do not diagnose common idioms.
11530       return;
11531     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11532       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11533   }
11534 }
11535 
11536 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11537                                     SourceLocation CC,
11538                                     bool *ICContext = nullptr,
11539                                     bool IsListInit = false) {
11540   if (E->isTypeDependent() || E->isValueDependent()) return;
11541 
11542   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11543   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11544   if (Source == Target) return;
11545   if (Target->isDependentType()) return;
11546 
11547   // If the conversion context location is invalid don't complain. We also
11548   // don't want to emit a warning if the issue occurs from the expansion of
11549   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11550   // delay this check as long as possible. Once we detect we are in that
11551   // scenario, we just return.
11552   if (CC.isInvalid())
11553     return;
11554 
11555   if (Source->isAtomicType())
11556     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11557 
11558   // Diagnose implicit casts to bool.
11559   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11560     if (isa<StringLiteral>(E))
11561       // Warn on string literal to bool.  Checks for string literals in logical
11562       // and expressions, for instance, assert(0 && "error here"), are
11563       // prevented by a check in AnalyzeImplicitConversions().
11564       return DiagnoseImpCast(S, E, T, CC,
11565                              diag::warn_impcast_string_literal_to_bool);
11566     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11567         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11568       // This covers the literal expressions that evaluate to Objective-C
11569       // objects.
11570       return DiagnoseImpCast(S, E, T, CC,
11571                              diag::warn_impcast_objective_c_literal_to_bool);
11572     }
11573     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11574       // Warn on pointer to bool conversion that is always true.
11575       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11576                                      SourceRange(CC));
11577     }
11578   }
11579 
11580   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11581   // is a typedef for signed char (macOS), then that constant value has to be 1
11582   // or 0.
11583   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11584     Expr::EvalResult Result;
11585     if (E->EvaluateAsInt(Result, S.getASTContext(),
11586                          Expr::SE_AllowSideEffects)) {
11587       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11588         adornObjCBoolConversionDiagWithTernaryFixit(
11589             S, E,
11590             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11591                 << Result.Val.getInt().toString(10));
11592       }
11593       return;
11594     }
11595   }
11596 
11597   // Check implicit casts from Objective-C collection literals to specialized
11598   // collection types, e.g., NSArray<NSString *> *.
11599   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11600     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11601   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11602     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11603 
11604   // Strip vector types.
11605   if (isa<VectorType>(Source)) {
11606     if (!isa<VectorType>(Target)) {
11607       if (S.SourceMgr.isInSystemMacro(CC))
11608         return;
11609       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11610     }
11611 
11612     // If the vector cast is cast between two vectors of the same size, it is
11613     // a bitcast, not a conversion.
11614     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11615       return;
11616 
11617     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11618     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11619   }
11620   if (auto VecTy = dyn_cast<VectorType>(Target))
11621     Target = VecTy->getElementType().getTypePtr();
11622 
11623   // Strip complex types.
11624   if (isa<ComplexType>(Source)) {
11625     if (!isa<ComplexType>(Target)) {
11626       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11627         return;
11628 
11629       return DiagnoseImpCast(S, E, T, CC,
11630                              S.getLangOpts().CPlusPlus
11631                                  ? diag::err_impcast_complex_scalar
11632                                  : diag::warn_impcast_complex_scalar);
11633     }
11634 
11635     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11636     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11637   }
11638 
11639   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11640   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11641 
11642   // If the source is floating point...
11643   if (SourceBT && SourceBT->isFloatingPoint()) {
11644     // ...and the target is floating point...
11645     if (TargetBT && TargetBT->isFloatingPoint()) {
11646       // ...then warn if we're dropping FP rank.
11647 
11648       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11649           QualType(SourceBT, 0), QualType(TargetBT, 0));
11650       if (Order > 0) {
11651         // Don't warn about float constants that are precisely
11652         // representable in the target type.
11653         Expr::EvalResult result;
11654         if (E->EvaluateAsRValue(result, S.Context)) {
11655           // Value might be a float, a float vector, or a float complex.
11656           if (IsSameFloatAfterCast(result.Val,
11657                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11658                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11659             return;
11660         }
11661 
11662         if (S.SourceMgr.isInSystemMacro(CC))
11663           return;
11664 
11665         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11666       }
11667       // ... or possibly if we're increasing rank, too
11668       else if (Order < 0) {
11669         if (S.SourceMgr.isInSystemMacro(CC))
11670           return;
11671 
11672         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11673       }
11674       return;
11675     }
11676 
11677     // If the target is integral, always warn.
11678     if (TargetBT && TargetBT->isInteger()) {
11679       if (S.SourceMgr.isInSystemMacro(CC))
11680         return;
11681 
11682       DiagnoseFloatingImpCast(S, E, T, CC);
11683     }
11684 
11685     // Detect the case where a call result is converted from floating-point to
11686     // to bool, and the final argument to the call is converted from bool, to
11687     // discover this typo:
11688     //
11689     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11690     //
11691     // FIXME: This is an incredibly special case; is there some more general
11692     // way to detect this class of misplaced-parentheses bug?
11693     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11694       // Check last argument of function call to see if it is an
11695       // implicit cast from a type matching the type the result
11696       // is being cast to.
11697       CallExpr *CEx = cast<CallExpr>(E);
11698       if (unsigned NumArgs = CEx->getNumArgs()) {
11699         Expr *LastA = CEx->getArg(NumArgs - 1);
11700         Expr *InnerE = LastA->IgnoreParenImpCasts();
11701         if (isa<ImplicitCastExpr>(LastA) &&
11702             InnerE->getType()->isBooleanType()) {
11703           // Warn on this floating-point to bool conversion
11704           DiagnoseImpCast(S, E, T, CC,
11705                           diag::warn_impcast_floating_point_to_bool);
11706         }
11707       }
11708     }
11709     return;
11710   }
11711 
11712   // Valid casts involving fixed point types should be accounted for here.
11713   if (Source->isFixedPointType()) {
11714     if (Target->isUnsaturatedFixedPointType()) {
11715       Expr::EvalResult Result;
11716       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11717                                   S.isConstantEvaluated())) {
11718         APFixedPoint Value = Result.Val.getFixedPoint();
11719         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11720         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11721         if (Value > MaxVal || Value < MinVal) {
11722           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11723                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11724                                     << Value.toString() << T
11725                                     << E->getSourceRange()
11726                                     << clang::SourceRange(CC));
11727           return;
11728         }
11729       }
11730     } else if (Target->isIntegerType()) {
11731       Expr::EvalResult Result;
11732       if (!S.isConstantEvaluated() &&
11733           E->EvaluateAsFixedPoint(Result, S.Context,
11734                                   Expr::SE_AllowSideEffects)) {
11735         APFixedPoint FXResult = Result.Val.getFixedPoint();
11736 
11737         bool Overflowed;
11738         llvm::APSInt IntResult = FXResult.convertToInt(
11739             S.Context.getIntWidth(T),
11740             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11741 
11742         if (Overflowed) {
11743           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11744                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11745                                     << FXResult.toString() << T
11746                                     << E->getSourceRange()
11747                                     << clang::SourceRange(CC));
11748           return;
11749         }
11750       }
11751     }
11752   } else if (Target->isUnsaturatedFixedPointType()) {
11753     if (Source->isIntegerType()) {
11754       Expr::EvalResult Result;
11755       if (!S.isConstantEvaluated() &&
11756           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11757         llvm::APSInt Value = Result.Val.getInt();
11758 
11759         bool Overflowed;
11760         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11761             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11762 
11763         if (Overflowed) {
11764           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11765                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11766                                     << Value.toString(/*Radix=*/10) << T
11767                                     << E->getSourceRange()
11768                                     << clang::SourceRange(CC));
11769           return;
11770         }
11771       }
11772     }
11773   }
11774 
11775   // If we are casting an integer type to a floating point type without
11776   // initialization-list syntax, we might lose accuracy if the floating
11777   // point type has a narrower significand than the integer type.
11778   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11779       TargetBT->isFloatingType() && !IsListInit) {
11780     // Determine the number of precision bits in the source integer type.
11781     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11782     unsigned int SourcePrecision = SourceRange.Width;
11783 
11784     // Determine the number of precision bits in the
11785     // target floating point type.
11786     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11787         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11788 
11789     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11790         SourcePrecision > TargetPrecision) {
11791 
11792       llvm::APSInt SourceInt;
11793       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11794         // If the source integer is a constant, convert it to the target
11795         // floating point type. Issue a warning if the value changes
11796         // during the whole conversion.
11797         llvm::APFloat TargetFloatValue(
11798             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11799         llvm::APFloat::opStatus ConversionStatus =
11800             TargetFloatValue.convertFromAPInt(
11801                 SourceInt, SourceBT->isSignedInteger(),
11802                 llvm::APFloat::rmNearestTiesToEven);
11803 
11804         if (ConversionStatus != llvm::APFloat::opOK) {
11805           std::string PrettySourceValue = SourceInt.toString(10);
11806           SmallString<32> PrettyTargetValue;
11807           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11808 
11809           S.DiagRuntimeBehavior(
11810               E->getExprLoc(), E,
11811               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11812                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11813                   << E->getSourceRange() << clang::SourceRange(CC));
11814         }
11815       } else {
11816         // Otherwise, the implicit conversion may lose precision.
11817         DiagnoseImpCast(S, E, T, CC,
11818                         diag::warn_impcast_integer_float_precision);
11819       }
11820     }
11821   }
11822 
11823   DiagnoseNullConversion(S, E, T, CC);
11824 
11825   S.DiscardMisalignedMemberAddress(Target, E);
11826 
11827   if (Target->isBooleanType())
11828     DiagnoseIntInBoolContext(S, E);
11829 
11830   if (!Source->isIntegerType() || !Target->isIntegerType())
11831     return;
11832 
11833   // TODO: remove this early return once the false positives for constant->bool
11834   // in templates, macros, etc, are reduced or removed.
11835   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11836     return;
11837 
11838   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11839       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
11840     return adornObjCBoolConversionDiagWithTernaryFixit(
11841         S, E,
11842         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11843             << E->getType());
11844   }
11845 
11846   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11847   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11848 
11849   if (SourceRange.Width > TargetRange.Width) {
11850     // If the source is a constant, use a default-on diagnostic.
11851     // TODO: this should happen for bitfield stores, too.
11852     Expr::EvalResult Result;
11853     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11854                          S.isConstantEvaluated())) {
11855       llvm::APSInt Value(32);
11856       Value = Result.Val.getInt();
11857 
11858       if (S.SourceMgr.isInSystemMacro(CC))
11859         return;
11860 
11861       std::string PrettySourceValue = Value.toString(10);
11862       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11863 
11864       S.DiagRuntimeBehavior(
11865           E->getExprLoc(), E,
11866           S.PDiag(diag::warn_impcast_integer_precision_constant)
11867               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11868               << E->getSourceRange() << clang::SourceRange(CC));
11869       return;
11870     }
11871 
11872     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11873     if (S.SourceMgr.isInSystemMacro(CC))
11874       return;
11875 
11876     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11877       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11878                              /* pruneControlFlow */ true);
11879     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11880   }
11881 
11882   if (TargetRange.Width > SourceRange.Width) {
11883     if (auto *UO = dyn_cast<UnaryOperator>(E))
11884       if (UO->getOpcode() == UO_Minus)
11885         if (Source->isUnsignedIntegerType()) {
11886           if (Target->isUnsignedIntegerType())
11887             return DiagnoseImpCast(S, E, T, CC,
11888                                    diag::warn_impcast_high_order_zero_bits);
11889           if (Target->isSignedIntegerType())
11890             return DiagnoseImpCast(S, E, T, CC,
11891                                    diag::warn_impcast_nonnegative_result);
11892         }
11893   }
11894 
11895   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11896       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11897     // Warn when doing a signed to signed conversion, warn if the positive
11898     // source value is exactly the width of the target type, which will
11899     // cause a negative value to be stored.
11900 
11901     Expr::EvalResult Result;
11902     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11903         !S.SourceMgr.isInSystemMacro(CC)) {
11904       llvm::APSInt Value = Result.Val.getInt();
11905       if (isSameWidthConstantConversion(S, E, T, CC)) {
11906         std::string PrettySourceValue = Value.toString(10);
11907         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11908 
11909         S.DiagRuntimeBehavior(
11910             E->getExprLoc(), E,
11911             S.PDiag(diag::warn_impcast_integer_precision_constant)
11912                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11913                 << E->getSourceRange() << clang::SourceRange(CC));
11914         return;
11915       }
11916     }
11917 
11918     // Fall through for non-constants to give a sign conversion warning.
11919   }
11920 
11921   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11922       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11923        SourceRange.Width == TargetRange.Width)) {
11924     if (S.SourceMgr.isInSystemMacro(CC))
11925       return;
11926 
11927     unsigned DiagID = diag::warn_impcast_integer_sign;
11928 
11929     // Traditionally, gcc has warned about this under -Wsign-compare.
11930     // We also want to warn about it in -Wconversion.
11931     // So if -Wconversion is off, use a completely identical diagnostic
11932     // in the sign-compare group.
11933     // The conditional-checking code will
11934     if (ICContext) {
11935       DiagID = diag::warn_impcast_integer_sign_conditional;
11936       *ICContext = true;
11937     }
11938 
11939     return DiagnoseImpCast(S, E, T, CC, DiagID);
11940   }
11941 
11942   // Diagnose conversions between different enumeration types.
11943   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11944   // type, to give us better diagnostics.
11945   QualType SourceType = E->getType();
11946   if (!S.getLangOpts().CPlusPlus) {
11947     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11948       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11949         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11950         SourceType = S.Context.getTypeDeclType(Enum);
11951         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11952       }
11953   }
11954 
11955   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11956     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11957       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11958           TargetEnum->getDecl()->hasNameForLinkage() &&
11959           SourceEnum != TargetEnum) {
11960         if (S.SourceMgr.isInSystemMacro(CC))
11961           return;
11962 
11963         return DiagnoseImpCast(S, E, SourceType, T, CC,
11964                                diag::warn_impcast_different_enum_types);
11965       }
11966 }
11967 
11968 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11969                                      SourceLocation CC, QualType T);
11970 
11971 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11972                                     SourceLocation CC, bool &ICContext) {
11973   E = E->IgnoreParenImpCasts();
11974 
11975   if (isa<ConditionalOperator>(E))
11976     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11977 
11978   AnalyzeImplicitConversions(S, E, CC);
11979   if (E->getType() != T)
11980     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11981 }
11982 
11983 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11984                                      SourceLocation CC, QualType T) {
11985   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11986 
11987   bool Suspicious = false;
11988   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11989   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11990   CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
11991                                 E->getFalseExpr());
11992 
11993   if (T->isBooleanType())
11994     DiagnoseIntInBoolContext(S, E);
11995 
11996   // If -Wconversion would have warned about either of the candidates
11997   // for a signedness conversion to the context type...
11998   if (!Suspicious) return;
11999 
12000   // ...but it's currently ignored...
12001   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12002     return;
12003 
12004   // ...then check whether it would have warned about either of the
12005   // candidates for a signedness conversion to the condition type.
12006   if (E->getType() == T) return;
12007 
12008   Suspicious = false;
12009   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
12010                           E->getType(), CC, &Suspicious);
12011   if (!Suspicious)
12012     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12013                             E->getType(), CC, &Suspicious);
12014 }
12015 
12016 /// Check conversion of given expression to boolean.
12017 /// Input argument E is a logical expression.
12018 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12019   if (S.getLangOpts().Bool)
12020     return;
12021   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12022     return;
12023   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12024 }
12025 
12026 /// AnalyzeImplicitConversions - Find and report any interesting
12027 /// implicit conversions in the given expression.  There are a couple
12028 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12029 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12030                                        bool IsListInit/*= false*/) {
12031   QualType T = OrigE->getType();
12032   Expr *E = OrigE->IgnoreParenImpCasts();
12033 
12034   // Propagate whether we are in a C++ list initialization expression.
12035   // If so, we do not issue warnings for implicit int-float conversion
12036   // precision loss, because C++11 narrowing already handles it.
12037   IsListInit =
12038       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12039 
12040   if (E->isTypeDependent() || E->isValueDependent())
12041     return;
12042 
12043   if (const auto *UO = dyn_cast<UnaryOperator>(E))
12044     if (UO->getOpcode() == UO_Not &&
12045         UO->getSubExpr()->isKnownToHaveBooleanValue())
12046       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12047           << OrigE->getSourceRange() << T->isBooleanType()
12048           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12049 
12050   // For conditional operators, we analyze the arguments as if they
12051   // were being fed directly into the output.
12052   if (isa<ConditionalOperator>(E)) {
12053     ConditionalOperator *CO = cast<ConditionalOperator>(E);
12054     CheckConditionalOperator(S, CO, CC, T);
12055     return;
12056   }
12057 
12058   // Check implicit argument conversions for function calls.
12059   if (CallExpr *Call = dyn_cast<CallExpr>(E))
12060     CheckImplicitArgumentConversions(S, Call, CC);
12061 
12062   // Go ahead and check any implicit conversions we might have skipped.
12063   // The non-canonical typecheck is just an optimization;
12064   // CheckImplicitConversion will filter out dead implicit conversions.
12065   if (E->getType() != T)
12066     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
12067 
12068   // Now continue drilling into this expression.
12069 
12070   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12071     // The bound subexpressions in a PseudoObjectExpr are not reachable
12072     // as transitive children.
12073     // FIXME: Use a more uniform representation for this.
12074     for (auto *SE : POE->semantics())
12075       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12076         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
12077   }
12078 
12079   // Skip past explicit casts.
12080   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12081     E = CE->getSubExpr()->IgnoreParenImpCasts();
12082     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12083       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12084     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
12085   }
12086 
12087   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12088     // Do a somewhat different check with comparison operators.
12089     if (BO->isComparisonOp())
12090       return AnalyzeComparison(S, BO);
12091 
12092     // And with simple assignments.
12093     if (BO->getOpcode() == BO_Assign)
12094       return AnalyzeAssignment(S, BO);
12095     // And with compound assignments.
12096     if (BO->isAssignmentOp())
12097       return AnalyzeCompoundAssignment(S, BO);
12098   }
12099 
12100   // These break the otherwise-useful invariant below.  Fortunately,
12101   // we don't really need to recurse into them, because any internal
12102   // expressions should have been analyzed already when they were
12103   // built into statements.
12104   if (isa<StmtExpr>(E)) return;
12105 
12106   // Don't descend into unevaluated contexts.
12107   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12108 
12109   // Now just recurse over the expression's children.
12110   CC = E->getExprLoc();
12111   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12112   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12113   for (Stmt *SubStmt : E->children()) {
12114     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12115     if (!ChildExpr)
12116       continue;
12117 
12118     if (IsLogicalAndOperator &&
12119         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12120       // Ignore checking string literals that are in logical and operators.
12121       // This is a common pattern for asserts.
12122       continue;
12123     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
12124   }
12125 
12126   if (BO && BO->isLogicalOp()) {
12127     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12128     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12129       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12130 
12131     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12132     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12133       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12134   }
12135 
12136   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12137     if (U->getOpcode() == UO_LNot) {
12138       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12139     } else if (U->getOpcode() != UO_AddrOf) {
12140       if (U->getSubExpr()->getType()->isAtomicType())
12141         S.Diag(U->getSubExpr()->getBeginLoc(),
12142                diag::warn_atomic_implicit_seq_cst);
12143     }
12144   }
12145 }
12146 
12147 /// Diagnose integer type and any valid implicit conversion to it.
12148 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12149   // Taking into account implicit conversions,
12150   // allow any integer.
12151   if (!E->getType()->isIntegerType()) {
12152     S.Diag(E->getBeginLoc(),
12153            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12154     return true;
12155   }
12156   // Potentially emit standard warnings for implicit conversions if enabled
12157   // using -Wconversion.
12158   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12159   return false;
12160 }
12161 
12162 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12163 // Returns true when emitting a warning about taking the address of a reference.
12164 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12165                               const PartialDiagnostic &PD) {
12166   E = E->IgnoreParenImpCasts();
12167 
12168   const FunctionDecl *FD = nullptr;
12169 
12170   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12171     if (!DRE->getDecl()->getType()->isReferenceType())
12172       return false;
12173   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12174     if (!M->getMemberDecl()->getType()->isReferenceType())
12175       return false;
12176   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12177     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12178       return false;
12179     FD = Call->getDirectCallee();
12180   } else {
12181     return false;
12182   }
12183 
12184   SemaRef.Diag(E->getExprLoc(), PD);
12185 
12186   // If possible, point to location of function.
12187   if (FD) {
12188     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12189   }
12190 
12191   return true;
12192 }
12193 
12194 // Returns true if the SourceLocation is expanded from any macro body.
12195 // Returns false if the SourceLocation is invalid, is from not in a macro
12196 // expansion, or is from expanded from a top-level macro argument.
12197 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12198   if (Loc.isInvalid())
12199     return false;
12200 
12201   while (Loc.isMacroID()) {
12202     if (SM.isMacroBodyExpansion(Loc))
12203       return true;
12204     Loc = SM.getImmediateMacroCallerLoc(Loc);
12205   }
12206 
12207   return false;
12208 }
12209 
12210 /// Diagnose pointers that are always non-null.
12211 /// \param E the expression containing the pointer
12212 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12213 /// compared to a null pointer
12214 /// \param IsEqual True when the comparison is equal to a null pointer
12215 /// \param Range Extra SourceRange to highlight in the diagnostic
12216 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12217                                         Expr::NullPointerConstantKind NullKind,
12218                                         bool IsEqual, SourceRange Range) {
12219   if (!E)
12220     return;
12221 
12222   // Don't warn inside macros.
12223   if (E->getExprLoc().isMacroID()) {
12224     const SourceManager &SM = getSourceManager();
12225     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12226         IsInAnyMacroBody(SM, Range.getBegin()))
12227       return;
12228   }
12229   E = E->IgnoreImpCasts();
12230 
12231   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12232 
12233   if (isa<CXXThisExpr>(E)) {
12234     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12235                                 : diag::warn_this_bool_conversion;
12236     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12237     return;
12238   }
12239 
12240   bool IsAddressOf = false;
12241 
12242   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12243     if (UO->getOpcode() != UO_AddrOf)
12244       return;
12245     IsAddressOf = true;
12246     E = UO->getSubExpr();
12247   }
12248 
12249   if (IsAddressOf) {
12250     unsigned DiagID = IsCompare
12251                           ? diag::warn_address_of_reference_null_compare
12252                           : diag::warn_address_of_reference_bool_conversion;
12253     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12254                                          << IsEqual;
12255     if (CheckForReference(*this, E, PD)) {
12256       return;
12257     }
12258   }
12259 
12260   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12261     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12262     std::string Str;
12263     llvm::raw_string_ostream S(Str);
12264     E->printPretty(S, nullptr, getPrintingPolicy());
12265     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12266                                 : diag::warn_cast_nonnull_to_bool;
12267     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12268       << E->getSourceRange() << Range << IsEqual;
12269     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12270   };
12271 
12272   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12273   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12274     if (auto *Callee = Call->getDirectCallee()) {
12275       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12276         ComplainAboutNonnullParamOrCall(A);
12277         return;
12278       }
12279     }
12280   }
12281 
12282   // Expect to find a single Decl.  Skip anything more complicated.
12283   ValueDecl *D = nullptr;
12284   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12285     D = R->getDecl();
12286   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12287     D = M->getMemberDecl();
12288   }
12289 
12290   // Weak Decls can be null.
12291   if (!D || D->isWeak())
12292     return;
12293 
12294   // Check for parameter decl with nonnull attribute
12295   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12296     if (getCurFunction() &&
12297         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12298       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12299         ComplainAboutNonnullParamOrCall(A);
12300         return;
12301       }
12302 
12303       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12304         // Skip function template not specialized yet.
12305         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12306           return;
12307         auto ParamIter = llvm::find(FD->parameters(), PV);
12308         assert(ParamIter != FD->param_end());
12309         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12310 
12311         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12312           if (!NonNull->args_size()) {
12313               ComplainAboutNonnullParamOrCall(NonNull);
12314               return;
12315           }
12316 
12317           for (const ParamIdx &ArgNo : NonNull->args()) {
12318             if (ArgNo.getASTIndex() == ParamNo) {
12319               ComplainAboutNonnullParamOrCall(NonNull);
12320               return;
12321             }
12322           }
12323         }
12324       }
12325     }
12326   }
12327 
12328   QualType T = D->getType();
12329   const bool IsArray = T->isArrayType();
12330   const bool IsFunction = T->isFunctionType();
12331 
12332   // Address of function is used to silence the function warning.
12333   if (IsAddressOf && IsFunction) {
12334     return;
12335   }
12336 
12337   // Found nothing.
12338   if (!IsAddressOf && !IsFunction && !IsArray)
12339     return;
12340 
12341   // Pretty print the expression for the diagnostic.
12342   std::string Str;
12343   llvm::raw_string_ostream S(Str);
12344   E->printPretty(S, nullptr, getPrintingPolicy());
12345 
12346   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12347                               : diag::warn_impcast_pointer_to_bool;
12348   enum {
12349     AddressOf,
12350     FunctionPointer,
12351     ArrayPointer
12352   } DiagType;
12353   if (IsAddressOf)
12354     DiagType = AddressOf;
12355   else if (IsFunction)
12356     DiagType = FunctionPointer;
12357   else if (IsArray)
12358     DiagType = ArrayPointer;
12359   else
12360     llvm_unreachable("Could not determine diagnostic.");
12361   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12362                                 << Range << IsEqual;
12363 
12364   if (!IsFunction)
12365     return;
12366 
12367   // Suggest '&' to silence the function warning.
12368   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12369       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12370 
12371   // Check to see if '()' fixit should be emitted.
12372   QualType ReturnType;
12373   UnresolvedSet<4> NonTemplateOverloads;
12374   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12375   if (ReturnType.isNull())
12376     return;
12377 
12378   if (IsCompare) {
12379     // There are two cases here.  If there is null constant, the only suggest
12380     // for a pointer return type.  If the null is 0, then suggest if the return
12381     // type is a pointer or an integer type.
12382     if (!ReturnType->isPointerType()) {
12383       if (NullKind == Expr::NPCK_ZeroExpression ||
12384           NullKind == Expr::NPCK_ZeroLiteral) {
12385         if (!ReturnType->isIntegerType())
12386           return;
12387       } else {
12388         return;
12389       }
12390     }
12391   } else { // !IsCompare
12392     // For function to bool, only suggest if the function pointer has bool
12393     // return type.
12394     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12395       return;
12396   }
12397   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12398       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12399 }
12400 
12401 /// Diagnoses "dangerous" implicit conversions within the given
12402 /// expression (which is a full expression).  Implements -Wconversion
12403 /// and -Wsign-compare.
12404 ///
12405 /// \param CC the "context" location of the implicit conversion, i.e.
12406 ///   the most location of the syntactic entity requiring the implicit
12407 ///   conversion
12408 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12409   // Don't diagnose in unevaluated contexts.
12410   if (isUnevaluatedContext())
12411     return;
12412 
12413   // Don't diagnose for value- or type-dependent expressions.
12414   if (E->isTypeDependent() || E->isValueDependent())
12415     return;
12416 
12417   // Check for array bounds violations in cases where the check isn't triggered
12418   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12419   // ArraySubscriptExpr is on the RHS of a variable initialization.
12420   CheckArrayAccess(E);
12421 
12422   // This is not the right CC for (e.g.) a variable initialization.
12423   AnalyzeImplicitConversions(*this, E, CC);
12424 }
12425 
12426 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12427 /// Input argument E is a logical expression.
12428 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12429   ::CheckBoolLikeConversion(*this, E, CC);
12430 }
12431 
12432 /// Diagnose when expression is an integer constant expression and its evaluation
12433 /// results in integer overflow
12434 void Sema::CheckForIntOverflow (Expr *E) {
12435   // Use a work list to deal with nested struct initializers.
12436   SmallVector<Expr *, 2> Exprs(1, E);
12437 
12438   do {
12439     Expr *OriginalE = Exprs.pop_back_val();
12440     Expr *E = OriginalE->IgnoreParenCasts();
12441 
12442     if (isa<BinaryOperator>(E)) {
12443       E->EvaluateForOverflow(Context);
12444       continue;
12445     }
12446 
12447     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12448       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12449     else if (isa<ObjCBoxedExpr>(OriginalE))
12450       E->EvaluateForOverflow(Context);
12451     else if (auto Call = dyn_cast<CallExpr>(E))
12452       Exprs.append(Call->arg_begin(), Call->arg_end());
12453     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12454       Exprs.append(Message->arg_begin(), Message->arg_end());
12455   } while (!Exprs.empty());
12456 }
12457 
12458 namespace {
12459 
12460 /// Visitor for expressions which looks for unsequenced operations on the
12461 /// same object.
12462 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
12463   using Base = EvaluatedExprVisitor<SequenceChecker>;
12464 
12465   /// A tree of sequenced regions within an expression. Two regions are
12466   /// unsequenced if one is an ancestor or a descendent of the other. When we
12467   /// finish processing an expression with sequencing, such as a comma
12468   /// expression, we fold its tree nodes into its parent, since they are
12469   /// unsequenced with respect to nodes we will visit later.
12470   class SequenceTree {
12471     struct Value {
12472       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12473       unsigned Parent : 31;
12474       unsigned Merged : 1;
12475     };
12476     SmallVector<Value, 8> Values;
12477 
12478   public:
12479     /// A region within an expression which may be sequenced with respect
12480     /// to some other region.
12481     class Seq {
12482       friend class SequenceTree;
12483 
12484       unsigned Index;
12485 
12486       explicit Seq(unsigned N) : Index(N) {}
12487 
12488     public:
12489       Seq() : Index(0) {}
12490     };
12491 
12492     SequenceTree() { Values.push_back(Value(0)); }
12493     Seq root() const { return Seq(0); }
12494 
12495     /// Create a new sequence of operations, which is an unsequenced
12496     /// subset of \p Parent. This sequence of operations is sequenced with
12497     /// respect to other children of \p Parent.
12498     Seq allocate(Seq Parent) {
12499       Values.push_back(Value(Parent.Index));
12500       return Seq(Values.size() - 1);
12501     }
12502 
12503     /// Merge a sequence of operations into its parent.
12504     void merge(Seq S) {
12505       Values[S.Index].Merged = true;
12506     }
12507 
12508     /// Determine whether two operations are unsequenced. This operation
12509     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12510     /// should have been merged into its parent as appropriate.
12511     bool isUnsequenced(Seq Cur, Seq Old) {
12512       unsigned C = representative(Cur.Index);
12513       unsigned Target = representative(Old.Index);
12514       while (C >= Target) {
12515         if (C == Target)
12516           return true;
12517         C = Values[C].Parent;
12518       }
12519       return false;
12520     }
12521 
12522   private:
12523     /// Pick a representative for a sequence.
12524     unsigned representative(unsigned K) {
12525       if (Values[K].Merged)
12526         // Perform path compression as we go.
12527         return Values[K].Parent = representative(Values[K].Parent);
12528       return K;
12529     }
12530   };
12531 
12532   /// An object for which we can track unsequenced uses.
12533   using Object = NamedDecl *;
12534 
12535   /// Different flavors of object usage which we track. We only track the
12536   /// least-sequenced usage of each kind.
12537   enum UsageKind {
12538     /// A read of an object. Multiple unsequenced reads are OK.
12539     UK_Use,
12540 
12541     /// A modification of an object which is sequenced before the value
12542     /// computation of the expression, such as ++n in C++.
12543     UK_ModAsValue,
12544 
12545     /// A modification of an object which is not sequenced before the value
12546     /// computation of the expression, such as n++.
12547     UK_ModAsSideEffect,
12548 
12549     UK_Count = UK_ModAsSideEffect + 1
12550   };
12551 
12552   struct Usage {
12553     Expr *Use;
12554     SequenceTree::Seq Seq;
12555 
12556     Usage() : Use(nullptr), Seq() {}
12557   };
12558 
12559   struct UsageInfo {
12560     Usage Uses[UK_Count];
12561 
12562     /// Have we issued a diagnostic for this variable already?
12563     bool Diagnosed;
12564 
12565     UsageInfo() : Uses(), Diagnosed(false) {}
12566   };
12567   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12568 
12569   Sema &SemaRef;
12570 
12571   /// Sequenced regions within the expression.
12572   SequenceTree Tree;
12573 
12574   /// Declaration modifications and references which we have seen.
12575   UsageInfoMap UsageMap;
12576 
12577   /// The region we are currently within.
12578   SequenceTree::Seq Region;
12579 
12580   /// Filled in with declarations which were modified as a side-effect
12581   /// (that is, post-increment operations).
12582   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12583 
12584   /// Expressions to check later. We defer checking these to reduce
12585   /// stack usage.
12586   SmallVectorImpl<Expr *> &WorkList;
12587 
12588   /// RAII object wrapping the visitation of a sequenced subexpression of an
12589   /// expression. At the end of this process, the side-effects of the evaluation
12590   /// become sequenced with respect to the value computation of the result, so
12591   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12592   /// UK_ModAsValue.
12593   struct SequencedSubexpression {
12594     SequencedSubexpression(SequenceChecker &Self)
12595       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12596       Self.ModAsSideEffect = &ModAsSideEffect;
12597     }
12598 
12599     ~SequencedSubexpression() {
12600       for (auto &M : llvm::reverse(ModAsSideEffect)) {
12601         UsageInfo &U = Self.UsageMap[M.first];
12602         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12603         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12604         SideEffectUsage = M.second;
12605       }
12606       Self.ModAsSideEffect = OldModAsSideEffect;
12607     }
12608 
12609     SequenceChecker &Self;
12610     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12611     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12612   };
12613 
12614   /// RAII object wrapping the visitation of a subexpression which we might
12615   /// choose to evaluate as a constant. If any subexpression is evaluated and
12616   /// found to be non-constant, this allows us to suppress the evaluation of
12617   /// the outer expression.
12618   class EvaluationTracker {
12619   public:
12620     EvaluationTracker(SequenceChecker &Self)
12621         : Self(Self), Prev(Self.EvalTracker) {
12622       Self.EvalTracker = this;
12623     }
12624 
12625     ~EvaluationTracker() {
12626       Self.EvalTracker = Prev;
12627       if (Prev)
12628         Prev->EvalOK &= EvalOK;
12629     }
12630 
12631     bool evaluate(const Expr *E, bool &Result) {
12632       if (!EvalOK || E->isValueDependent())
12633         return false;
12634       EvalOK = E->EvaluateAsBooleanCondition(
12635           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12636       return EvalOK;
12637     }
12638 
12639   private:
12640     SequenceChecker &Self;
12641     EvaluationTracker *Prev;
12642     bool EvalOK = true;
12643   } *EvalTracker = nullptr;
12644 
12645   /// Find the object which is produced by the specified expression,
12646   /// if any.
12647   Object getObject(Expr *E, bool Mod) const {
12648     E = E->IgnoreParenCasts();
12649     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12650       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12651         return getObject(UO->getSubExpr(), Mod);
12652     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12653       if (BO->getOpcode() == BO_Comma)
12654         return getObject(BO->getRHS(), Mod);
12655       if (Mod && BO->isAssignmentOp())
12656         return getObject(BO->getLHS(), Mod);
12657     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12658       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12659       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12660         return ME->getMemberDecl();
12661     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12662       // FIXME: If this is a reference, map through to its value.
12663       return DRE->getDecl();
12664     return nullptr;
12665   }
12666 
12667   /// Note that an object was modified or used by an expression.
12668   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12669     Usage &U = UI.Uses[UK];
12670     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12671       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12672         ModAsSideEffect->push_back(std::make_pair(O, U));
12673       U.Use = Ref;
12674       U.Seq = Region;
12675     }
12676   }
12677 
12678   /// Check whether a modification or use conflicts with a prior usage.
12679   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12680                   bool IsModMod) {
12681     if (UI.Diagnosed)
12682       return;
12683 
12684     const Usage &U = UI.Uses[OtherKind];
12685     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12686       return;
12687 
12688     Expr *Mod = U.Use;
12689     Expr *ModOrUse = Ref;
12690     if (OtherKind == UK_Use)
12691       std::swap(Mod, ModOrUse);
12692 
12693     SemaRef.DiagRuntimeBehavior(
12694         Mod->getExprLoc(), {Mod, ModOrUse},
12695         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12696                                : diag::warn_unsequenced_mod_use)
12697             << O << SourceRange(ModOrUse->getExprLoc()));
12698     UI.Diagnosed = true;
12699   }
12700 
12701   void notePreUse(Object O, Expr *Use) {
12702     UsageInfo &U = UsageMap[O];
12703     // Uses conflict with other modifications.
12704     checkUsage(O, U, Use, UK_ModAsValue, false);
12705   }
12706 
12707   void notePostUse(Object O, Expr *Use) {
12708     UsageInfo &U = UsageMap[O];
12709     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12710     addUsage(U, O, Use, UK_Use);
12711   }
12712 
12713   void notePreMod(Object O, Expr *Mod) {
12714     UsageInfo &U = UsageMap[O];
12715     // Modifications conflict with other modifications and with uses.
12716     checkUsage(O, U, Mod, UK_ModAsValue, true);
12717     checkUsage(O, U, Mod, UK_Use, false);
12718   }
12719 
12720   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12721     UsageInfo &U = UsageMap[O];
12722     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12723     addUsage(U, O, Use, UK);
12724   }
12725 
12726 public:
12727   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12728       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12729     Visit(E);
12730   }
12731 
12732   void VisitStmt(Stmt *S) {
12733     // Skip all statements which aren't expressions for now.
12734   }
12735 
12736   void VisitExpr(Expr *E) {
12737     // By default, just recurse to evaluated subexpressions.
12738     Base::VisitStmt(E);
12739   }
12740 
12741   void VisitCastExpr(CastExpr *E) {
12742     Object O = Object();
12743     if (E->getCastKind() == CK_LValueToRValue)
12744       O = getObject(E->getSubExpr(), false);
12745 
12746     if (O)
12747       notePreUse(O, E);
12748     VisitExpr(E);
12749     if (O)
12750       notePostUse(O, E);
12751   }
12752 
12753   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12754     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12755     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12756     SequenceTree::Seq OldRegion = Region;
12757 
12758     {
12759       SequencedSubexpression SeqBefore(*this);
12760       Region = BeforeRegion;
12761       Visit(SequencedBefore);
12762     }
12763 
12764     Region = AfterRegion;
12765     Visit(SequencedAfter);
12766 
12767     Region = OldRegion;
12768 
12769     Tree.merge(BeforeRegion);
12770     Tree.merge(AfterRegion);
12771   }
12772 
12773   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12774     // C++17 [expr.sub]p1:
12775     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12776     //   expression E1 is sequenced before the expression E2.
12777     if (SemaRef.getLangOpts().CPlusPlus17)
12778       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12779     else
12780       Base::VisitStmt(ASE);
12781   }
12782 
12783   void VisitBinComma(BinaryOperator *BO) {
12784     // C++11 [expr.comma]p1:
12785     //   Every value computation and side effect associated with the left
12786     //   expression is sequenced before every value computation and side
12787     //   effect associated with the right expression.
12788     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12789   }
12790 
12791   void VisitBinAssign(BinaryOperator *BO) {
12792     // The modification is sequenced after the value computation of the LHS
12793     // and RHS, so check it before inspecting the operands and update the
12794     // map afterwards.
12795     Object O = getObject(BO->getLHS(), true);
12796     if (!O)
12797       return VisitExpr(BO);
12798 
12799     notePreMod(O, BO);
12800 
12801     // C++11 [expr.ass]p7:
12802     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12803     //   only once.
12804     //
12805     // Therefore, for a compound assignment operator, O is considered used
12806     // everywhere except within the evaluation of E1 itself.
12807     if (isa<CompoundAssignOperator>(BO))
12808       notePreUse(O, BO);
12809 
12810     Visit(BO->getLHS());
12811 
12812     if (isa<CompoundAssignOperator>(BO))
12813       notePostUse(O, BO);
12814 
12815     Visit(BO->getRHS());
12816 
12817     // C++11 [expr.ass]p1:
12818     //   the assignment is sequenced [...] before the value computation of the
12819     //   assignment expression.
12820     // C11 6.5.16/3 has no such rule.
12821     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12822                                                        : UK_ModAsSideEffect);
12823   }
12824 
12825   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12826     VisitBinAssign(CAO);
12827   }
12828 
12829   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12830   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12831   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12832     Object O = getObject(UO->getSubExpr(), true);
12833     if (!O)
12834       return VisitExpr(UO);
12835 
12836     notePreMod(O, UO);
12837     Visit(UO->getSubExpr());
12838     // C++11 [expr.pre.incr]p1:
12839     //   the expression ++x is equivalent to x+=1
12840     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12841                                                        : UK_ModAsSideEffect);
12842   }
12843 
12844   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12845   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12846   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12847     Object O = getObject(UO->getSubExpr(), true);
12848     if (!O)
12849       return VisitExpr(UO);
12850 
12851     notePreMod(O, UO);
12852     Visit(UO->getSubExpr());
12853     notePostMod(O, UO, UK_ModAsSideEffect);
12854   }
12855 
12856   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12857   void VisitBinLOr(BinaryOperator *BO) {
12858     // The side-effects of the LHS of an '&&' are sequenced before the
12859     // value computation of the RHS, and hence before the value computation
12860     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12861     // as if they were unconditionally sequenced.
12862     EvaluationTracker Eval(*this);
12863     {
12864       SequencedSubexpression Sequenced(*this);
12865       Visit(BO->getLHS());
12866     }
12867 
12868     bool Result;
12869     if (Eval.evaluate(BO->getLHS(), Result)) {
12870       if (!Result)
12871         Visit(BO->getRHS());
12872     } else {
12873       // Check for unsequenced operations in the RHS, treating it as an
12874       // entirely separate evaluation.
12875       //
12876       // FIXME: If there are operations in the RHS which are unsequenced
12877       // with respect to operations outside the RHS, and those operations
12878       // are unconditionally evaluated, diagnose them.
12879       WorkList.push_back(BO->getRHS());
12880     }
12881   }
12882   void VisitBinLAnd(BinaryOperator *BO) {
12883     EvaluationTracker Eval(*this);
12884     {
12885       SequencedSubexpression Sequenced(*this);
12886       Visit(BO->getLHS());
12887     }
12888 
12889     bool Result;
12890     if (Eval.evaluate(BO->getLHS(), Result)) {
12891       if (Result)
12892         Visit(BO->getRHS());
12893     } else {
12894       WorkList.push_back(BO->getRHS());
12895     }
12896   }
12897 
12898   // Only visit the condition, unless we can be sure which subexpression will
12899   // be chosen.
12900   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12901     EvaluationTracker Eval(*this);
12902     {
12903       SequencedSubexpression Sequenced(*this);
12904       Visit(CO->getCond());
12905     }
12906 
12907     bool Result;
12908     if (Eval.evaluate(CO->getCond(), Result))
12909       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12910     else {
12911       WorkList.push_back(CO->getTrueExpr());
12912       WorkList.push_back(CO->getFalseExpr());
12913     }
12914   }
12915 
12916   void VisitCallExpr(CallExpr *CE) {
12917     // C++11 [intro.execution]p15:
12918     //   When calling a function [...], every value computation and side effect
12919     //   associated with any argument expression, or with the postfix expression
12920     //   designating the called function, is sequenced before execution of every
12921     //   expression or statement in the body of the function [and thus before
12922     //   the value computation of its result].
12923     SequencedSubexpression Sequenced(*this);
12924     Base::VisitCallExpr(CE);
12925 
12926     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12927   }
12928 
12929   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12930     // This is a call, so all subexpressions are sequenced before the result.
12931     SequencedSubexpression Sequenced(*this);
12932 
12933     if (!CCE->isListInitialization())
12934       return VisitExpr(CCE);
12935 
12936     // In C++11, list initializations are sequenced.
12937     SmallVector<SequenceTree::Seq, 32> Elts;
12938     SequenceTree::Seq Parent = Region;
12939     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12940                                         E = CCE->arg_end();
12941          I != E; ++I) {
12942       Region = Tree.allocate(Parent);
12943       Elts.push_back(Region);
12944       Visit(*I);
12945     }
12946 
12947     // Forget that the initializers are sequenced.
12948     Region = Parent;
12949     for (unsigned I = 0; I < Elts.size(); ++I)
12950       Tree.merge(Elts[I]);
12951   }
12952 
12953   void VisitInitListExpr(InitListExpr *ILE) {
12954     if (!SemaRef.getLangOpts().CPlusPlus11)
12955       return VisitExpr(ILE);
12956 
12957     // In C++11, list initializations are sequenced.
12958     SmallVector<SequenceTree::Seq, 32> Elts;
12959     SequenceTree::Seq Parent = Region;
12960     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12961       Expr *E = ILE->getInit(I);
12962       if (!E) continue;
12963       Region = Tree.allocate(Parent);
12964       Elts.push_back(Region);
12965       Visit(E);
12966     }
12967 
12968     // Forget that the initializers are sequenced.
12969     Region = Parent;
12970     for (unsigned I = 0; I < Elts.size(); ++I)
12971       Tree.merge(Elts[I]);
12972   }
12973 };
12974 
12975 } // namespace
12976 
12977 void Sema::CheckUnsequencedOperations(Expr *E) {
12978   SmallVector<Expr *, 8> WorkList;
12979   WorkList.push_back(E);
12980   while (!WorkList.empty()) {
12981     Expr *Item = WorkList.pop_back_val();
12982     SequenceChecker(*this, Item, WorkList);
12983   }
12984 }
12985 
12986 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12987                               bool IsConstexpr) {
12988   llvm::SaveAndRestore<bool> ConstantContext(
12989       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12990   CheckImplicitConversions(E, CheckLoc);
12991   if (!E->isInstantiationDependent())
12992     CheckUnsequencedOperations(E);
12993   if (!IsConstexpr && !E->isValueDependent())
12994     CheckForIntOverflow(E);
12995   DiagnoseMisalignedMembers();
12996 }
12997 
12998 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12999                                        FieldDecl *BitField,
13000                                        Expr *Init) {
13001   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13002 }
13003 
13004 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13005                                          SourceLocation Loc) {
13006   if (!PType->isVariablyModifiedType())
13007     return;
13008   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13009     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13010     return;
13011   }
13012   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13013     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13014     return;
13015   }
13016   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13017     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13018     return;
13019   }
13020 
13021   const ArrayType *AT = S.Context.getAsArrayType(PType);
13022   if (!AT)
13023     return;
13024 
13025   if (AT->getSizeModifier() != ArrayType::Star) {
13026     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13027     return;
13028   }
13029 
13030   S.Diag(Loc, diag::err_array_star_in_function_definition);
13031 }
13032 
13033 /// CheckParmsForFunctionDef - Check that the parameters of the given
13034 /// function are appropriate for the definition of a function. This
13035 /// takes care of any checks that cannot be performed on the
13036 /// declaration itself, e.g., that the types of each of the function
13037 /// parameters are complete.
13038 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13039                                     bool CheckParameterNames) {
13040   bool HasInvalidParm = false;
13041   for (ParmVarDecl *Param : Parameters) {
13042     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13043     // function declarator that is part of a function definition of
13044     // that function shall not have incomplete type.
13045     //
13046     // This is also C++ [dcl.fct]p6.
13047     if (!Param->isInvalidDecl() &&
13048         RequireCompleteType(Param->getLocation(), Param->getType(),
13049                             diag::err_typecheck_decl_incomplete_type)) {
13050       Param->setInvalidDecl();
13051       HasInvalidParm = true;
13052     }
13053 
13054     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13055     // declaration of each parameter shall include an identifier.
13056     if (CheckParameterNames &&
13057         Param->getIdentifier() == nullptr &&
13058         !Param->isImplicit() &&
13059         !getLangOpts().CPlusPlus)
13060       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13061 
13062     // C99 6.7.5.3p12:
13063     //   If the function declarator is not part of a definition of that
13064     //   function, parameters may have incomplete type and may use the [*]
13065     //   notation in their sequences of declarator specifiers to specify
13066     //   variable length array types.
13067     QualType PType = Param->getOriginalType();
13068     // FIXME: This diagnostic should point the '[*]' if source-location
13069     // information is added for it.
13070     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13071 
13072     // If the parameter is a c++ class type and it has to be destructed in the
13073     // callee function, declare the destructor so that it can be called by the
13074     // callee function. Do not perform any direct access check on the dtor here.
13075     if (!Param->isInvalidDecl()) {
13076       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13077         if (!ClassDecl->isInvalidDecl() &&
13078             !ClassDecl->hasIrrelevantDestructor() &&
13079             !ClassDecl->isDependentContext() &&
13080             ClassDecl->isParamDestroyedInCallee()) {
13081           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13082           MarkFunctionReferenced(Param->getLocation(), Destructor);
13083           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13084         }
13085       }
13086     }
13087 
13088     // Parameters with the pass_object_size attribute only need to be marked
13089     // constant at function definitions. Because we lack information about
13090     // whether we're on a declaration or definition when we're instantiating the
13091     // attribute, we need to check for constness here.
13092     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13093       if (!Param->getType().isConstQualified())
13094         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13095             << Attr->getSpelling() << 1;
13096 
13097     // Check for parameter names shadowing fields from the class.
13098     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13099       // The owning context for the parameter should be the function, but we
13100       // want to see if this function's declaration context is a record.
13101       DeclContext *DC = Param->getDeclContext();
13102       if (DC && DC->isFunctionOrMethod()) {
13103         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13104           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13105                                      RD, /*DeclIsField*/ false);
13106       }
13107     }
13108   }
13109 
13110   return HasInvalidParm;
13111 }
13112 
13113 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13114 /// or MemberExpr.
13115 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13116                               ASTContext &Context) {
13117   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13118     return Context.getDeclAlign(DRE->getDecl());
13119 
13120   if (const auto *ME = dyn_cast<MemberExpr>(E))
13121     return Context.getDeclAlign(ME->getMemberDecl());
13122 
13123   return TypeAlign;
13124 }
13125 
13126 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13127 /// pointer cast increases the alignment requirements.
13128 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13129   // This is actually a lot of work to potentially be doing on every
13130   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13131   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13132     return;
13133 
13134   // Ignore dependent types.
13135   if (T->isDependentType() || Op->getType()->isDependentType())
13136     return;
13137 
13138   // Require that the destination be a pointer type.
13139   const PointerType *DestPtr = T->getAs<PointerType>();
13140   if (!DestPtr) return;
13141 
13142   // If the destination has alignment 1, we're done.
13143   QualType DestPointee = DestPtr->getPointeeType();
13144   if (DestPointee->isIncompleteType()) return;
13145   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13146   if (DestAlign.isOne()) return;
13147 
13148   // Require that the source be a pointer type.
13149   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13150   if (!SrcPtr) return;
13151   QualType SrcPointee = SrcPtr->getPointeeType();
13152 
13153   // Whitelist casts from cv void*.  We already implicitly
13154   // whitelisted casts to cv void*, since they have alignment 1.
13155   // Also whitelist casts involving incomplete types, which implicitly
13156   // includes 'void'.
13157   if (SrcPointee->isIncompleteType()) return;
13158 
13159   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13160 
13161   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13162     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13163       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13164   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13165     if (UO->getOpcode() == UO_AddrOf)
13166       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13167   }
13168 
13169   if (SrcAlign >= DestAlign) return;
13170 
13171   Diag(TRange.getBegin(), diag::warn_cast_align)
13172     << Op->getType() << T
13173     << static_cast<unsigned>(SrcAlign.getQuantity())
13174     << static_cast<unsigned>(DestAlign.getQuantity())
13175     << TRange << Op->getSourceRange();
13176 }
13177 
13178 /// Check whether this array fits the idiom of a size-one tail padded
13179 /// array member of a struct.
13180 ///
13181 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13182 /// commonly used to emulate flexible arrays in C89 code.
13183 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13184                                     const NamedDecl *ND) {
13185   if (Size != 1 || !ND) return false;
13186 
13187   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13188   if (!FD) return false;
13189 
13190   // Don't consider sizes resulting from macro expansions or template argument
13191   // substitution to form C89 tail-padded arrays.
13192 
13193   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13194   while (TInfo) {
13195     TypeLoc TL = TInfo->getTypeLoc();
13196     // Look through typedefs.
13197     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13198       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13199       TInfo = TDL->getTypeSourceInfo();
13200       continue;
13201     }
13202     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13203       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13204       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13205         return false;
13206     }
13207     break;
13208   }
13209 
13210   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13211   if (!RD) return false;
13212   if (RD->isUnion()) return false;
13213   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13214     if (!CRD->isStandardLayout()) return false;
13215   }
13216 
13217   // See if this is the last field decl in the record.
13218   const Decl *D = FD;
13219   while ((D = D->getNextDeclInContext()))
13220     if (isa<FieldDecl>(D))
13221       return false;
13222   return true;
13223 }
13224 
13225 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13226                             const ArraySubscriptExpr *ASE,
13227                             bool AllowOnePastEnd, bool IndexNegated) {
13228   // Already diagnosed by the constant evaluator.
13229   if (isConstantEvaluated())
13230     return;
13231 
13232   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13233   if (IndexExpr->isValueDependent())
13234     return;
13235 
13236   const Type *EffectiveType =
13237       BaseExpr->getType()->getPointeeOrArrayElementType();
13238   BaseExpr = BaseExpr->IgnoreParenCasts();
13239   const ConstantArrayType *ArrayTy =
13240       Context.getAsConstantArrayType(BaseExpr->getType());
13241 
13242   if (!ArrayTy)
13243     return;
13244 
13245   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13246   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13247     return;
13248 
13249   Expr::EvalResult Result;
13250   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13251     return;
13252 
13253   llvm::APSInt index = Result.Val.getInt();
13254   if (IndexNegated)
13255     index = -index;
13256 
13257   const NamedDecl *ND = nullptr;
13258   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13259     ND = DRE->getDecl();
13260   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13261     ND = ME->getMemberDecl();
13262 
13263   if (index.isUnsigned() || !index.isNegative()) {
13264     // It is possible that the type of the base expression after
13265     // IgnoreParenCasts is incomplete, even though the type of the base
13266     // expression before IgnoreParenCasts is complete (see PR39746 for an
13267     // example). In this case we have no information about whether the array
13268     // access exceeds the array bounds. However we can still diagnose an array
13269     // access which precedes the array bounds.
13270     if (BaseType->isIncompleteType())
13271       return;
13272 
13273     llvm::APInt size = ArrayTy->getSize();
13274     if (!size.isStrictlyPositive())
13275       return;
13276 
13277     if (BaseType != EffectiveType) {
13278       // Make sure we're comparing apples to apples when comparing index to size
13279       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13280       uint64_t array_typesize = Context.getTypeSize(BaseType);
13281       // Handle ptrarith_typesize being zero, such as when casting to void*
13282       if (!ptrarith_typesize) ptrarith_typesize = 1;
13283       if (ptrarith_typesize != array_typesize) {
13284         // There's a cast to a different size type involved
13285         uint64_t ratio = array_typesize / ptrarith_typesize;
13286         // TODO: Be smarter about handling cases where array_typesize is not a
13287         // multiple of ptrarith_typesize
13288         if (ptrarith_typesize * ratio == array_typesize)
13289           size *= llvm::APInt(size.getBitWidth(), ratio);
13290       }
13291     }
13292 
13293     if (size.getBitWidth() > index.getBitWidth())
13294       index = index.zext(size.getBitWidth());
13295     else if (size.getBitWidth() < index.getBitWidth())
13296       size = size.zext(index.getBitWidth());
13297 
13298     // For array subscripting the index must be less than size, but for pointer
13299     // arithmetic also allow the index (offset) to be equal to size since
13300     // computing the next address after the end of the array is legal and
13301     // commonly done e.g. in C++ iterators and range-based for loops.
13302     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13303       return;
13304 
13305     // Also don't warn for arrays of size 1 which are members of some
13306     // structure. These are often used to approximate flexible arrays in C89
13307     // code.
13308     if (IsTailPaddedMemberArray(*this, size, ND))
13309       return;
13310 
13311     // Suppress the warning if the subscript expression (as identified by the
13312     // ']' location) and the index expression are both from macro expansions
13313     // within a system header.
13314     if (ASE) {
13315       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13316           ASE->getRBracketLoc());
13317       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13318         SourceLocation IndexLoc =
13319             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13320         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13321           return;
13322       }
13323     }
13324 
13325     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13326     if (ASE)
13327       DiagID = diag::warn_array_index_exceeds_bounds;
13328 
13329     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13330                         PDiag(DiagID) << index.toString(10, true)
13331                                       << size.toString(10, true)
13332                                       << (unsigned)size.getLimitedValue(~0U)
13333                                       << IndexExpr->getSourceRange());
13334   } else {
13335     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13336     if (!ASE) {
13337       DiagID = diag::warn_ptr_arith_precedes_bounds;
13338       if (index.isNegative()) index = -index;
13339     }
13340 
13341     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13342                         PDiag(DiagID) << index.toString(10, true)
13343                                       << IndexExpr->getSourceRange());
13344   }
13345 
13346   if (!ND) {
13347     // Try harder to find a NamedDecl to point at in the note.
13348     while (const ArraySubscriptExpr *ASE =
13349            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13350       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13351     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13352       ND = DRE->getDecl();
13353     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13354       ND = ME->getMemberDecl();
13355   }
13356 
13357   if (ND)
13358     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13359                         PDiag(diag::note_array_declared_here)
13360                             << ND->getDeclName());
13361 }
13362 
13363 void Sema::CheckArrayAccess(const Expr *expr) {
13364   int AllowOnePastEnd = 0;
13365   while (expr) {
13366     expr = expr->IgnoreParenImpCasts();
13367     switch (expr->getStmtClass()) {
13368       case Stmt::ArraySubscriptExprClass: {
13369         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13370         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13371                          AllowOnePastEnd > 0);
13372         expr = ASE->getBase();
13373         break;
13374       }
13375       case Stmt::MemberExprClass: {
13376         expr = cast<MemberExpr>(expr)->getBase();
13377         break;
13378       }
13379       case Stmt::OMPArraySectionExprClass: {
13380         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13381         if (ASE->getLowerBound())
13382           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13383                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13384         return;
13385       }
13386       case Stmt::UnaryOperatorClass: {
13387         // Only unwrap the * and & unary operators
13388         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13389         expr = UO->getSubExpr();
13390         switch (UO->getOpcode()) {
13391           case UO_AddrOf:
13392             AllowOnePastEnd++;
13393             break;
13394           case UO_Deref:
13395             AllowOnePastEnd--;
13396             break;
13397           default:
13398             return;
13399         }
13400         break;
13401       }
13402       case Stmt::ConditionalOperatorClass: {
13403         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13404         if (const Expr *lhs = cond->getLHS())
13405           CheckArrayAccess(lhs);
13406         if (const Expr *rhs = cond->getRHS())
13407           CheckArrayAccess(rhs);
13408         return;
13409       }
13410       case Stmt::CXXOperatorCallExprClass: {
13411         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13412         for (const auto *Arg : OCE->arguments())
13413           CheckArrayAccess(Arg);
13414         return;
13415       }
13416       default:
13417         return;
13418     }
13419   }
13420 }
13421 
13422 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13423 
13424 namespace {
13425 
13426 struct RetainCycleOwner {
13427   VarDecl *Variable = nullptr;
13428   SourceRange Range;
13429   SourceLocation Loc;
13430   bool Indirect = false;
13431 
13432   RetainCycleOwner() = default;
13433 
13434   void setLocsFrom(Expr *e) {
13435     Loc = e->getExprLoc();
13436     Range = e->getSourceRange();
13437   }
13438 };
13439 
13440 } // namespace
13441 
13442 /// Consider whether capturing the given variable can possibly lead to
13443 /// a retain cycle.
13444 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13445   // In ARC, it's captured strongly iff the variable has __strong
13446   // lifetime.  In MRR, it's captured strongly if the variable is
13447   // __block and has an appropriate type.
13448   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13449     return false;
13450 
13451   owner.Variable = var;
13452   if (ref)
13453     owner.setLocsFrom(ref);
13454   return true;
13455 }
13456 
13457 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13458   while (true) {
13459     e = e->IgnoreParens();
13460     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13461       switch (cast->getCastKind()) {
13462       case CK_BitCast:
13463       case CK_LValueBitCast:
13464       case CK_LValueToRValue:
13465       case CK_ARCReclaimReturnedObject:
13466         e = cast->getSubExpr();
13467         continue;
13468 
13469       default:
13470         return false;
13471       }
13472     }
13473 
13474     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13475       ObjCIvarDecl *ivar = ref->getDecl();
13476       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13477         return false;
13478 
13479       // Try to find a retain cycle in the base.
13480       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13481         return false;
13482 
13483       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13484       owner.Indirect = true;
13485       return true;
13486     }
13487 
13488     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13489       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13490       if (!var) return false;
13491       return considerVariable(var, ref, owner);
13492     }
13493 
13494     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13495       if (member->isArrow()) return false;
13496 
13497       // Don't count this as an indirect ownership.
13498       e = member->getBase();
13499       continue;
13500     }
13501 
13502     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13503       // Only pay attention to pseudo-objects on property references.
13504       ObjCPropertyRefExpr *pre
13505         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13506                                               ->IgnoreParens());
13507       if (!pre) return false;
13508       if (pre->isImplicitProperty()) return false;
13509       ObjCPropertyDecl *property = pre->getExplicitProperty();
13510       if (!property->isRetaining() &&
13511           !(property->getPropertyIvarDecl() &&
13512             property->getPropertyIvarDecl()->getType()
13513               .getObjCLifetime() == Qualifiers::OCL_Strong))
13514           return false;
13515 
13516       owner.Indirect = true;
13517       if (pre->isSuperReceiver()) {
13518         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13519         if (!owner.Variable)
13520           return false;
13521         owner.Loc = pre->getLocation();
13522         owner.Range = pre->getSourceRange();
13523         return true;
13524       }
13525       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13526                               ->getSourceExpr());
13527       continue;
13528     }
13529 
13530     // Array ivars?
13531 
13532     return false;
13533   }
13534 }
13535 
13536 namespace {
13537 
13538   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13539     ASTContext &Context;
13540     VarDecl *Variable;
13541     Expr *Capturer = nullptr;
13542     bool VarWillBeReased = false;
13543 
13544     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13545         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13546           Context(Context), Variable(variable) {}
13547 
13548     void VisitDeclRefExpr(DeclRefExpr *ref) {
13549       if (ref->getDecl() == Variable && !Capturer)
13550         Capturer = ref;
13551     }
13552 
13553     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13554       if (Capturer) return;
13555       Visit(ref->getBase());
13556       if (Capturer && ref->isFreeIvar())
13557         Capturer = ref;
13558     }
13559 
13560     void VisitBlockExpr(BlockExpr *block) {
13561       // Look inside nested blocks
13562       if (block->getBlockDecl()->capturesVariable(Variable))
13563         Visit(block->getBlockDecl()->getBody());
13564     }
13565 
13566     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13567       if (Capturer) return;
13568       if (OVE->getSourceExpr())
13569         Visit(OVE->getSourceExpr());
13570     }
13571 
13572     void VisitBinaryOperator(BinaryOperator *BinOp) {
13573       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13574         return;
13575       Expr *LHS = BinOp->getLHS();
13576       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13577         if (DRE->getDecl() != Variable)
13578           return;
13579         if (Expr *RHS = BinOp->getRHS()) {
13580           RHS = RHS->IgnoreParenCasts();
13581           llvm::APSInt Value;
13582           VarWillBeReased =
13583             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13584         }
13585       }
13586     }
13587   };
13588 
13589 } // namespace
13590 
13591 /// Check whether the given argument is a block which captures a
13592 /// variable.
13593 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13594   assert(owner.Variable && owner.Loc.isValid());
13595 
13596   e = e->IgnoreParenCasts();
13597 
13598   // Look through [^{...} copy] and Block_copy(^{...}).
13599   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13600     Selector Cmd = ME->getSelector();
13601     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13602       e = ME->getInstanceReceiver();
13603       if (!e)
13604         return nullptr;
13605       e = e->IgnoreParenCasts();
13606     }
13607   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13608     if (CE->getNumArgs() == 1) {
13609       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13610       if (Fn) {
13611         const IdentifierInfo *FnI = Fn->getIdentifier();
13612         if (FnI && FnI->isStr("_Block_copy")) {
13613           e = CE->getArg(0)->IgnoreParenCasts();
13614         }
13615       }
13616     }
13617   }
13618 
13619   BlockExpr *block = dyn_cast<BlockExpr>(e);
13620   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13621     return nullptr;
13622 
13623   FindCaptureVisitor visitor(S.Context, owner.Variable);
13624   visitor.Visit(block->getBlockDecl()->getBody());
13625   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13626 }
13627 
13628 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13629                                 RetainCycleOwner &owner) {
13630   assert(capturer);
13631   assert(owner.Variable && owner.Loc.isValid());
13632 
13633   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13634     << owner.Variable << capturer->getSourceRange();
13635   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13636     << owner.Indirect << owner.Range;
13637 }
13638 
13639 /// Check for a keyword selector that starts with the word 'add' or
13640 /// 'set'.
13641 static bool isSetterLikeSelector(Selector sel) {
13642   if (sel.isUnarySelector()) return false;
13643 
13644   StringRef str = sel.getNameForSlot(0);
13645   while (!str.empty() && str.front() == '_') str = str.substr(1);
13646   if (str.startswith("set"))
13647     str = str.substr(3);
13648   else if (str.startswith("add")) {
13649     // Specially whitelist 'addOperationWithBlock:'.
13650     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13651       return false;
13652     str = str.substr(3);
13653   }
13654   else
13655     return false;
13656 
13657   if (str.empty()) return true;
13658   return !isLowercase(str.front());
13659 }
13660 
13661 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13662                                                     ObjCMessageExpr *Message) {
13663   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13664                                                 Message->getReceiverInterface(),
13665                                                 NSAPI::ClassId_NSMutableArray);
13666   if (!IsMutableArray) {
13667     return None;
13668   }
13669 
13670   Selector Sel = Message->getSelector();
13671 
13672   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13673     S.NSAPIObj->getNSArrayMethodKind(Sel);
13674   if (!MKOpt) {
13675     return None;
13676   }
13677 
13678   NSAPI::NSArrayMethodKind MK = *MKOpt;
13679 
13680   switch (MK) {
13681     case NSAPI::NSMutableArr_addObject:
13682     case NSAPI::NSMutableArr_insertObjectAtIndex:
13683     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13684       return 0;
13685     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13686       return 1;
13687 
13688     default:
13689       return None;
13690   }
13691 
13692   return None;
13693 }
13694 
13695 static
13696 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13697                                                   ObjCMessageExpr *Message) {
13698   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13699                                             Message->getReceiverInterface(),
13700                                             NSAPI::ClassId_NSMutableDictionary);
13701   if (!IsMutableDictionary) {
13702     return None;
13703   }
13704 
13705   Selector Sel = Message->getSelector();
13706 
13707   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13708     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13709   if (!MKOpt) {
13710     return None;
13711   }
13712 
13713   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13714 
13715   switch (MK) {
13716     case NSAPI::NSMutableDict_setObjectForKey:
13717     case NSAPI::NSMutableDict_setValueForKey:
13718     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13719       return 0;
13720 
13721     default:
13722       return None;
13723   }
13724 
13725   return None;
13726 }
13727 
13728 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13729   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13730                                                 Message->getReceiverInterface(),
13731                                                 NSAPI::ClassId_NSMutableSet);
13732 
13733   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13734                                             Message->getReceiverInterface(),
13735                                             NSAPI::ClassId_NSMutableOrderedSet);
13736   if (!IsMutableSet && !IsMutableOrderedSet) {
13737     return None;
13738   }
13739 
13740   Selector Sel = Message->getSelector();
13741 
13742   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13743   if (!MKOpt) {
13744     return None;
13745   }
13746 
13747   NSAPI::NSSetMethodKind MK = *MKOpt;
13748 
13749   switch (MK) {
13750     case NSAPI::NSMutableSet_addObject:
13751     case NSAPI::NSOrderedSet_setObjectAtIndex:
13752     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13753     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13754       return 0;
13755     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13756       return 1;
13757   }
13758 
13759   return None;
13760 }
13761 
13762 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13763   if (!Message->isInstanceMessage()) {
13764     return;
13765   }
13766 
13767   Optional<int> ArgOpt;
13768 
13769   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13770       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13771       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13772     return;
13773   }
13774 
13775   int ArgIndex = *ArgOpt;
13776 
13777   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13778   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13779     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13780   }
13781 
13782   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13783     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13784       if (ArgRE->isObjCSelfExpr()) {
13785         Diag(Message->getSourceRange().getBegin(),
13786              diag::warn_objc_circular_container)
13787           << ArgRE->getDecl() << StringRef("'super'");
13788       }
13789     }
13790   } else {
13791     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13792 
13793     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13794       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13795     }
13796 
13797     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13798       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13799         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13800           ValueDecl *Decl = ReceiverRE->getDecl();
13801           Diag(Message->getSourceRange().getBegin(),
13802                diag::warn_objc_circular_container)
13803             << Decl << Decl;
13804           if (!ArgRE->isObjCSelfExpr()) {
13805             Diag(Decl->getLocation(),
13806                  diag::note_objc_circular_container_declared_here)
13807               << Decl;
13808           }
13809         }
13810       }
13811     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13812       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13813         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13814           ObjCIvarDecl *Decl = IvarRE->getDecl();
13815           Diag(Message->getSourceRange().getBegin(),
13816                diag::warn_objc_circular_container)
13817             << Decl << Decl;
13818           Diag(Decl->getLocation(),
13819                diag::note_objc_circular_container_declared_here)
13820             << Decl;
13821         }
13822       }
13823     }
13824   }
13825 }
13826 
13827 /// Check a message send to see if it's likely to cause a retain cycle.
13828 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13829   // Only check instance methods whose selector looks like a setter.
13830   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13831     return;
13832 
13833   // Try to find a variable that the receiver is strongly owned by.
13834   RetainCycleOwner owner;
13835   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13836     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13837       return;
13838   } else {
13839     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13840     owner.Variable = getCurMethodDecl()->getSelfDecl();
13841     owner.Loc = msg->getSuperLoc();
13842     owner.Range = msg->getSuperLoc();
13843   }
13844 
13845   // Check whether the receiver is captured by any of the arguments.
13846   const ObjCMethodDecl *MD = msg->getMethodDecl();
13847   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13848     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13849       // noescape blocks should not be retained by the method.
13850       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13851         continue;
13852       return diagnoseRetainCycle(*this, capturer, owner);
13853     }
13854   }
13855 }
13856 
13857 /// Check a property assign to see if it's likely to cause a retain cycle.
13858 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13859   RetainCycleOwner owner;
13860   if (!findRetainCycleOwner(*this, receiver, owner))
13861     return;
13862 
13863   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13864     diagnoseRetainCycle(*this, capturer, owner);
13865 }
13866 
13867 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13868   RetainCycleOwner Owner;
13869   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13870     return;
13871 
13872   // Because we don't have an expression for the variable, we have to set the
13873   // location explicitly here.
13874   Owner.Loc = Var->getLocation();
13875   Owner.Range = Var->getSourceRange();
13876 
13877   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13878     diagnoseRetainCycle(*this, Capturer, Owner);
13879 }
13880 
13881 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13882                                      Expr *RHS, bool isProperty) {
13883   // Check if RHS is an Objective-C object literal, which also can get
13884   // immediately zapped in a weak reference.  Note that we explicitly
13885   // allow ObjCStringLiterals, since those are designed to never really die.
13886   RHS = RHS->IgnoreParenImpCasts();
13887 
13888   // This enum needs to match with the 'select' in
13889   // warn_objc_arc_literal_assign (off-by-1).
13890   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13891   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13892     return false;
13893 
13894   S.Diag(Loc, diag::warn_arc_literal_assign)
13895     << (unsigned) Kind
13896     << (isProperty ? 0 : 1)
13897     << RHS->getSourceRange();
13898 
13899   return true;
13900 }
13901 
13902 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13903                                     Qualifiers::ObjCLifetime LT,
13904                                     Expr *RHS, bool isProperty) {
13905   // Strip off any implicit cast added to get to the one ARC-specific.
13906   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13907     if (cast->getCastKind() == CK_ARCConsumeObject) {
13908       S.Diag(Loc, diag::warn_arc_retained_assign)
13909         << (LT == Qualifiers::OCL_ExplicitNone)
13910         << (isProperty ? 0 : 1)
13911         << RHS->getSourceRange();
13912       return true;
13913     }
13914     RHS = cast->getSubExpr();
13915   }
13916 
13917   if (LT == Qualifiers::OCL_Weak &&
13918       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13919     return true;
13920 
13921   return false;
13922 }
13923 
13924 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13925                               QualType LHS, Expr *RHS) {
13926   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13927 
13928   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13929     return false;
13930 
13931   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13932     return true;
13933 
13934   return false;
13935 }
13936 
13937 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13938                               Expr *LHS, Expr *RHS) {
13939   QualType LHSType;
13940   // PropertyRef on LHS type need be directly obtained from
13941   // its declaration as it has a PseudoType.
13942   ObjCPropertyRefExpr *PRE
13943     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13944   if (PRE && !PRE->isImplicitProperty()) {
13945     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13946     if (PD)
13947       LHSType = PD->getType();
13948   }
13949 
13950   if (LHSType.isNull())
13951     LHSType = LHS->getType();
13952 
13953   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13954 
13955   if (LT == Qualifiers::OCL_Weak) {
13956     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13957       getCurFunction()->markSafeWeakUse(LHS);
13958   }
13959 
13960   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13961     return;
13962 
13963   // FIXME. Check for other life times.
13964   if (LT != Qualifiers::OCL_None)
13965     return;
13966 
13967   if (PRE) {
13968     if (PRE->isImplicitProperty())
13969       return;
13970     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13971     if (!PD)
13972       return;
13973 
13974     unsigned Attributes = PD->getPropertyAttributes();
13975     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13976       // when 'assign' attribute was not explicitly specified
13977       // by user, ignore it and rely on property type itself
13978       // for lifetime info.
13979       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13980       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13981           LHSType->isObjCRetainableType())
13982         return;
13983 
13984       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13985         if (cast->getCastKind() == CK_ARCConsumeObject) {
13986           Diag(Loc, diag::warn_arc_retained_property_assign)
13987           << RHS->getSourceRange();
13988           return;
13989         }
13990         RHS = cast->getSubExpr();
13991       }
13992     }
13993     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13994       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13995         return;
13996     }
13997   }
13998 }
13999 
14000 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14001 
14002 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
14003                                         SourceLocation StmtLoc,
14004                                         const NullStmt *Body) {
14005   // Do not warn if the body is a macro that expands to nothing, e.g:
14006   //
14007   // #define CALL(x)
14008   // if (condition)
14009   //   CALL(0);
14010   if (Body->hasLeadingEmptyMacro())
14011     return false;
14012 
14013   // Get line numbers of statement and body.
14014   bool StmtLineInvalid;
14015   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
14016                                                       &StmtLineInvalid);
14017   if (StmtLineInvalid)
14018     return false;
14019 
14020   bool BodyLineInvalid;
14021   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
14022                                                       &BodyLineInvalid);
14023   if (BodyLineInvalid)
14024     return false;
14025 
14026   // Warn if null statement and body are on the same line.
14027   if (StmtLine != BodyLine)
14028     return false;
14029 
14030   return true;
14031 }
14032 
14033 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
14034                                  const Stmt *Body,
14035                                  unsigned DiagID) {
14036   // Since this is a syntactic check, don't emit diagnostic for template
14037   // instantiations, this just adds noise.
14038   if (CurrentInstantiationScope)
14039     return;
14040 
14041   // The body should be a null statement.
14042   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14043   if (!NBody)
14044     return;
14045 
14046   // Do the usual checks.
14047   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14048     return;
14049 
14050   Diag(NBody->getSemiLoc(), DiagID);
14051   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14052 }
14053 
14054 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
14055                                  const Stmt *PossibleBody) {
14056   assert(!CurrentInstantiationScope); // Ensured by caller
14057 
14058   SourceLocation StmtLoc;
14059   const Stmt *Body;
14060   unsigned DiagID;
14061   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
14062     StmtLoc = FS->getRParenLoc();
14063     Body = FS->getBody();
14064     DiagID = diag::warn_empty_for_body;
14065   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
14066     StmtLoc = WS->getCond()->getSourceRange().getEnd();
14067     Body = WS->getBody();
14068     DiagID = diag::warn_empty_while_body;
14069   } else
14070     return; // Neither `for' nor `while'.
14071 
14072   // The body should be a null statement.
14073   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
14074   if (!NBody)
14075     return;
14076 
14077   // Skip expensive checks if diagnostic is disabled.
14078   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
14079     return;
14080 
14081   // Do the usual checks.
14082   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
14083     return;
14084 
14085   // `for(...);' and `while(...);' are popular idioms, so in order to keep
14086   // noise level low, emit diagnostics only if for/while is followed by a
14087   // CompoundStmt, e.g.:
14088   //    for (int i = 0; i < n; i++);
14089   //    {
14090   //      a(i);
14091   //    }
14092   // or if for/while is followed by a statement with more indentation
14093   // than for/while itself:
14094   //    for (int i = 0; i < n; i++);
14095   //      a(i);
14096   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
14097   if (!ProbableTypo) {
14098     bool BodyColInvalid;
14099     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14100         PossibleBody->getBeginLoc(), &BodyColInvalid);
14101     if (BodyColInvalid)
14102       return;
14103 
14104     bool StmtColInvalid;
14105     unsigned StmtCol =
14106         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14107     if (StmtColInvalid)
14108       return;
14109 
14110     if (BodyCol > StmtCol)
14111       ProbableTypo = true;
14112   }
14113 
14114   if (ProbableTypo) {
14115     Diag(NBody->getSemiLoc(), DiagID);
14116     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14117   }
14118 }
14119 
14120 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14121 
14122 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14123 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14124                              SourceLocation OpLoc) {
14125   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14126     return;
14127 
14128   if (inTemplateInstantiation())
14129     return;
14130 
14131   // Strip parens and casts away.
14132   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14133   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14134 
14135   // Check for a call expression
14136   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14137   if (!CE || CE->getNumArgs() != 1)
14138     return;
14139 
14140   // Check for a call to std::move
14141   if (!CE->isCallToStdMove())
14142     return;
14143 
14144   // Get argument from std::move
14145   RHSExpr = CE->getArg(0);
14146 
14147   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14148   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14149 
14150   // Two DeclRefExpr's, check that the decls are the same.
14151   if (LHSDeclRef && RHSDeclRef) {
14152     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14153       return;
14154     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14155         RHSDeclRef->getDecl()->getCanonicalDecl())
14156       return;
14157 
14158     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14159                                         << LHSExpr->getSourceRange()
14160                                         << RHSExpr->getSourceRange();
14161     return;
14162   }
14163 
14164   // Member variables require a different approach to check for self moves.
14165   // MemberExpr's are the same if every nested MemberExpr refers to the same
14166   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14167   // the base Expr's are CXXThisExpr's.
14168   const Expr *LHSBase = LHSExpr;
14169   const Expr *RHSBase = RHSExpr;
14170   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14171   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14172   if (!LHSME || !RHSME)
14173     return;
14174 
14175   while (LHSME && RHSME) {
14176     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14177         RHSME->getMemberDecl()->getCanonicalDecl())
14178       return;
14179 
14180     LHSBase = LHSME->getBase();
14181     RHSBase = RHSME->getBase();
14182     LHSME = dyn_cast<MemberExpr>(LHSBase);
14183     RHSME = dyn_cast<MemberExpr>(RHSBase);
14184   }
14185 
14186   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14187   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14188   if (LHSDeclRef && RHSDeclRef) {
14189     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14190       return;
14191     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14192         RHSDeclRef->getDecl()->getCanonicalDecl())
14193       return;
14194 
14195     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14196                                         << LHSExpr->getSourceRange()
14197                                         << RHSExpr->getSourceRange();
14198     return;
14199   }
14200 
14201   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14202     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14203                                         << LHSExpr->getSourceRange()
14204                                         << RHSExpr->getSourceRange();
14205 }
14206 
14207 //===--- Layout compatibility ----------------------------------------------//
14208 
14209 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14210 
14211 /// Check if two enumeration types are layout-compatible.
14212 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14213   // C++11 [dcl.enum] p8:
14214   // Two enumeration types are layout-compatible if they have the same
14215   // underlying type.
14216   return ED1->isComplete() && ED2->isComplete() &&
14217          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14218 }
14219 
14220 /// Check if two fields are layout-compatible.
14221 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14222                                FieldDecl *Field2) {
14223   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14224     return false;
14225 
14226   if (Field1->isBitField() != Field2->isBitField())
14227     return false;
14228 
14229   if (Field1->isBitField()) {
14230     // Make sure that the bit-fields are the same length.
14231     unsigned Bits1 = Field1->getBitWidthValue(C);
14232     unsigned Bits2 = Field2->getBitWidthValue(C);
14233 
14234     if (Bits1 != Bits2)
14235       return false;
14236   }
14237 
14238   return true;
14239 }
14240 
14241 /// Check if two standard-layout structs are layout-compatible.
14242 /// (C++11 [class.mem] p17)
14243 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14244                                      RecordDecl *RD2) {
14245   // If both records are C++ classes, check that base classes match.
14246   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14247     // If one of records is a CXXRecordDecl we are in C++ mode,
14248     // thus the other one is a CXXRecordDecl, too.
14249     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14250     // Check number of base classes.
14251     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14252       return false;
14253 
14254     // Check the base classes.
14255     for (CXXRecordDecl::base_class_const_iterator
14256                Base1 = D1CXX->bases_begin(),
14257            BaseEnd1 = D1CXX->bases_end(),
14258               Base2 = D2CXX->bases_begin();
14259          Base1 != BaseEnd1;
14260          ++Base1, ++Base2) {
14261       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14262         return false;
14263     }
14264   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14265     // If only RD2 is a C++ class, it should have zero base classes.
14266     if (D2CXX->getNumBases() > 0)
14267       return false;
14268   }
14269 
14270   // Check the fields.
14271   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14272                              Field2End = RD2->field_end(),
14273                              Field1 = RD1->field_begin(),
14274                              Field1End = RD1->field_end();
14275   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14276     if (!isLayoutCompatible(C, *Field1, *Field2))
14277       return false;
14278   }
14279   if (Field1 != Field1End || Field2 != Field2End)
14280     return false;
14281 
14282   return true;
14283 }
14284 
14285 /// Check if two standard-layout unions are layout-compatible.
14286 /// (C++11 [class.mem] p18)
14287 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14288                                     RecordDecl *RD2) {
14289   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14290   for (auto *Field2 : RD2->fields())
14291     UnmatchedFields.insert(Field2);
14292 
14293   for (auto *Field1 : RD1->fields()) {
14294     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14295         I = UnmatchedFields.begin(),
14296         E = UnmatchedFields.end();
14297 
14298     for ( ; I != E; ++I) {
14299       if (isLayoutCompatible(C, Field1, *I)) {
14300         bool Result = UnmatchedFields.erase(*I);
14301         (void) Result;
14302         assert(Result);
14303         break;
14304       }
14305     }
14306     if (I == E)
14307       return false;
14308   }
14309 
14310   return UnmatchedFields.empty();
14311 }
14312 
14313 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14314                                RecordDecl *RD2) {
14315   if (RD1->isUnion() != RD2->isUnion())
14316     return false;
14317 
14318   if (RD1->isUnion())
14319     return isLayoutCompatibleUnion(C, RD1, RD2);
14320   else
14321     return isLayoutCompatibleStruct(C, RD1, RD2);
14322 }
14323 
14324 /// Check if two types are layout-compatible in C++11 sense.
14325 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14326   if (T1.isNull() || T2.isNull())
14327     return false;
14328 
14329   // C++11 [basic.types] p11:
14330   // If two types T1 and T2 are the same type, then T1 and T2 are
14331   // layout-compatible types.
14332   if (C.hasSameType(T1, T2))
14333     return true;
14334 
14335   T1 = T1.getCanonicalType().getUnqualifiedType();
14336   T2 = T2.getCanonicalType().getUnqualifiedType();
14337 
14338   const Type::TypeClass TC1 = T1->getTypeClass();
14339   const Type::TypeClass TC2 = T2->getTypeClass();
14340 
14341   if (TC1 != TC2)
14342     return false;
14343 
14344   if (TC1 == Type::Enum) {
14345     return isLayoutCompatible(C,
14346                               cast<EnumType>(T1)->getDecl(),
14347                               cast<EnumType>(T2)->getDecl());
14348   } else if (TC1 == Type::Record) {
14349     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14350       return false;
14351 
14352     return isLayoutCompatible(C,
14353                               cast<RecordType>(T1)->getDecl(),
14354                               cast<RecordType>(T2)->getDecl());
14355   }
14356 
14357   return false;
14358 }
14359 
14360 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14361 
14362 /// Given a type tag expression find the type tag itself.
14363 ///
14364 /// \param TypeExpr Type tag expression, as it appears in user's code.
14365 ///
14366 /// \param VD Declaration of an identifier that appears in a type tag.
14367 ///
14368 /// \param MagicValue Type tag magic value.
14369 ///
14370 /// \param isConstantEvaluated wether the evalaution should be performed in
14371 
14372 /// constant context.
14373 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14374                             const ValueDecl **VD, uint64_t *MagicValue,
14375                             bool isConstantEvaluated) {
14376   while(true) {
14377     if (!TypeExpr)
14378       return false;
14379 
14380     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14381 
14382     switch (TypeExpr->getStmtClass()) {
14383     case Stmt::UnaryOperatorClass: {
14384       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14385       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14386         TypeExpr = UO->getSubExpr();
14387         continue;
14388       }
14389       return false;
14390     }
14391 
14392     case Stmt::DeclRefExprClass: {
14393       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14394       *VD = DRE->getDecl();
14395       return true;
14396     }
14397 
14398     case Stmt::IntegerLiteralClass: {
14399       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14400       llvm::APInt MagicValueAPInt = IL->getValue();
14401       if (MagicValueAPInt.getActiveBits() <= 64) {
14402         *MagicValue = MagicValueAPInt.getZExtValue();
14403         return true;
14404       } else
14405         return false;
14406     }
14407 
14408     case Stmt::BinaryConditionalOperatorClass:
14409     case Stmt::ConditionalOperatorClass: {
14410       const AbstractConditionalOperator *ACO =
14411           cast<AbstractConditionalOperator>(TypeExpr);
14412       bool Result;
14413       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14414                                                      isConstantEvaluated)) {
14415         if (Result)
14416           TypeExpr = ACO->getTrueExpr();
14417         else
14418           TypeExpr = ACO->getFalseExpr();
14419         continue;
14420       }
14421       return false;
14422     }
14423 
14424     case Stmt::BinaryOperatorClass: {
14425       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14426       if (BO->getOpcode() == BO_Comma) {
14427         TypeExpr = BO->getRHS();
14428         continue;
14429       }
14430       return false;
14431     }
14432 
14433     default:
14434       return false;
14435     }
14436   }
14437 }
14438 
14439 /// Retrieve the C type corresponding to type tag TypeExpr.
14440 ///
14441 /// \param TypeExpr Expression that specifies a type tag.
14442 ///
14443 /// \param MagicValues Registered magic values.
14444 ///
14445 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14446 ///        kind.
14447 ///
14448 /// \param TypeInfo Information about the corresponding C type.
14449 ///
14450 /// \param isConstantEvaluated wether the evalaution should be performed in
14451 /// constant context.
14452 ///
14453 /// \returns true if the corresponding C type was found.
14454 static bool GetMatchingCType(
14455     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14456     const ASTContext &Ctx,
14457     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14458         *MagicValues,
14459     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14460     bool isConstantEvaluated) {
14461   FoundWrongKind = false;
14462 
14463   // Variable declaration that has type_tag_for_datatype attribute.
14464   const ValueDecl *VD = nullptr;
14465 
14466   uint64_t MagicValue;
14467 
14468   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14469     return false;
14470 
14471   if (VD) {
14472     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14473       if (I->getArgumentKind() != ArgumentKind) {
14474         FoundWrongKind = true;
14475         return false;
14476       }
14477       TypeInfo.Type = I->getMatchingCType();
14478       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14479       TypeInfo.MustBeNull = I->getMustBeNull();
14480       return true;
14481     }
14482     return false;
14483   }
14484 
14485   if (!MagicValues)
14486     return false;
14487 
14488   llvm::DenseMap<Sema::TypeTagMagicValue,
14489                  Sema::TypeTagData>::const_iterator I =
14490       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14491   if (I == MagicValues->end())
14492     return false;
14493 
14494   TypeInfo = I->second;
14495   return true;
14496 }
14497 
14498 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14499                                       uint64_t MagicValue, QualType Type,
14500                                       bool LayoutCompatible,
14501                                       bool MustBeNull) {
14502   if (!TypeTagForDatatypeMagicValues)
14503     TypeTagForDatatypeMagicValues.reset(
14504         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14505 
14506   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14507   (*TypeTagForDatatypeMagicValues)[Magic] =
14508       TypeTagData(Type, LayoutCompatible, MustBeNull);
14509 }
14510 
14511 static bool IsSameCharType(QualType T1, QualType T2) {
14512   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14513   if (!BT1)
14514     return false;
14515 
14516   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14517   if (!BT2)
14518     return false;
14519 
14520   BuiltinType::Kind T1Kind = BT1->getKind();
14521   BuiltinType::Kind T2Kind = BT2->getKind();
14522 
14523   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14524          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14525          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14526          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14527 }
14528 
14529 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14530                                     const ArrayRef<const Expr *> ExprArgs,
14531                                     SourceLocation CallSiteLoc) {
14532   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14533   bool IsPointerAttr = Attr->getIsPointer();
14534 
14535   // Retrieve the argument representing the 'type_tag'.
14536   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14537   if (TypeTagIdxAST >= ExprArgs.size()) {
14538     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14539         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14540     return;
14541   }
14542   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14543   bool FoundWrongKind;
14544   TypeTagData TypeInfo;
14545   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14546                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14547                         TypeInfo, isConstantEvaluated())) {
14548     if (FoundWrongKind)
14549       Diag(TypeTagExpr->getExprLoc(),
14550            diag::warn_type_tag_for_datatype_wrong_kind)
14551         << TypeTagExpr->getSourceRange();
14552     return;
14553   }
14554 
14555   // Retrieve the argument representing the 'arg_idx'.
14556   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14557   if (ArgumentIdxAST >= ExprArgs.size()) {
14558     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14559         << 1 << Attr->getArgumentIdx().getSourceIndex();
14560     return;
14561   }
14562   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14563   if (IsPointerAttr) {
14564     // Skip implicit cast of pointer to `void *' (as a function argument).
14565     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14566       if (ICE->getType()->isVoidPointerType() &&
14567           ICE->getCastKind() == CK_BitCast)
14568         ArgumentExpr = ICE->getSubExpr();
14569   }
14570   QualType ArgumentType = ArgumentExpr->getType();
14571 
14572   // Passing a `void*' pointer shouldn't trigger a warning.
14573   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14574     return;
14575 
14576   if (TypeInfo.MustBeNull) {
14577     // Type tag with matching void type requires a null pointer.
14578     if (!ArgumentExpr->isNullPointerConstant(Context,
14579                                              Expr::NPC_ValueDependentIsNotNull)) {
14580       Diag(ArgumentExpr->getExprLoc(),
14581            diag::warn_type_safety_null_pointer_required)
14582           << ArgumentKind->getName()
14583           << ArgumentExpr->getSourceRange()
14584           << TypeTagExpr->getSourceRange();
14585     }
14586     return;
14587   }
14588 
14589   QualType RequiredType = TypeInfo.Type;
14590   if (IsPointerAttr)
14591     RequiredType = Context.getPointerType(RequiredType);
14592 
14593   bool mismatch = false;
14594   if (!TypeInfo.LayoutCompatible) {
14595     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14596 
14597     // C++11 [basic.fundamental] p1:
14598     // Plain char, signed char, and unsigned char are three distinct types.
14599     //
14600     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14601     // char' depending on the current char signedness mode.
14602     if (mismatch)
14603       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14604                                            RequiredType->getPointeeType())) ||
14605           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14606         mismatch = false;
14607   } else
14608     if (IsPointerAttr)
14609       mismatch = !isLayoutCompatible(Context,
14610                                      ArgumentType->getPointeeType(),
14611                                      RequiredType->getPointeeType());
14612     else
14613       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14614 
14615   if (mismatch)
14616     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14617         << ArgumentType << ArgumentKind
14618         << TypeInfo.LayoutCompatible << RequiredType
14619         << ArgumentExpr->getSourceRange()
14620         << TypeTagExpr->getSourceRange();
14621 }
14622 
14623 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14624                                          CharUnits Alignment) {
14625   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14626 }
14627 
14628 void Sema::DiagnoseMisalignedMembers() {
14629   for (MisalignedMember &m : MisalignedMembers) {
14630     const NamedDecl *ND = m.RD;
14631     if (ND->getName().empty()) {
14632       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14633         ND = TD;
14634     }
14635     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14636         << m.MD << ND << m.E->getSourceRange();
14637   }
14638   MisalignedMembers.clear();
14639 }
14640 
14641 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14642   E = E->IgnoreParens();
14643   if (!T->isPointerType() && !T->isIntegerType())
14644     return;
14645   if (isa<UnaryOperator>(E) &&
14646       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14647     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14648     if (isa<MemberExpr>(Op)) {
14649       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14650       if (MA != MisalignedMembers.end() &&
14651           (T->isIntegerType() ||
14652            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14653                                    Context.getTypeAlignInChars(
14654                                        T->getPointeeType()) <= MA->Alignment))))
14655         MisalignedMembers.erase(MA);
14656     }
14657   }
14658 }
14659 
14660 void Sema::RefersToMemberWithReducedAlignment(
14661     Expr *E,
14662     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14663         Action) {
14664   const auto *ME = dyn_cast<MemberExpr>(E);
14665   if (!ME)
14666     return;
14667 
14668   // No need to check expressions with an __unaligned-qualified type.
14669   if (E->getType().getQualifiers().hasUnaligned())
14670     return;
14671 
14672   // For a chain of MemberExpr like "a.b.c.d" this list
14673   // will keep FieldDecl's like [d, c, b].
14674   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14675   const MemberExpr *TopME = nullptr;
14676   bool AnyIsPacked = false;
14677   do {
14678     QualType BaseType = ME->getBase()->getType();
14679     if (ME->isArrow())
14680       BaseType = BaseType->getPointeeType();
14681     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14682     if (RD->isInvalidDecl())
14683       return;
14684 
14685     ValueDecl *MD = ME->getMemberDecl();
14686     auto *FD = dyn_cast<FieldDecl>(MD);
14687     // We do not care about non-data members.
14688     if (!FD || FD->isInvalidDecl())
14689       return;
14690 
14691     AnyIsPacked =
14692         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14693     ReverseMemberChain.push_back(FD);
14694 
14695     TopME = ME;
14696     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14697   } while (ME);
14698   assert(TopME && "We did not compute a topmost MemberExpr!");
14699 
14700   // Not the scope of this diagnostic.
14701   if (!AnyIsPacked)
14702     return;
14703 
14704   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14705   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14706   // TODO: The innermost base of the member expression may be too complicated.
14707   // For now, just disregard these cases. This is left for future
14708   // improvement.
14709   if (!DRE && !isa<CXXThisExpr>(TopBase))
14710       return;
14711 
14712   // Alignment expected by the whole expression.
14713   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14714 
14715   // No need to do anything else with this case.
14716   if (ExpectedAlignment.isOne())
14717     return;
14718 
14719   // Synthesize offset of the whole access.
14720   CharUnits Offset;
14721   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14722        I++) {
14723     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14724   }
14725 
14726   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14727   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14728       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14729 
14730   // The base expression of the innermost MemberExpr may give
14731   // stronger guarantees than the class containing the member.
14732   if (DRE && !TopME->isArrow()) {
14733     const ValueDecl *VD = DRE->getDecl();
14734     if (!VD->getType()->isReferenceType())
14735       CompleteObjectAlignment =
14736           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14737   }
14738 
14739   // Check if the synthesized offset fulfills the alignment.
14740   if (Offset % ExpectedAlignment != 0 ||
14741       // It may fulfill the offset it but the effective alignment may still be
14742       // lower than the expected expression alignment.
14743       CompleteObjectAlignment < ExpectedAlignment) {
14744     // If this happens, we want to determine a sensible culprit of this.
14745     // Intuitively, watching the chain of member expressions from right to
14746     // left, we start with the required alignment (as required by the field
14747     // type) but some packed attribute in that chain has reduced the alignment.
14748     // It may happen that another packed structure increases it again. But if
14749     // we are here such increase has not been enough. So pointing the first
14750     // FieldDecl that either is packed or else its RecordDecl is,
14751     // seems reasonable.
14752     FieldDecl *FD = nullptr;
14753     CharUnits Alignment;
14754     for (FieldDecl *FDI : ReverseMemberChain) {
14755       if (FDI->hasAttr<PackedAttr>() ||
14756           FDI->getParent()->hasAttr<PackedAttr>()) {
14757         FD = FDI;
14758         Alignment = std::min(
14759             Context.getTypeAlignInChars(FD->getType()),
14760             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14761         break;
14762       }
14763     }
14764     assert(FD && "We did not find a packed FieldDecl!");
14765     Action(E, FD->getParent(), FD, Alignment);
14766   }
14767 }
14768 
14769 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14770   using namespace std::placeholders;
14771 
14772   RefersToMemberWithReducedAlignment(
14773       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14774                      _2, _3, _4));
14775 }
14776