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_be:
1540         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1541           return ExprError();
1542         break;
1543       case llvm::Triple::bpfeb:
1544       case llvm::Triple::bpfel:
1545         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1546           return ExprError();
1547         break;
1548       case llvm::Triple::hexagon:
1549         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1550           return ExprError();
1551         break;
1552       case llvm::Triple::mips:
1553       case llvm::Triple::mipsel:
1554       case llvm::Triple::mips64:
1555       case llvm::Triple::mips64el:
1556         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1557           return ExprError();
1558         break;
1559       case llvm::Triple::systemz:
1560         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1561           return ExprError();
1562         break;
1563       case llvm::Triple::x86:
1564       case llvm::Triple::x86_64:
1565         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1566           return ExprError();
1567         break;
1568       case llvm::Triple::ppc:
1569       case llvm::Triple::ppc64:
1570       case llvm::Triple::ppc64le:
1571         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1572           return ExprError();
1573         break;
1574       default:
1575         break;
1576     }
1577   }
1578 
1579   return TheCallResult;
1580 }
1581 
1582 // Get the valid immediate range for the specified NEON type code.
1583 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1584   NeonTypeFlags Type(t);
1585   int IsQuad = ForceQuad ? true : Type.isQuad();
1586   switch (Type.getEltType()) {
1587   case NeonTypeFlags::Int8:
1588   case NeonTypeFlags::Poly8:
1589     return shift ? 7 : (8 << IsQuad) - 1;
1590   case NeonTypeFlags::Int16:
1591   case NeonTypeFlags::Poly16:
1592     return shift ? 15 : (4 << IsQuad) - 1;
1593   case NeonTypeFlags::Int32:
1594     return shift ? 31 : (2 << IsQuad) - 1;
1595   case NeonTypeFlags::Int64:
1596   case NeonTypeFlags::Poly64:
1597     return shift ? 63 : (1 << IsQuad) - 1;
1598   case NeonTypeFlags::Poly128:
1599     return shift ? 127 : (1 << IsQuad) - 1;
1600   case NeonTypeFlags::Float16:
1601     assert(!shift && "cannot shift float types!");
1602     return (4 << IsQuad) - 1;
1603   case NeonTypeFlags::Float32:
1604     assert(!shift && "cannot shift float types!");
1605     return (2 << IsQuad) - 1;
1606   case NeonTypeFlags::Float64:
1607     assert(!shift && "cannot shift float types!");
1608     return (1 << IsQuad) - 1;
1609   }
1610   llvm_unreachable("Invalid NeonTypeFlag!");
1611 }
1612 
1613 /// getNeonEltType - Return the QualType corresponding to the elements of
1614 /// the vector type specified by the NeonTypeFlags.  This is used to check
1615 /// the pointer arguments for Neon load/store intrinsics.
1616 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1617                                bool IsPolyUnsigned, bool IsInt64Long) {
1618   switch (Flags.getEltType()) {
1619   case NeonTypeFlags::Int8:
1620     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1621   case NeonTypeFlags::Int16:
1622     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1623   case NeonTypeFlags::Int32:
1624     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1625   case NeonTypeFlags::Int64:
1626     if (IsInt64Long)
1627       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1628     else
1629       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1630                                 : Context.LongLongTy;
1631   case NeonTypeFlags::Poly8:
1632     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1633   case NeonTypeFlags::Poly16:
1634     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1635   case NeonTypeFlags::Poly64:
1636     if (IsInt64Long)
1637       return Context.UnsignedLongTy;
1638     else
1639       return Context.UnsignedLongLongTy;
1640   case NeonTypeFlags::Poly128:
1641     break;
1642   case NeonTypeFlags::Float16:
1643     return Context.HalfTy;
1644   case NeonTypeFlags::Float32:
1645     return Context.FloatTy;
1646   case NeonTypeFlags::Float64:
1647     return Context.DoubleTy;
1648   }
1649   llvm_unreachable("Invalid NeonTypeFlag!");
1650 }
1651 
1652 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1653   llvm::APSInt Result;
1654   uint64_t mask = 0;
1655   unsigned TV = 0;
1656   int PtrArgNum = -1;
1657   bool HasConstPtr = false;
1658   switch (BuiltinID) {
1659 #define GET_NEON_OVERLOAD_CHECK
1660 #include "clang/Basic/arm_neon.inc"
1661 #include "clang/Basic/arm_fp16.inc"
1662 #undef GET_NEON_OVERLOAD_CHECK
1663   }
1664 
1665   // For NEON intrinsics which are overloaded on vector element type, validate
1666   // the immediate which specifies which variant to emit.
1667   unsigned ImmArg = TheCall->getNumArgs()-1;
1668   if (mask) {
1669     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1670       return true;
1671 
1672     TV = Result.getLimitedValue(64);
1673     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1674       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1675              << TheCall->getArg(ImmArg)->getSourceRange();
1676   }
1677 
1678   if (PtrArgNum >= 0) {
1679     // Check that pointer arguments have the specified type.
1680     Expr *Arg = TheCall->getArg(PtrArgNum);
1681     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1682       Arg = ICE->getSubExpr();
1683     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1684     QualType RHSTy = RHS.get()->getType();
1685 
1686     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1687     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1688                           Arch == llvm::Triple::aarch64_be;
1689     bool IsInt64Long =
1690         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1691     QualType EltTy =
1692         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1693     if (HasConstPtr)
1694       EltTy = EltTy.withConst();
1695     QualType LHSTy = Context.getPointerType(EltTy);
1696     AssignConvertType ConvTy;
1697     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1698     if (RHS.isInvalid())
1699       return true;
1700     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1701                                  RHS.get(), AA_Assigning))
1702       return true;
1703   }
1704 
1705   // For NEON intrinsics which take an immediate value as part of the
1706   // instruction, range check them here.
1707   unsigned i = 0, l = 0, u = 0;
1708   switch (BuiltinID) {
1709   default:
1710     return false;
1711   #define GET_NEON_IMMEDIATE_CHECK
1712   #include "clang/Basic/arm_neon.inc"
1713   #include "clang/Basic/arm_fp16.inc"
1714   #undef GET_NEON_IMMEDIATE_CHECK
1715   }
1716 
1717   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1718 }
1719 
1720 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1721                                         unsigned MaxWidth) {
1722   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1723           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1724           BuiltinID == ARM::BI__builtin_arm_strex ||
1725           BuiltinID == ARM::BI__builtin_arm_stlex ||
1726           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1727           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1728           BuiltinID == AArch64::BI__builtin_arm_strex ||
1729           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1730          "unexpected ARM builtin");
1731   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1732                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1733                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1734                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1735 
1736   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1737 
1738   // Ensure that we have the proper number of arguments.
1739   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1740     return true;
1741 
1742   // Inspect the pointer argument of the atomic builtin.  This should always be
1743   // a pointer type, whose element is an integral scalar or pointer type.
1744   // Because it is a pointer type, we don't have to worry about any implicit
1745   // casts here.
1746   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1747   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1748   if (PointerArgRes.isInvalid())
1749     return true;
1750   PointerArg = PointerArgRes.get();
1751 
1752   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1753   if (!pointerType) {
1754     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1755         << PointerArg->getType() << PointerArg->getSourceRange();
1756     return true;
1757   }
1758 
1759   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1760   // task is to insert the appropriate casts into the AST. First work out just
1761   // what the appropriate type is.
1762   QualType ValType = pointerType->getPointeeType();
1763   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1764   if (IsLdrex)
1765     AddrType.addConst();
1766 
1767   // Issue a warning if the cast is dodgy.
1768   CastKind CastNeeded = CK_NoOp;
1769   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1770     CastNeeded = CK_BitCast;
1771     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1772         << PointerArg->getType() << Context.getPointerType(AddrType)
1773         << AA_Passing << PointerArg->getSourceRange();
1774   }
1775 
1776   // Finally, do the cast and replace the argument with the corrected version.
1777   AddrType = Context.getPointerType(AddrType);
1778   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1779   if (PointerArgRes.isInvalid())
1780     return true;
1781   PointerArg = PointerArgRes.get();
1782 
1783   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1784 
1785   // In general, we allow ints, floats and pointers to be loaded and stored.
1786   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1787       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1788     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1789         << PointerArg->getType() << PointerArg->getSourceRange();
1790     return true;
1791   }
1792 
1793   // But ARM doesn't have instructions to deal with 128-bit versions.
1794   if (Context.getTypeSize(ValType) > MaxWidth) {
1795     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1796     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1797         << PointerArg->getType() << PointerArg->getSourceRange();
1798     return true;
1799   }
1800 
1801   switch (ValType.getObjCLifetime()) {
1802   case Qualifiers::OCL_None:
1803   case Qualifiers::OCL_ExplicitNone:
1804     // okay
1805     break;
1806 
1807   case Qualifiers::OCL_Weak:
1808   case Qualifiers::OCL_Strong:
1809   case Qualifiers::OCL_Autoreleasing:
1810     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1811         << ValType << PointerArg->getSourceRange();
1812     return true;
1813   }
1814 
1815   if (IsLdrex) {
1816     TheCall->setType(ValType);
1817     return false;
1818   }
1819 
1820   // Initialize the argument to be stored.
1821   ExprResult ValArg = TheCall->getArg(0);
1822   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1823       Context, ValType, /*consume*/ false);
1824   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1825   if (ValArg.isInvalid())
1826     return true;
1827   TheCall->setArg(0, ValArg.get());
1828 
1829   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1830   // but the custom checker bypasses all default analysis.
1831   TheCall->setType(Context.IntTy);
1832   return false;
1833 }
1834 
1835 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1836   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1837       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1838       BuiltinID == ARM::BI__builtin_arm_strex ||
1839       BuiltinID == ARM::BI__builtin_arm_stlex) {
1840     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1841   }
1842 
1843   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1844     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1845       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1846   }
1847 
1848   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1849       BuiltinID == ARM::BI__builtin_arm_wsr64)
1850     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1851 
1852   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1853       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1854       BuiltinID == ARM::BI__builtin_arm_wsr ||
1855       BuiltinID == ARM::BI__builtin_arm_wsrp)
1856     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1857 
1858   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1859     return true;
1860 
1861   // For intrinsics which take an immediate value as part of the instruction,
1862   // range check them here.
1863   // FIXME: VFP Intrinsics should error if VFP not present.
1864   switch (BuiltinID) {
1865   default: return false;
1866   case ARM::BI__builtin_arm_ssat:
1867     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1868   case ARM::BI__builtin_arm_usat:
1869     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1870   case ARM::BI__builtin_arm_ssat16:
1871     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1872   case ARM::BI__builtin_arm_usat16:
1873     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1874   case ARM::BI__builtin_arm_vcvtr_f:
1875   case ARM::BI__builtin_arm_vcvtr_d:
1876     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1877   case ARM::BI__builtin_arm_dmb:
1878   case ARM::BI__builtin_arm_dsb:
1879   case ARM::BI__builtin_arm_isb:
1880   case ARM::BI__builtin_arm_dbg:
1881     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1882   }
1883 }
1884 
1885 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1886                                          CallExpr *TheCall) {
1887   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1888       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1889       BuiltinID == AArch64::BI__builtin_arm_strex ||
1890       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1891     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1892   }
1893 
1894   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1895     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1896       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1897       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1898       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1899   }
1900 
1901   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1902       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1903     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1904 
1905   // Memory Tagging Extensions (MTE) Intrinsics
1906   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1907       BuiltinID == AArch64::BI__builtin_arm_addg ||
1908       BuiltinID == AArch64::BI__builtin_arm_gmi ||
1909       BuiltinID == AArch64::BI__builtin_arm_ldg ||
1910       BuiltinID == AArch64::BI__builtin_arm_stg ||
1911       BuiltinID == AArch64::BI__builtin_arm_subp) {
1912     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1913   }
1914 
1915   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1916       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1917       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1918       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1919     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1920 
1921   // Only check the valid encoding range. Any constant in this range would be
1922   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1923   // an exception for incorrect registers. This matches MSVC behavior.
1924   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1925       BuiltinID == AArch64::BI_WriteStatusReg)
1926     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1927 
1928   if (BuiltinID == AArch64::BI__getReg)
1929     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1930 
1931   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1932     return true;
1933 
1934   // For intrinsics which take an immediate value as part of the instruction,
1935   // range check them here.
1936   unsigned i = 0, l = 0, u = 0;
1937   switch (BuiltinID) {
1938   default: return false;
1939   case AArch64::BI__builtin_arm_dmb:
1940   case AArch64::BI__builtin_arm_dsb:
1941   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1942   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
1943   }
1944 
1945   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1946 }
1947 
1948 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
1949                                        CallExpr *TheCall) {
1950   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
1951          "unexpected ARM builtin");
1952 
1953   if (checkArgCount(*this, TheCall, 2))
1954     return true;
1955 
1956   // The first argument needs to be a record field access.
1957   // If it is an array element access, we delay decision
1958   // to BPF backend to check whether the access is a
1959   // field access or not.
1960   Expr *Arg = TheCall->getArg(0);
1961   if (Arg->getType()->getAsPlaceholderType() ||
1962       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
1963        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
1964        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
1965     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
1966         << 1 << Arg->getSourceRange();
1967     return true;
1968   }
1969 
1970   // The second argument needs to be a constant int
1971   llvm::APSInt Value;
1972   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
1973     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
1974         << 2 << Arg->getSourceRange();
1975     return true;
1976   }
1977 
1978   TheCall->setType(Context.UnsignedIntTy);
1979   return false;
1980 }
1981 
1982 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1983   struct BuiltinAndString {
1984     unsigned BuiltinID;
1985     const char *Str;
1986   };
1987 
1988   static BuiltinAndString ValidCPU[] = {
1989     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1992     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1993     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1994     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1997     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
2012   };
2013 
2014   static BuiltinAndString ValidHVX[] = {
2015     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2671     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2672     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2673     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2674     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2675     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2676     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2677     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2678     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2679     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2680     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2681     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2682     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2683     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2684     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2685     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2686     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2687     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2688     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2689     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2690     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2691     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2692     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2693     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2694     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2695     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2696     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2697     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2706     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2708     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2709     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2710     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2711     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2712     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2713     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2714     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2715     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2716     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2717     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2718     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2719     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2720     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2721     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2722     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2723     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2724     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2725     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2726     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2727     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2728     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2729     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2730     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2733     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2734     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2735     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2736     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2737     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2738     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2739     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2740     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2741     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2742     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2743     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2744     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2745     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2746     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2747   };
2748 
2749   // Sort the tables on first execution so we can binary search them.
2750   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2751     return LHS.BuiltinID < RHS.BuiltinID;
2752   };
2753   static const bool SortOnce =
2754       (llvm::sort(ValidCPU, SortCmp),
2755        llvm::sort(ValidHVX, SortCmp), true);
2756   (void)SortOnce;
2757   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2758     return BI.BuiltinID < BuiltinID;
2759   };
2760 
2761   const TargetInfo &TI = Context.getTargetInfo();
2762 
2763   const BuiltinAndString *FC =
2764       llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2765   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2766     const TargetOptions &Opts = TI.getTargetOpts();
2767     StringRef CPU = Opts.CPU;
2768     if (!CPU.empty()) {
2769       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2770       CPU.consume_front("hexagon");
2771       SmallVector<StringRef, 3> CPUs;
2772       StringRef(FC->Str).split(CPUs, ',');
2773       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2774         return Diag(TheCall->getBeginLoc(),
2775                     diag::err_hexagon_builtin_unsupported_cpu);
2776     }
2777   }
2778 
2779   const BuiltinAndString *FH =
2780       llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2781   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2782     if (!TI.hasFeature("hvx"))
2783       return Diag(TheCall->getBeginLoc(),
2784                   diag::err_hexagon_builtin_requires_hvx);
2785 
2786     SmallVector<StringRef, 3> HVXs;
2787     StringRef(FH->Str).split(HVXs, ',');
2788     bool IsValid = llvm::any_of(HVXs,
2789                                 [&TI] (StringRef V) {
2790                                   std::string F = "hvx" + V.str();
2791                                   return TI.hasFeature(F);
2792                                 });
2793     if (!IsValid)
2794       return Diag(TheCall->getBeginLoc(),
2795                   diag::err_hexagon_builtin_unsupported_hvx);
2796   }
2797 
2798   return false;
2799 }
2800 
2801 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2802   struct ArgInfo {
2803     uint8_t OpNum;
2804     bool IsSigned;
2805     uint8_t BitWidth;
2806     uint8_t Align;
2807   };
2808   struct BuiltinInfo {
2809     unsigned BuiltinID;
2810     ArgInfo Infos[2];
2811   };
2812 
2813   static BuiltinInfo Infos[] = {
2814     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2815     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2816     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2817     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2818     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2819     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2820     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2821     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2822     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2823     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2824     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2825 
2826     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2829     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2830     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2831     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2837 
2838     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2890                                                       {{ 1, false, 6,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2898                                                       {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2905                                                        { 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2907                                                        { 2, false, 6,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2909                                                        { 3, false, 5,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2911                                                        { 3, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2928                                                       {{ 2, false, 4,  0 },
2929                                                        { 3, false, 5,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2931                                                       {{ 2, false, 4,  0 },
2932                                                        { 3, false, 5,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2934                                                       {{ 2, false, 4,  0 },
2935                                                        { 3, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2937                                                       {{ 2, false, 4,  0 },
2938                                                        { 3, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2950                                                        { 2, false, 5,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2952                                                        { 2, false, 6,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2961     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2962                                                       {{ 1, false, 4,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2964     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2965                                                       {{ 1, false, 4,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2967     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2968     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2969     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2970     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2971     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2972     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2973     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2974     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2975     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2976     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2977     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2978     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2979     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2980     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2981     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2982     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2983     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2984     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2985     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2986                                                       {{ 3, false, 1,  0 }} },
2987     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2988     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2989     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2990     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2991                                                       {{ 3, false, 1,  0 }} },
2992     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2993     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2994     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2995     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2996                                                       {{ 3, false, 1,  0 }} },
2997   };
2998 
2999   // Use a dynamically initialized static to sort the table exactly once on
3000   // first run.
3001   static const bool SortOnce =
3002       (llvm::sort(Infos,
3003                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3004                    return LHS.BuiltinID < RHS.BuiltinID;
3005                  }),
3006        true);
3007   (void)SortOnce;
3008 
3009   const BuiltinInfo *F = llvm::partition_point(
3010       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3011   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3012     return false;
3013 
3014   bool Error = false;
3015 
3016   for (const ArgInfo &A : F->Infos) {
3017     // Ignore empty ArgInfo elements.
3018     if (A.BitWidth == 0)
3019       continue;
3020 
3021     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3022     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3023     if (!A.Align) {
3024       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3025     } else {
3026       unsigned M = 1 << A.Align;
3027       Min *= M;
3028       Max *= M;
3029       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
3030                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3031     }
3032   }
3033   return Error;
3034 }
3035 
3036 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3037                                            CallExpr *TheCall) {
3038   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3039          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3040 }
3041 
3042 
3043 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3044 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3045 // ordering for DSP is unspecified. MSA is ordered by the data format used
3046 // by the underlying instruction i.e., df/m, df/n and then by size.
3047 //
3048 // FIXME: The size tests here should instead be tablegen'd along with the
3049 //        definitions from include/clang/Basic/BuiltinsMips.def.
3050 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3051 //        be too.
3052 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3053   unsigned i = 0, l = 0, u = 0, m = 0;
3054   switch (BuiltinID) {
3055   default: return false;
3056   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3057   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3058   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3059   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3060   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3061   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3062   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3063   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3064   // df/m field.
3065   // These intrinsics take an unsigned 3 bit immediate.
3066   case Mips::BI__builtin_msa_bclri_b:
3067   case Mips::BI__builtin_msa_bnegi_b:
3068   case Mips::BI__builtin_msa_bseti_b:
3069   case Mips::BI__builtin_msa_sat_s_b:
3070   case Mips::BI__builtin_msa_sat_u_b:
3071   case Mips::BI__builtin_msa_slli_b:
3072   case Mips::BI__builtin_msa_srai_b:
3073   case Mips::BI__builtin_msa_srari_b:
3074   case Mips::BI__builtin_msa_srli_b:
3075   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3076   case Mips::BI__builtin_msa_binsli_b:
3077   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3078   // These intrinsics take an unsigned 4 bit immediate.
3079   case Mips::BI__builtin_msa_bclri_h:
3080   case Mips::BI__builtin_msa_bnegi_h:
3081   case Mips::BI__builtin_msa_bseti_h:
3082   case Mips::BI__builtin_msa_sat_s_h:
3083   case Mips::BI__builtin_msa_sat_u_h:
3084   case Mips::BI__builtin_msa_slli_h:
3085   case Mips::BI__builtin_msa_srai_h:
3086   case Mips::BI__builtin_msa_srari_h:
3087   case Mips::BI__builtin_msa_srli_h:
3088   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3089   case Mips::BI__builtin_msa_binsli_h:
3090   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3091   // These intrinsics take an unsigned 5 bit immediate.
3092   // The first block of intrinsics actually have an unsigned 5 bit field,
3093   // not a df/n field.
3094   case Mips::BI__builtin_msa_cfcmsa:
3095   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3096   case Mips::BI__builtin_msa_clei_u_b:
3097   case Mips::BI__builtin_msa_clei_u_h:
3098   case Mips::BI__builtin_msa_clei_u_w:
3099   case Mips::BI__builtin_msa_clei_u_d:
3100   case Mips::BI__builtin_msa_clti_u_b:
3101   case Mips::BI__builtin_msa_clti_u_h:
3102   case Mips::BI__builtin_msa_clti_u_w:
3103   case Mips::BI__builtin_msa_clti_u_d:
3104   case Mips::BI__builtin_msa_maxi_u_b:
3105   case Mips::BI__builtin_msa_maxi_u_h:
3106   case Mips::BI__builtin_msa_maxi_u_w:
3107   case Mips::BI__builtin_msa_maxi_u_d:
3108   case Mips::BI__builtin_msa_mini_u_b:
3109   case Mips::BI__builtin_msa_mini_u_h:
3110   case Mips::BI__builtin_msa_mini_u_w:
3111   case Mips::BI__builtin_msa_mini_u_d:
3112   case Mips::BI__builtin_msa_addvi_b:
3113   case Mips::BI__builtin_msa_addvi_h:
3114   case Mips::BI__builtin_msa_addvi_w:
3115   case Mips::BI__builtin_msa_addvi_d:
3116   case Mips::BI__builtin_msa_bclri_w:
3117   case Mips::BI__builtin_msa_bnegi_w:
3118   case Mips::BI__builtin_msa_bseti_w:
3119   case Mips::BI__builtin_msa_sat_s_w:
3120   case Mips::BI__builtin_msa_sat_u_w:
3121   case Mips::BI__builtin_msa_slli_w:
3122   case Mips::BI__builtin_msa_srai_w:
3123   case Mips::BI__builtin_msa_srari_w:
3124   case Mips::BI__builtin_msa_srli_w:
3125   case Mips::BI__builtin_msa_srlri_w:
3126   case Mips::BI__builtin_msa_subvi_b:
3127   case Mips::BI__builtin_msa_subvi_h:
3128   case Mips::BI__builtin_msa_subvi_w:
3129   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3130   case Mips::BI__builtin_msa_binsli_w:
3131   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3132   // These intrinsics take an unsigned 6 bit immediate.
3133   case Mips::BI__builtin_msa_bclri_d:
3134   case Mips::BI__builtin_msa_bnegi_d:
3135   case Mips::BI__builtin_msa_bseti_d:
3136   case Mips::BI__builtin_msa_sat_s_d:
3137   case Mips::BI__builtin_msa_sat_u_d:
3138   case Mips::BI__builtin_msa_slli_d:
3139   case Mips::BI__builtin_msa_srai_d:
3140   case Mips::BI__builtin_msa_srari_d:
3141   case Mips::BI__builtin_msa_srli_d:
3142   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3143   case Mips::BI__builtin_msa_binsli_d:
3144   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3145   // These intrinsics take a signed 5 bit immediate.
3146   case Mips::BI__builtin_msa_ceqi_b:
3147   case Mips::BI__builtin_msa_ceqi_h:
3148   case Mips::BI__builtin_msa_ceqi_w:
3149   case Mips::BI__builtin_msa_ceqi_d:
3150   case Mips::BI__builtin_msa_clti_s_b:
3151   case Mips::BI__builtin_msa_clti_s_h:
3152   case Mips::BI__builtin_msa_clti_s_w:
3153   case Mips::BI__builtin_msa_clti_s_d:
3154   case Mips::BI__builtin_msa_clei_s_b:
3155   case Mips::BI__builtin_msa_clei_s_h:
3156   case Mips::BI__builtin_msa_clei_s_w:
3157   case Mips::BI__builtin_msa_clei_s_d:
3158   case Mips::BI__builtin_msa_maxi_s_b:
3159   case Mips::BI__builtin_msa_maxi_s_h:
3160   case Mips::BI__builtin_msa_maxi_s_w:
3161   case Mips::BI__builtin_msa_maxi_s_d:
3162   case Mips::BI__builtin_msa_mini_s_b:
3163   case Mips::BI__builtin_msa_mini_s_h:
3164   case Mips::BI__builtin_msa_mini_s_w:
3165   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3166   // These intrinsics take an unsigned 8 bit immediate.
3167   case Mips::BI__builtin_msa_andi_b:
3168   case Mips::BI__builtin_msa_nori_b:
3169   case Mips::BI__builtin_msa_ori_b:
3170   case Mips::BI__builtin_msa_shf_b:
3171   case Mips::BI__builtin_msa_shf_h:
3172   case Mips::BI__builtin_msa_shf_w:
3173   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3174   case Mips::BI__builtin_msa_bseli_b:
3175   case Mips::BI__builtin_msa_bmnzi_b:
3176   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3177   // df/n format
3178   // These intrinsics take an unsigned 4 bit immediate.
3179   case Mips::BI__builtin_msa_copy_s_b:
3180   case Mips::BI__builtin_msa_copy_u_b:
3181   case Mips::BI__builtin_msa_insve_b:
3182   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3183   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3184   // These intrinsics take an unsigned 3 bit immediate.
3185   case Mips::BI__builtin_msa_copy_s_h:
3186   case Mips::BI__builtin_msa_copy_u_h:
3187   case Mips::BI__builtin_msa_insve_h:
3188   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3189   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3190   // These intrinsics take an unsigned 2 bit immediate.
3191   case Mips::BI__builtin_msa_copy_s_w:
3192   case Mips::BI__builtin_msa_copy_u_w:
3193   case Mips::BI__builtin_msa_insve_w:
3194   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3195   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3196   // These intrinsics take an unsigned 1 bit immediate.
3197   case Mips::BI__builtin_msa_copy_s_d:
3198   case Mips::BI__builtin_msa_copy_u_d:
3199   case Mips::BI__builtin_msa_insve_d:
3200   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3201   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3202   // Memory offsets and immediate loads.
3203   // These intrinsics take a signed 10 bit immediate.
3204   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3205   case Mips::BI__builtin_msa_ldi_h:
3206   case Mips::BI__builtin_msa_ldi_w:
3207   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3208   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3209   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3210   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3211   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3212   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3213   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3214   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3215   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3216   }
3217 
3218   if (!m)
3219     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3220 
3221   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3222          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3223 }
3224 
3225 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3226   unsigned i = 0, l = 0, u = 0;
3227   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3228                       BuiltinID == PPC::BI__builtin_divdeu ||
3229                       BuiltinID == PPC::BI__builtin_bpermd;
3230   bool IsTarget64Bit = Context.getTargetInfo()
3231                               .getTypeWidth(Context
3232                                             .getTargetInfo()
3233                                             .getIntPtrType()) == 64;
3234   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3235                        BuiltinID == PPC::BI__builtin_divweu ||
3236                        BuiltinID == PPC::BI__builtin_divde ||
3237                        BuiltinID == PPC::BI__builtin_divdeu;
3238 
3239   if (Is64BitBltin && !IsTarget64Bit)
3240     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3241            << TheCall->getSourceRange();
3242 
3243   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3244       (BuiltinID == PPC::BI__builtin_bpermd &&
3245        !Context.getTargetInfo().hasFeature("bpermd")))
3246     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3247            << TheCall->getSourceRange();
3248 
3249   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3250     if (!Context.getTargetInfo().hasFeature("vsx"))
3251       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3252              << TheCall->getSourceRange();
3253     return false;
3254   };
3255 
3256   switch (BuiltinID) {
3257   default: return false;
3258   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3259   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3260     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3261            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3262   case PPC::BI__builtin_altivec_dss:
3263     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3264   case PPC::BI__builtin_tbegin:
3265   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3266   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3267   case PPC::BI__builtin_tabortwc:
3268   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3269   case PPC::BI__builtin_tabortwci:
3270   case PPC::BI__builtin_tabortdci:
3271     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3272            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3273   case PPC::BI__builtin_altivec_dst:
3274   case PPC::BI__builtin_altivec_dstt:
3275   case PPC::BI__builtin_altivec_dstst:
3276   case PPC::BI__builtin_altivec_dststt:
3277     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3278   case PPC::BI__builtin_vsx_xxpermdi:
3279   case PPC::BI__builtin_vsx_xxsldwi:
3280     return SemaBuiltinVSX(TheCall);
3281   case PPC::BI__builtin_unpack_vector_int128:
3282     return SemaVSXCheck(TheCall) ||
3283            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3284   case PPC::BI__builtin_pack_vector_int128:
3285     return SemaVSXCheck(TheCall);
3286   }
3287   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3288 }
3289 
3290 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3291                                            CallExpr *TheCall) {
3292   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3293     Expr *Arg = TheCall->getArg(0);
3294     llvm::APSInt AbortCode(32);
3295     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3296         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3297       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3298              << Arg->getSourceRange();
3299   }
3300 
3301   // For intrinsics which take an immediate value as part of the instruction,
3302   // range check them here.
3303   unsigned i = 0, l = 0, u = 0;
3304   switch (BuiltinID) {
3305   default: return false;
3306   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3307   case SystemZ::BI__builtin_s390_verimb:
3308   case SystemZ::BI__builtin_s390_verimh:
3309   case SystemZ::BI__builtin_s390_verimf:
3310   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3311   case SystemZ::BI__builtin_s390_vfaeb:
3312   case SystemZ::BI__builtin_s390_vfaeh:
3313   case SystemZ::BI__builtin_s390_vfaef:
3314   case SystemZ::BI__builtin_s390_vfaebs:
3315   case SystemZ::BI__builtin_s390_vfaehs:
3316   case SystemZ::BI__builtin_s390_vfaefs:
3317   case SystemZ::BI__builtin_s390_vfaezb:
3318   case SystemZ::BI__builtin_s390_vfaezh:
3319   case SystemZ::BI__builtin_s390_vfaezf:
3320   case SystemZ::BI__builtin_s390_vfaezbs:
3321   case SystemZ::BI__builtin_s390_vfaezhs:
3322   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3323   case SystemZ::BI__builtin_s390_vfisb:
3324   case SystemZ::BI__builtin_s390_vfidb:
3325     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3326            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3327   case SystemZ::BI__builtin_s390_vftcisb:
3328   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3329   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3330   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3331   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3332   case SystemZ::BI__builtin_s390_vstrcb:
3333   case SystemZ::BI__builtin_s390_vstrch:
3334   case SystemZ::BI__builtin_s390_vstrcf:
3335   case SystemZ::BI__builtin_s390_vstrczb:
3336   case SystemZ::BI__builtin_s390_vstrczh:
3337   case SystemZ::BI__builtin_s390_vstrczf:
3338   case SystemZ::BI__builtin_s390_vstrcbs:
3339   case SystemZ::BI__builtin_s390_vstrchs:
3340   case SystemZ::BI__builtin_s390_vstrcfs:
3341   case SystemZ::BI__builtin_s390_vstrczbs:
3342   case SystemZ::BI__builtin_s390_vstrczhs:
3343   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3344   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3345   case SystemZ::BI__builtin_s390_vfminsb:
3346   case SystemZ::BI__builtin_s390_vfmaxsb:
3347   case SystemZ::BI__builtin_s390_vfmindb:
3348   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3349   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3350   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3351   }
3352   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3353 }
3354 
3355 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3356 /// This checks that the target supports __builtin_cpu_supports and
3357 /// that the string argument is constant and valid.
3358 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3359   Expr *Arg = TheCall->getArg(0);
3360 
3361   // Check if the argument is a string literal.
3362   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3363     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3364            << Arg->getSourceRange();
3365 
3366   // Check the contents of the string.
3367   StringRef Feature =
3368       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3369   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3370     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3371            << Arg->getSourceRange();
3372   return false;
3373 }
3374 
3375 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3376 /// This checks that the target supports __builtin_cpu_is and
3377 /// that the string argument is constant and valid.
3378 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3379   Expr *Arg = TheCall->getArg(0);
3380 
3381   // Check if the argument is a string literal.
3382   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3383     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3384            << Arg->getSourceRange();
3385 
3386   // Check the contents of the string.
3387   StringRef Feature =
3388       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3389   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3390     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3391            << Arg->getSourceRange();
3392   return false;
3393 }
3394 
3395 // Check if the rounding mode is legal.
3396 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3397   // Indicates if this instruction has rounding control or just SAE.
3398   bool HasRC = false;
3399 
3400   unsigned ArgNum = 0;
3401   switch (BuiltinID) {
3402   default:
3403     return false;
3404   case X86::BI__builtin_ia32_vcvttsd2si32:
3405   case X86::BI__builtin_ia32_vcvttsd2si64:
3406   case X86::BI__builtin_ia32_vcvttsd2usi32:
3407   case X86::BI__builtin_ia32_vcvttsd2usi64:
3408   case X86::BI__builtin_ia32_vcvttss2si32:
3409   case X86::BI__builtin_ia32_vcvttss2si64:
3410   case X86::BI__builtin_ia32_vcvttss2usi32:
3411   case X86::BI__builtin_ia32_vcvttss2usi64:
3412     ArgNum = 1;
3413     break;
3414   case X86::BI__builtin_ia32_maxpd512:
3415   case X86::BI__builtin_ia32_maxps512:
3416   case X86::BI__builtin_ia32_minpd512:
3417   case X86::BI__builtin_ia32_minps512:
3418     ArgNum = 2;
3419     break;
3420   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3421   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3422   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3423   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3424   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3425   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3426   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3427   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3428   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3429   case X86::BI__builtin_ia32_exp2pd_mask:
3430   case X86::BI__builtin_ia32_exp2ps_mask:
3431   case X86::BI__builtin_ia32_getexppd512_mask:
3432   case X86::BI__builtin_ia32_getexpps512_mask:
3433   case X86::BI__builtin_ia32_rcp28pd_mask:
3434   case X86::BI__builtin_ia32_rcp28ps_mask:
3435   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3436   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3437   case X86::BI__builtin_ia32_vcomisd:
3438   case X86::BI__builtin_ia32_vcomiss:
3439   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3440     ArgNum = 3;
3441     break;
3442   case X86::BI__builtin_ia32_cmppd512_mask:
3443   case X86::BI__builtin_ia32_cmpps512_mask:
3444   case X86::BI__builtin_ia32_cmpsd_mask:
3445   case X86::BI__builtin_ia32_cmpss_mask:
3446   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3447   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3448   case X86::BI__builtin_ia32_getexpss128_round_mask:
3449   case X86::BI__builtin_ia32_getmantpd512_mask:
3450   case X86::BI__builtin_ia32_getmantps512_mask:
3451   case X86::BI__builtin_ia32_maxsd_round_mask:
3452   case X86::BI__builtin_ia32_maxss_round_mask:
3453   case X86::BI__builtin_ia32_minsd_round_mask:
3454   case X86::BI__builtin_ia32_minss_round_mask:
3455   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3456   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3457   case X86::BI__builtin_ia32_reducepd512_mask:
3458   case X86::BI__builtin_ia32_reduceps512_mask:
3459   case X86::BI__builtin_ia32_rndscalepd_mask:
3460   case X86::BI__builtin_ia32_rndscaleps_mask:
3461   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3462   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3463     ArgNum = 4;
3464     break;
3465   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3466   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3467   case X86::BI__builtin_ia32_fixupimmps512_mask:
3468   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3469   case X86::BI__builtin_ia32_fixupimmsd_mask:
3470   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3471   case X86::BI__builtin_ia32_fixupimmss_mask:
3472   case X86::BI__builtin_ia32_fixupimmss_maskz:
3473   case X86::BI__builtin_ia32_getmantsd_round_mask:
3474   case X86::BI__builtin_ia32_getmantss_round_mask:
3475   case X86::BI__builtin_ia32_rangepd512_mask:
3476   case X86::BI__builtin_ia32_rangeps512_mask:
3477   case X86::BI__builtin_ia32_rangesd128_round_mask:
3478   case X86::BI__builtin_ia32_rangess128_round_mask:
3479   case X86::BI__builtin_ia32_reducesd_mask:
3480   case X86::BI__builtin_ia32_reducess_mask:
3481   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3482   case X86::BI__builtin_ia32_rndscaless_round_mask:
3483     ArgNum = 5;
3484     break;
3485   case X86::BI__builtin_ia32_vcvtsd2si64:
3486   case X86::BI__builtin_ia32_vcvtsd2si32:
3487   case X86::BI__builtin_ia32_vcvtsd2usi32:
3488   case X86::BI__builtin_ia32_vcvtsd2usi64:
3489   case X86::BI__builtin_ia32_vcvtss2si32:
3490   case X86::BI__builtin_ia32_vcvtss2si64:
3491   case X86::BI__builtin_ia32_vcvtss2usi32:
3492   case X86::BI__builtin_ia32_vcvtss2usi64:
3493   case X86::BI__builtin_ia32_sqrtpd512:
3494   case X86::BI__builtin_ia32_sqrtps512:
3495     ArgNum = 1;
3496     HasRC = true;
3497     break;
3498   case X86::BI__builtin_ia32_addpd512:
3499   case X86::BI__builtin_ia32_addps512:
3500   case X86::BI__builtin_ia32_divpd512:
3501   case X86::BI__builtin_ia32_divps512:
3502   case X86::BI__builtin_ia32_mulpd512:
3503   case X86::BI__builtin_ia32_mulps512:
3504   case X86::BI__builtin_ia32_subpd512:
3505   case X86::BI__builtin_ia32_subps512:
3506   case X86::BI__builtin_ia32_cvtsi2sd64:
3507   case X86::BI__builtin_ia32_cvtsi2ss32:
3508   case X86::BI__builtin_ia32_cvtsi2ss64:
3509   case X86::BI__builtin_ia32_cvtusi2sd64:
3510   case X86::BI__builtin_ia32_cvtusi2ss32:
3511   case X86::BI__builtin_ia32_cvtusi2ss64:
3512     ArgNum = 2;
3513     HasRC = true;
3514     break;
3515   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3516   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3517   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3518   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3519   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3520   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3521   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3522   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3523   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3524   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3525   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3526   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3527   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3528   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3529   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3530     ArgNum = 3;
3531     HasRC = true;
3532     break;
3533   case X86::BI__builtin_ia32_addss_round_mask:
3534   case X86::BI__builtin_ia32_addsd_round_mask:
3535   case X86::BI__builtin_ia32_divss_round_mask:
3536   case X86::BI__builtin_ia32_divsd_round_mask:
3537   case X86::BI__builtin_ia32_mulss_round_mask:
3538   case X86::BI__builtin_ia32_mulsd_round_mask:
3539   case X86::BI__builtin_ia32_subss_round_mask:
3540   case X86::BI__builtin_ia32_subsd_round_mask:
3541   case X86::BI__builtin_ia32_scalefpd512_mask:
3542   case X86::BI__builtin_ia32_scalefps512_mask:
3543   case X86::BI__builtin_ia32_scalefsd_round_mask:
3544   case X86::BI__builtin_ia32_scalefss_round_mask:
3545   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3546   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3547   case X86::BI__builtin_ia32_sqrtss_round_mask:
3548   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3549   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3550   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3551   case X86::BI__builtin_ia32_vfmaddss3_mask:
3552   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3553   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3554   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3555   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3556   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3557   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3558   case X86::BI__builtin_ia32_vfmaddps512_mask:
3559   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3560   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3561   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3562   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3563   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3564   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3565   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3566   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3567   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3568   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3569   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3570     ArgNum = 4;
3571     HasRC = true;
3572     break;
3573   }
3574 
3575   llvm::APSInt Result;
3576 
3577   // We can't check the value of a dependent argument.
3578   Expr *Arg = TheCall->getArg(ArgNum);
3579   if (Arg->isTypeDependent() || Arg->isValueDependent())
3580     return false;
3581 
3582   // Check constant-ness first.
3583   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3584     return true;
3585 
3586   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3587   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3588   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3589   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3590   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3591       Result == 8/*ROUND_NO_EXC*/ ||
3592       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3593       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3594     return false;
3595 
3596   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3597          << Arg->getSourceRange();
3598 }
3599 
3600 // Check if the gather/scatter scale is legal.
3601 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3602                                              CallExpr *TheCall) {
3603   unsigned ArgNum = 0;
3604   switch (BuiltinID) {
3605   default:
3606     return false;
3607   case X86::BI__builtin_ia32_gatherpfdpd:
3608   case X86::BI__builtin_ia32_gatherpfdps:
3609   case X86::BI__builtin_ia32_gatherpfqpd:
3610   case X86::BI__builtin_ia32_gatherpfqps:
3611   case X86::BI__builtin_ia32_scatterpfdpd:
3612   case X86::BI__builtin_ia32_scatterpfdps:
3613   case X86::BI__builtin_ia32_scatterpfqpd:
3614   case X86::BI__builtin_ia32_scatterpfqps:
3615     ArgNum = 3;
3616     break;
3617   case X86::BI__builtin_ia32_gatherd_pd:
3618   case X86::BI__builtin_ia32_gatherd_pd256:
3619   case X86::BI__builtin_ia32_gatherq_pd:
3620   case X86::BI__builtin_ia32_gatherq_pd256:
3621   case X86::BI__builtin_ia32_gatherd_ps:
3622   case X86::BI__builtin_ia32_gatherd_ps256:
3623   case X86::BI__builtin_ia32_gatherq_ps:
3624   case X86::BI__builtin_ia32_gatherq_ps256:
3625   case X86::BI__builtin_ia32_gatherd_q:
3626   case X86::BI__builtin_ia32_gatherd_q256:
3627   case X86::BI__builtin_ia32_gatherq_q:
3628   case X86::BI__builtin_ia32_gatherq_q256:
3629   case X86::BI__builtin_ia32_gatherd_d:
3630   case X86::BI__builtin_ia32_gatherd_d256:
3631   case X86::BI__builtin_ia32_gatherq_d:
3632   case X86::BI__builtin_ia32_gatherq_d256:
3633   case X86::BI__builtin_ia32_gather3div2df:
3634   case X86::BI__builtin_ia32_gather3div2di:
3635   case X86::BI__builtin_ia32_gather3div4df:
3636   case X86::BI__builtin_ia32_gather3div4di:
3637   case X86::BI__builtin_ia32_gather3div4sf:
3638   case X86::BI__builtin_ia32_gather3div4si:
3639   case X86::BI__builtin_ia32_gather3div8sf:
3640   case X86::BI__builtin_ia32_gather3div8si:
3641   case X86::BI__builtin_ia32_gather3siv2df:
3642   case X86::BI__builtin_ia32_gather3siv2di:
3643   case X86::BI__builtin_ia32_gather3siv4df:
3644   case X86::BI__builtin_ia32_gather3siv4di:
3645   case X86::BI__builtin_ia32_gather3siv4sf:
3646   case X86::BI__builtin_ia32_gather3siv4si:
3647   case X86::BI__builtin_ia32_gather3siv8sf:
3648   case X86::BI__builtin_ia32_gather3siv8si:
3649   case X86::BI__builtin_ia32_gathersiv8df:
3650   case X86::BI__builtin_ia32_gathersiv16sf:
3651   case X86::BI__builtin_ia32_gatherdiv8df:
3652   case X86::BI__builtin_ia32_gatherdiv16sf:
3653   case X86::BI__builtin_ia32_gathersiv8di:
3654   case X86::BI__builtin_ia32_gathersiv16si:
3655   case X86::BI__builtin_ia32_gatherdiv8di:
3656   case X86::BI__builtin_ia32_gatherdiv16si:
3657   case X86::BI__builtin_ia32_scatterdiv2df:
3658   case X86::BI__builtin_ia32_scatterdiv2di:
3659   case X86::BI__builtin_ia32_scatterdiv4df:
3660   case X86::BI__builtin_ia32_scatterdiv4di:
3661   case X86::BI__builtin_ia32_scatterdiv4sf:
3662   case X86::BI__builtin_ia32_scatterdiv4si:
3663   case X86::BI__builtin_ia32_scatterdiv8sf:
3664   case X86::BI__builtin_ia32_scatterdiv8si:
3665   case X86::BI__builtin_ia32_scattersiv2df:
3666   case X86::BI__builtin_ia32_scattersiv2di:
3667   case X86::BI__builtin_ia32_scattersiv4df:
3668   case X86::BI__builtin_ia32_scattersiv4di:
3669   case X86::BI__builtin_ia32_scattersiv4sf:
3670   case X86::BI__builtin_ia32_scattersiv4si:
3671   case X86::BI__builtin_ia32_scattersiv8sf:
3672   case X86::BI__builtin_ia32_scattersiv8si:
3673   case X86::BI__builtin_ia32_scattersiv8df:
3674   case X86::BI__builtin_ia32_scattersiv16sf:
3675   case X86::BI__builtin_ia32_scatterdiv8df:
3676   case X86::BI__builtin_ia32_scatterdiv16sf:
3677   case X86::BI__builtin_ia32_scattersiv8di:
3678   case X86::BI__builtin_ia32_scattersiv16si:
3679   case X86::BI__builtin_ia32_scatterdiv8di:
3680   case X86::BI__builtin_ia32_scatterdiv16si:
3681     ArgNum = 4;
3682     break;
3683   }
3684 
3685   llvm::APSInt Result;
3686 
3687   // We can't check the value of a dependent argument.
3688   Expr *Arg = TheCall->getArg(ArgNum);
3689   if (Arg->isTypeDependent() || Arg->isValueDependent())
3690     return false;
3691 
3692   // Check constant-ness first.
3693   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3694     return true;
3695 
3696   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3697     return false;
3698 
3699   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3700          << Arg->getSourceRange();
3701 }
3702 
3703 static bool isX86_32Builtin(unsigned BuiltinID) {
3704   // These builtins only work on x86-32 targets.
3705   switch (BuiltinID) {
3706   case X86::BI__builtin_ia32_readeflags_u32:
3707   case X86::BI__builtin_ia32_writeeflags_u32:
3708     return true;
3709   }
3710 
3711   return false;
3712 }
3713 
3714 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3715   if (BuiltinID == X86::BI__builtin_cpu_supports)
3716     return SemaBuiltinCpuSupports(*this, TheCall);
3717 
3718   if (BuiltinID == X86::BI__builtin_cpu_is)
3719     return SemaBuiltinCpuIs(*this, TheCall);
3720 
3721   // Check for 32-bit only builtins on a 64-bit target.
3722   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3723   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3724     return Diag(TheCall->getCallee()->getBeginLoc(),
3725                 diag::err_32_bit_builtin_64_bit_tgt);
3726 
3727   // If the intrinsic has rounding or SAE make sure its valid.
3728   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3729     return true;
3730 
3731   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3732   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3733     return true;
3734 
3735   // For intrinsics which take an immediate value as part of the instruction,
3736   // range check them here.
3737   int i = 0, l = 0, u = 0;
3738   switch (BuiltinID) {
3739   default:
3740     return false;
3741   case X86::BI__builtin_ia32_vec_ext_v2si:
3742   case X86::BI__builtin_ia32_vec_ext_v2di:
3743   case X86::BI__builtin_ia32_vextractf128_pd256:
3744   case X86::BI__builtin_ia32_vextractf128_ps256:
3745   case X86::BI__builtin_ia32_vextractf128_si256:
3746   case X86::BI__builtin_ia32_extract128i256:
3747   case X86::BI__builtin_ia32_extractf64x4_mask:
3748   case X86::BI__builtin_ia32_extracti64x4_mask:
3749   case X86::BI__builtin_ia32_extractf32x8_mask:
3750   case X86::BI__builtin_ia32_extracti32x8_mask:
3751   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3752   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3753   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3754   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3755     i = 1; l = 0; u = 1;
3756     break;
3757   case X86::BI__builtin_ia32_vec_set_v2di:
3758   case X86::BI__builtin_ia32_vinsertf128_pd256:
3759   case X86::BI__builtin_ia32_vinsertf128_ps256:
3760   case X86::BI__builtin_ia32_vinsertf128_si256:
3761   case X86::BI__builtin_ia32_insert128i256:
3762   case X86::BI__builtin_ia32_insertf32x8:
3763   case X86::BI__builtin_ia32_inserti32x8:
3764   case X86::BI__builtin_ia32_insertf64x4:
3765   case X86::BI__builtin_ia32_inserti64x4:
3766   case X86::BI__builtin_ia32_insertf64x2_256:
3767   case X86::BI__builtin_ia32_inserti64x2_256:
3768   case X86::BI__builtin_ia32_insertf32x4_256:
3769   case X86::BI__builtin_ia32_inserti32x4_256:
3770     i = 2; l = 0; u = 1;
3771     break;
3772   case X86::BI__builtin_ia32_vpermilpd:
3773   case X86::BI__builtin_ia32_vec_ext_v4hi:
3774   case X86::BI__builtin_ia32_vec_ext_v4si:
3775   case X86::BI__builtin_ia32_vec_ext_v4sf:
3776   case X86::BI__builtin_ia32_vec_ext_v4di:
3777   case X86::BI__builtin_ia32_extractf32x4_mask:
3778   case X86::BI__builtin_ia32_extracti32x4_mask:
3779   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3780   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3781     i = 1; l = 0; u = 3;
3782     break;
3783   case X86::BI_mm_prefetch:
3784   case X86::BI__builtin_ia32_vec_ext_v8hi:
3785   case X86::BI__builtin_ia32_vec_ext_v8si:
3786     i = 1; l = 0; u = 7;
3787     break;
3788   case X86::BI__builtin_ia32_sha1rnds4:
3789   case X86::BI__builtin_ia32_blendpd:
3790   case X86::BI__builtin_ia32_shufpd:
3791   case X86::BI__builtin_ia32_vec_set_v4hi:
3792   case X86::BI__builtin_ia32_vec_set_v4si:
3793   case X86::BI__builtin_ia32_vec_set_v4di:
3794   case X86::BI__builtin_ia32_shuf_f32x4_256:
3795   case X86::BI__builtin_ia32_shuf_f64x2_256:
3796   case X86::BI__builtin_ia32_shuf_i32x4_256:
3797   case X86::BI__builtin_ia32_shuf_i64x2_256:
3798   case X86::BI__builtin_ia32_insertf64x2_512:
3799   case X86::BI__builtin_ia32_inserti64x2_512:
3800   case X86::BI__builtin_ia32_insertf32x4:
3801   case X86::BI__builtin_ia32_inserti32x4:
3802     i = 2; l = 0; u = 3;
3803     break;
3804   case X86::BI__builtin_ia32_vpermil2pd:
3805   case X86::BI__builtin_ia32_vpermil2pd256:
3806   case X86::BI__builtin_ia32_vpermil2ps:
3807   case X86::BI__builtin_ia32_vpermil2ps256:
3808     i = 3; l = 0; u = 3;
3809     break;
3810   case X86::BI__builtin_ia32_cmpb128_mask:
3811   case X86::BI__builtin_ia32_cmpw128_mask:
3812   case X86::BI__builtin_ia32_cmpd128_mask:
3813   case X86::BI__builtin_ia32_cmpq128_mask:
3814   case X86::BI__builtin_ia32_cmpb256_mask:
3815   case X86::BI__builtin_ia32_cmpw256_mask:
3816   case X86::BI__builtin_ia32_cmpd256_mask:
3817   case X86::BI__builtin_ia32_cmpq256_mask:
3818   case X86::BI__builtin_ia32_cmpb512_mask:
3819   case X86::BI__builtin_ia32_cmpw512_mask:
3820   case X86::BI__builtin_ia32_cmpd512_mask:
3821   case X86::BI__builtin_ia32_cmpq512_mask:
3822   case X86::BI__builtin_ia32_ucmpb128_mask:
3823   case X86::BI__builtin_ia32_ucmpw128_mask:
3824   case X86::BI__builtin_ia32_ucmpd128_mask:
3825   case X86::BI__builtin_ia32_ucmpq128_mask:
3826   case X86::BI__builtin_ia32_ucmpb256_mask:
3827   case X86::BI__builtin_ia32_ucmpw256_mask:
3828   case X86::BI__builtin_ia32_ucmpd256_mask:
3829   case X86::BI__builtin_ia32_ucmpq256_mask:
3830   case X86::BI__builtin_ia32_ucmpb512_mask:
3831   case X86::BI__builtin_ia32_ucmpw512_mask:
3832   case X86::BI__builtin_ia32_ucmpd512_mask:
3833   case X86::BI__builtin_ia32_ucmpq512_mask:
3834   case X86::BI__builtin_ia32_vpcomub:
3835   case X86::BI__builtin_ia32_vpcomuw:
3836   case X86::BI__builtin_ia32_vpcomud:
3837   case X86::BI__builtin_ia32_vpcomuq:
3838   case X86::BI__builtin_ia32_vpcomb:
3839   case X86::BI__builtin_ia32_vpcomw:
3840   case X86::BI__builtin_ia32_vpcomd:
3841   case X86::BI__builtin_ia32_vpcomq:
3842   case X86::BI__builtin_ia32_vec_set_v8hi:
3843   case X86::BI__builtin_ia32_vec_set_v8si:
3844     i = 2; l = 0; u = 7;
3845     break;
3846   case X86::BI__builtin_ia32_vpermilpd256:
3847   case X86::BI__builtin_ia32_roundps:
3848   case X86::BI__builtin_ia32_roundpd:
3849   case X86::BI__builtin_ia32_roundps256:
3850   case X86::BI__builtin_ia32_roundpd256:
3851   case X86::BI__builtin_ia32_getmantpd128_mask:
3852   case X86::BI__builtin_ia32_getmantpd256_mask:
3853   case X86::BI__builtin_ia32_getmantps128_mask:
3854   case X86::BI__builtin_ia32_getmantps256_mask:
3855   case X86::BI__builtin_ia32_getmantpd512_mask:
3856   case X86::BI__builtin_ia32_getmantps512_mask:
3857   case X86::BI__builtin_ia32_vec_ext_v16qi:
3858   case X86::BI__builtin_ia32_vec_ext_v16hi:
3859     i = 1; l = 0; u = 15;
3860     break;
3861   case X86::BI__builtin_ia32_pblendd128:
3862   case X86::BI__builtin_ia32_blendps:
3863   case X86::BI__builtin_ia32_blendpd256:
3864   case X86::BI__builtin_ia32_shufpd256:
3865   case X86::BI__builtin_ia32_roundss:
3866   case X86::BI__builtin_ia32_roundsd:
3867   case X86::BI__builtin_ia32_rangepd128_mask:
3868   case X86::BI__builtin_ia32_rangepd256_mask:
3869   case X86::BI__builtin_ia32_rangepd512_mask:
3870   case X86::BI__builtin_ia32_rangeps128_mask:
3871   case X86::BI__builtin_ia32_rangeps256_mask:
3872   case X86::BI__builtin_ia32_rangeps512_mask:
3873   case X86::BI__builtin_ia32_getmantsd_round_mask:
3874   case X86::BI__builtin_ia32_getmantss_round_mask:
3875   case X86::BI__builtin_ia32_vec_set_v16qi:
3876   case X86::BI__builtin_ia32_vec_set_v16hi:
3877     i = 2; l = 0; u = 15;
3878     break;
3879   case X86::BI__builtin_ia32_vec_ext_v32qi:
3880     i = 1; l = 0; u = 31;
3881     break;
3882   case X86::BI__builtin_ia32_cmpps:
3883   case X86::BI__builtin_ia32_cmpss:
3884   case X86::BI__builtin_ia32_cmppd:
3885   case X86::BI__builtin_ia32_cmpsd:
3886   case X86::BI__builtin_ia32_cmpps256:
3887   case X86::BI__builtin_ia32_cmppd256:
3888   case X86::BI__builtin_ia32_cmpps128_mask:
3889   case X86::BI__builtin_ia32_cmppd128_mask:
3890   case X86::BI__builtin_ia32_cmpps256_mask:
3891   case X86::BI__builtin_ia32_cmppd256_mask:
3892   case X86::BI__builtin_ia32_cmpps512_mask:
3893   case X86::BI__builtin_ia32_cmppd512_mask:
3894   case X86::BI__builtin_ia32_cmpsd_mask:
3895   case X86::BI__builtin_ia32_cmpss_mask:
3896   case X86::BI__builtin_ia32_vec_set_v32qi:
3897     i = 2; l = 0; u = 31;
3898     break;
3899   case X86::BI__builtin_ia32_permdf256:
3900   case X86::BI__builtin_ia32_permdi256:
3901   case X86::BI__builtin_ia32_permdf512:
3902   case X86::BI__builtin_ia32_permdi512:
3903   case X86::BI__builtin_ia32_vpermilps:
3904   case X86::BI__builtin_ia32_vpermilps256:
3905   case X86::BI__builtin_ia32_vpermilpd512:
3906   case X86::BI__builtin_ia32_vpermilps512:
3907   case X86::BI__builtin_ia32_pshufd:
3908   case X86::BI__builtin_ia32_pshufd256:
3909   case X86::BI__builtin_ia32_pshufd512:
3910   case X86::BI__builtin_ia32_pshufhw:
3911   case X86::BI__builtin_ia32_pshufhw256:
3912   case X86::BI__builtin_ia32_pshufhw512:
3913   case X86::BI__builtin_ia32_pshuflw:
3914   case X86::BI__builtin_ia32_pshuflw256:
3915   case X86::BI__builtin_ia32_pshuflw512:
3916   case X86::BI__builtin_ia32_vcvtps2ph:
3917   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3918   case X86::BI__builtin_ia32_vcvtps2ph256:
3919   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3920   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3921   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3922   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3923   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3924   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3925   case X86::BI__builtin_ia32_rndscaleps_mask:
3926   case X86::BI__builtin_ia32_rndscalepd_mask:
3927   case X86::BI__builtin_ia32_reducepd128_mask:
3928   case X86::BI__builtin_ia32_reducepd256_mask:
3929   case X86::BI__builtin_ia32_reducepd512_mask:
3930   case X86::BI__builtin_ia32_reduceps128_mask:
3931   case X86::BI__builtin_ia32_reduceps256_mask:
3932   case X86::BI__builtin_ia32_reduceps512_mask:
3933   case X86::BI__builtin_ia32_prold512:
3934   case X86::BI__builtin_ia32_prolq512:
3935   case X86::BI__builtin_ia32_prold128:
3936   case X86::BI__builtin_ia32_prold256:
3937   case X86::BI__builtin_ia32_prolq128:
3938   case X86::BI__builtin_ia32_prolq256:
3939   case X86::BI__builtin_ia32_prord512:
3940   case X86::BI__builtin_ia32_prorq512:
3941   case X86::BI__builtin_ia32_prord128:
3942   case X86::BI__builtin_ia32_prord256:
3943   case X86::BI__builtin_ia32_prorq128:
3944   case X86::BI__builtin_ia32_prorq256:
3945   case X86::BI__builtin_ia32_fpclasspd128_mask:
3946   case X86::BI__builtin_ia32_fpclasspd256_mask:
3947   case X86::BI__builtin_ia32_fpclassps128_mask:
3948   case X86::BI__builtin_ia32_fpclassps256_mask:
3949   case X86::BI__builtin_ia32_fpclassps512_mask:
3950   case X86::BI__builtin_ia32_fpclasspd512_mask:
3951   case X86::BI__builtin_ia32_fpclasssd_mask:
3952   case X86::BI__builtin_ia32_fpclassss_mask:
3953   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3954   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3955   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3956   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3957   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3958   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3959   case X86::BI__builtin_ia32_kshiftliqi:
3960   case X86::BI__builtin_ia32_kshiftlihi:
3961   case X86::BI__builtin_ia32_kshiftlisi:
3962   case X86::BI__builtin_ia32_kshiftlidi:
3963   case X86::BI__builtin_ia32_kshiftriqi:
3964   case X86::BI__builtin_ia32_kshiftrihi:
3965   case X86::BI__builtin_ia32_kshiftrisi:
3966   case X86::BI__builtin_ia32_kshiftridi:
3967     i = 1; l = 0; u = 255;
3968     break;
3969   case X86::BI__builtin_ia32_vperm2f128_pd256:
3970   case X86::BI__builtin_ia32_vperm2f128_ps256:
3971   case X86::BI__builtin_ia32_vperm2f128_si256:
3972   case X86::BI__builtin_ia32_permti256:
3973   case X86::BI__builtin_ia32_pblendw128:
3974   case X86::BI__builtin_ia32_pblendw256:
3975   case X86::BI__builtin_ia32_blendps256:
3976   case X86::BI__builtin_ia32_pblendd256:
3977   case X86::BI__builtin_ia32_palignr128:
3978   case X86::BI__builtin_ia32_palignr256:
3979   case X86::BI__builtin_ia32_palignr512:
3980   case X86::BI__builtin_ia32_alignq512:
3981   case X86::BI__builtin_ia32_alignd512:
3982   case X86::BI__builtin_ia32_alignd128:
3983   case X86::BI__builtin_ia32_alignd256:
3984   case X86::BI__builtin_ia32_alignq128:
3985   case X86::BI__builtin_ia32_alignq256:
3986   case X86::BI__builtin_ia32_vcomisd:
3987   case X86::BI__builtin_ia32_vcomiss:
3988   case X86::BI__builtin_ia32_shuf_f32x4:
3989   case X86::BI__builtin_ia32_shuf_f64x2:
3990   case X86::BI__builtin_ia32_shuf_i32x4:
3991   case X86::BI__builtin_ia32_shuf_i64x2:
3992   case X86::BI__builtin_ia32_shufpd512:
3993   case X86::BI__builtin_ia32_shufps:
3994   case X86::BI__builtin_ia32_shufps256:
3995   case X86::BI__builtin_ia32_shufps512:
3996   case X86::BI__builtin_ia32_dbpsadbw128:
3997   case X86::BI__builtin_ia32_dbpsadbw256:
3998   case X86::BI__builtin_ia32_dbpsadbw512:
3999   case X86::BI__builtin_ia32_vpshldd128:
4000   case X86::BI__builtin_ia32_vpshldd256:
4001   case X86::BI__builtin_ia32_vpshldd512:
4002   case X86::BI__builtin_ia32_vpshldq128:
4003   case X86::BI__builtin_ia32_vpshldq256:
4004   case X86::BI__builtin_ia32_vpshldq512:
4005   case X86::BI__builtin_ia32_vpshldw128:
4006   case X86::BI__builtin_ia32_vpshldw256:
4007   case X86::BI__builtin_ia32_vpshldw512:
4008   case X86::BI__builtin_ia32_vpshrdd128:
4009   case X86::BI__builtin_ia32_vpshrdd256:
4010   case X86::BI__builtin_ia32_vpshrdd512:
4011   case X86::BI__builtin_ia32_vpshrdq128:
4012   case X86::BI__builtin_ia32_vpshrdq256:
4013   case X86::BI__builtin_ia32_vpshrdq512:
4014   case X86::BI__builtin_ia32_vpshrdw128:
4015   case X86::BI__builtin_ia32_vpshrdw256:
4016   case X86::BI__builtin_ia32_vpshrdw512:
4017     i = 2; l = 0; u = 255;
4018     break;
4019   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4020   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4021   case X86::BI__builtin_ia32_fixupimmps512_mask:
4022   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4023   case X86::BI__builtin_ia32_fixupimmsd_mask:
4024   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4025   case X86::BI__builtin_ia32_fixupimmss_mask:
4026   case X86::BI__builtin_ia32_fixupimmss_maskz:
4027   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4028   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4029   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4030   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4031   case X86::BI__builtin_ia32_fixupimmps128_mask:
4032   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4033   case X86::BI__builtin_ia32_fixupimmps256_mask:
4034   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4035   case X86::BI__builtin_ia32_pternlogd512_mask:
4036   case X86::BI__builtin_ia32_pternlogd512_maskz:
4037   case X86::BI__builtin_ia32_pternlogq512_mask:
4038   case X86::BI__builtin_ia32_pternlogq512_maskz:
4039   case X86::BI__builtin_ia32_pternlogd128_mask:
4040   case X86::BI__builtin_ia32_pternlogd128_maskz:
4041   case X86::BI__builtin_ia32_pternlogd256_mask:
4042   case X86::BI__builtin_ia32_pternlogd256_maskz:
4043   case X86::BI__builtin_ia32_pternlogq128_mask:
4044   case X86::BI__builtin_ia32_pternlogq128_maskz:
4045   case X86::BI__builtin_ia32_pternlogq256_mask:
4046   case X86::BI__builtin_ia32_pternlogq256_maskz:
4047     i = 3; l = 0; u = 255;
4048     break;
4049   case X86::BI__builtin_ia32_gatherpfdpd:
4050   case X86::BI__builtin_ia32_gatherpfdps:
4051   case X86::BI__builtin_ia32_gatherpfqpd:
4052   case X86::BI__builtin_ia32_gatherpfqps:
4053   case X86::BI__builtin_ia32_scatterpfdpd:
4054   case X86::BI__builtin_ia32_scatterpfdps:
4055   case X86::BI__builtin_ia32_scatterpfqpd:
4056   case X86::BI__builtin_ia32_scatterpfqps:
4057     i = 4; l = 2; u = 3;
4058     break;
4059   case X86::BI__builtin_ia32_reducesd_mask:
4060   case X86::BI__builtin_ia32_reducess_mask:
4061   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4062   case X86::BI__builtin_ia32_rndscaless_round_mask:
4063     i = 4; l = 0; u = 255;
4064     break;
4065   }
4066 
4067   // Note that we don't force a hard error on the range check here, allowing
4068   // template-generated or macro-generated dead code to potentially have out-of-
4069   // range values. These need to code generate, but don't need to necessarily
4070   // make any sense. We use a warning that defaults to an error.
4071   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4072 }
4073 
4074 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4075 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4076 /// Returns true when the format fits the function and the FormatStringInfo has
4077 /// been populated.
4078 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4079                                FormatStringInfo *FSI) {
4080   FSI->HasVAListArg = Format->getFirstArg() == 0;
4081   FSI->FormatIdx = Format->getFormatIdx() - 1;
4082   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4083 
4084   // The way the format attribute works in GCC, the implicit this argument
4085   // of member functions is counted. However, it doesn't appear in our own
4086   // lists, so decrement format_idx in that case.
4087   if (IsCXXMember) {
4088     if(FSI->FormatIdx == 0)
4089       return false;
4090     --FSI->FormatIdx;
4091     if (FSI->FirstDataArg != 0)
4092       --FSI->FirstDataArg;
4093   }
4094   return true;
4095 }
4096 
4097 /// Checks if a the given expression evaluates to null.
4098 ///
4099 /// Returns true if the value evaluates to null.
4100 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4101   // If the expression has non-null type, it doesn't evaluate to null.
4102   if (auto nullability
4103         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4104     if (*nullability == NullabilityKind::NonNull)
4105       return false;
4106   }
4107 
4108   // As a special case, transparent unions initialized with zero are
4109   // considered null for the purposes of the nonnull attribute.
4110   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4111     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4112       if (const CompoundLiteralExpr *CLE =
4113           dyn_cast<CompoundLiteralExpr>(Expr))
4114         if (const InitListExpr *ILE =
4115             dyn_cast<InitListExpr>(CLE->getInitializer()))
4116           Expr = ILE->getInit(0);
4117   }
4118 
4119   bool Result;
4120   return (!Expr->isValueDependent() &&
4121           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4122           !Result);
4123 }
4124 
4125 static void CheckNonNullArgument(Sema &S,
4126                                  const Expr *ArgExpr,
4127                                  SourceLocation CallSiteLoc) {
4128   if (CheckNonNullExpr(S, ArgExpr))
4129     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4130                           S.PDiag(diag::warn_null_arg)
4131                               << ArgExpr->getSourceRange());
4132 }
4133 
4134 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4135   FormatStringInfo FSI;
4136   if ((GetFormatStringType(Format) == FST_NSString) &&
4137       getFormatStringInfo(Format, false, &FSI)) {
4138     Idx = FSI.FormatIdx;
4139     return true;
4140   }
4141   return false;
4142 }
4143 
4144 /// Diagnose use of %s directive in an NSString which is being passed
4145 /// as formatting string to formatting method.
4146 static void
4147 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4148                                         const NamedDecl *FDecl,
4149                                         Expr **Args,
4150                                         unsigned NumArgs) {
4151   unsigned Idx = 0;
4152   bool Format = false;
4153   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4154   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4155     Idx = 2;
4156     Format = true;
4157   }
4158   else
4159     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4160       if (S.GetFormatNSStringIdx(I, Idx)) {
4161         Format = true;
4162         break;
4163       }
4164     }
4165   if (!Format || NumArgs <= Idx)
4166     return;
4167   const Expr *FormatExpr = Args[Idx];
4168   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4169     FormatExpr = CSCE->getSubExpr();
4170   const StringLiteral *FormatString;
4171   if (const ObjCStringLiteral *OSL =
4172       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4173     FormatString = OSL->getString();
4174   else
4175     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4176   if (!FormatString)
4177     return;
4178   if (S.FormatStringHasSArg(FormatString)) {
4179     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4180       << "%s" << 1 << 1;
4181     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4182       << FDecl->getDeclName();
4183   }
4184 }
4185 
4186 /// Determine whether the given type has a non-null nullability annotation.
4187 static bool isNonNullType(ASTContext &ctx, QualType type) {
4188   if (auto nullability = type->getNullability(ctx))
4189     return *nullability == NullabilityKind::NonNull;
4190 
4191   return false;
4192 }
4193 
4194 static void CheckNonNullArguments(Sema &S,
4195                                   const NamedDecl *FDecl,
4196                                   const FunctionProtoType *Proto,
4197                                   ArrayRef<const Expr *> Args,
4198                                   SourceLocation CallSiteLoc) {
4199   assert((FDecl || Proto) && "Need a function declaration or prototype");
4200 
4201   // Already checked by by constant evaluator.
4202   if (S.isConstantEvaluated())
4203     return;
4204   // Check the attributes attached to the method/function itself.
4205   llvm::SmallBitVector NonNullArgs;
4206   if (FDecl) {
4207     // Handle the nonnull attribute on the function/method declaration itself.
4208     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4209       if (!NonNull->args_size()) {
4210         // Easy case: all pointer arguments are nonnull.
4211         for (const auto *Arg : Args)
4212           if (S.isValidPointerAttrType(Arg->getType()))
4213             CheckNonNullArgument(S, Arg, CallSiteLoc);
4214         return;
4215       }
4216 
4217       for (const ParamIdx &Idx : NonNull->args()) {
4218         unsigned IdxAST = Idx.getASTIndex();
4219         if (IdxAST >= Args.size())
4220           continue;
4221         if (NonNullArgs.empty())
4222           NonNullArgs.resize(Args.size());
4223         NonNullArgs.set(IdxAST);
4224       }
4225     }
4226   }
4227 
4228   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4229     // Handle the nonnull attribute on the parameters of the
4230     // function/method.
4231     ArrayRef<ParmVarDecl*> parms;
4232     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4233       parms = FD->parameters();
4234     else
4235       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4236 
4237     unsigned ParamIndex = 0;
4238     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4239          I != E; ++I, ++ParamIndex) {
4240       const ParmVarDecl *PVD = *I;
4241       if (PVD->hasAttr<NonNullAttr>() ||
4242           isNonNullType(S.Context, PVD->getType())) {
4243         if (NonNullArgs.empty())
4244           NonNullArgs.resize(Args.size());
4245 
4246         NonNullArgs.set(ParamIndex);
4247       }
4248     }
4249   } else {
4250     // If we have a non-function, non-method declaration but no
4251     // function prototype, try to dig out the function prototype.
4252     if (!Proto) {
4253       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4254         QualType type = VD->getType().getNonReferenceType();
4255         if (auto pointerType = type->getAs<PointerType>())
4256           type = pointerType->getPointeeType();
4257         else if (auto blockType = type->getAs<BlockPointerType>())
4258           type = blockType->getPointeeType();
4259         // FIXME: data member pointers?
4260 
4261         // Dig out the function prototype, if there is one.
4262         Proto = type->getAs<FunctionProtoType>();
4263       }
4264     }
4265 
4266     // Fill in non-null argument information from the nullability
4267     // information on the parameter types (if we have them).
4268     if (Proto) {
4269       unsigned Index = 0;
4270       for (auto paramType : Proto->getParamTypes()) {
4271         if (isNonNullType(S.Context, paramType)) {
4272           if (NonNullArgs.empty())
4273             NonNullArgs.resize(Args.size());
4274 
4275           NonNullArgs.set(Index);
4276         }
4277 
4278         ++Index;
4279       }
4280     }
4281   }
4282 
4283   // Check for non-null arguments.
4284   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4285        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4286     if (NonNullArgs[ArgIndex])
4287       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4288   }
4289 }
4290 
4291 /// Handles the checks for format strings, non-POD arguments to vararg
4292 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4293 /// attributes.
4294 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4295                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4296                      bool IsMemberFunction, SourceLocation Loc,
4297                      SourceRange Range, VariadicCallType CallType) {
4298   // FIXME: We should check as much as we can in the template definition.
4299   if (CurContext->isDependentContext())
4300     return;
4301 
4302   // Printf and scanf checking.
4303   llvm::SmallBitVector CheckedVarArgs;
4304   if (FDecl) {
4305     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4306       // Only create vector if there are format attributes.
4307       CheckedVarArgs.resize(Args.size());
4308 
4309       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4310                            CheckedVarArgs);
4311     }
4312   }
4313 
4314   // Refuse POD arguments that weren't caught by the format string
4315   // checks above.
4316   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4317   if (CallType != VariadicDoesNotApply &&
4318       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4319     unsigned NumParams = Proto ? Proto->getNumParams()
4320                        : FDecl && isa<FunctionDecl>(FDecl)
4321                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4322                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4323                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4324                        : 0;
4325 
4326     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4327       // Args[ArgIdx] can be null in malformed code.
4328       if (const Expr *Arg = Args[ArgIdx]) {
4329         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4330           checkVariadicArgument(Arg, CallType);
4331       }
4332     }
4333   }
4334 
4335   if (FDecl || Proto) {
4336     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4337 
4338     // Type safety checking.
4339     if (FDecl) {
4340       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4341         CheckArgumentWithTypeTag(I, Args, Loc);
4342     }
4343   }
4344 
4345   if (FD)
4346     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4347 }
4348 
4349 /// CheckConstructorCall - Check a constructor call for correctness and safety
4350 /// properties not enforced by the C type system.
4351 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4352                                 ArrayRef<const Expr *> Args,
4353                                 const FunctionProtoType *Proto,
4354                                 SourceLocation Loc) {
4355   VariadicCallType CallType =
4356     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4357   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4358             Loc, SourceRange(), CallType);
4359 }
4360 
4361 /// CheckFunctionCall - Check a direct function call for various correctness
4362 /// and safety properties not strictly enforced by the C type system.
4363 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4364                              const FunctionProtoType *Proto) {
4365   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4366                               isa<CXXMethodDecl>(FDecl);
4367   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4368                           IsMemberOperatorCall;
4369   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4370                                                   TheCall->getCallee());
4371   Expr** Args = TheCall->getArgs();
4372   unsigned NumArgs = TheCall->getNumArgs();
4373 
4374   Expr *ImplicitThis = nullptr;
4375   if (IsMemberOperatorCall) {
4376     // If this is a call to a member operator, hide the first argument
4377     // from checkCall.
4378     // FIXME: Our choice of AST representation here is less than ideal.
4379     ImplicitThis = Args[0];
4380     ++Args;
4381     --NumArgs;
4382   } else if (IsMemberFunction)
4383     ImplicitThis =
4384         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4385 
4386   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4387             IsMemberFunction, TheCall->getRParenLoc(),
4388             TheCall->getCallee()->getSourceRange(), CallType);
4389 
4390   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4391   // None of the checks below are needed for functions that don't have
4392   // simple names (e.g., C++ conversion functions).
4393   if (!FnInfo)
4394     return false;
4395 
4396   CheckAbsoluteValueFunction(TheCall, FDecl);
4397   CheckMaxUnsignedZero(TheCall, FDecl);
4398 
4399   if (getLangOpts().ObjC)
4400     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4401 
4402   unsigned CMId = FDecl->getMemoryFunctionKind();
4403   if (CMId == 0)
4404     return false;
4405 
4406   // Handle memory setting and copying functions.
4407   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4408     CheckStrlcpycatArguments(TheCall, FnInfo);
4409   else if (CMId == Builtin::BIstrncat)
4410     CheckStrncatArguments(TheCall, FnInfo);
4411   else
4412     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4413 
4414   return false;
4415 }
4416 
4417 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4418                                ArrayRef<const Expr *> Args) {
4419   VariadicCallType CallType =
4420       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4421 
4422   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4423             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4424             CallType);
4425 
4426   return false;
4427 }
4428 
4429 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4430                             const FunctionProtoType *Proto) {
4431   QualType Ty;
4432   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4433     Ty = V->getType().getNonReferenceType();
4434   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4435     Ty = F->getType().getNonReferenceType();
4436   else
4437     return false;
4438 
4439   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4440       !Ty->isFunctionProtoType())
4441     return false;
4442 
4443   VariadicCallType CallType;
4444   if (!Proto || !Proto->isVariadic()) {
4445     CallType = VariadicDoesNotApply;
4446   } else if (Ty->isBlockPointerType()) {
4447     CallType = VariadicBlock;
4448   } else { // Ty->isFunctionPointerType()
4449     CallType = VariadicFunction;
4450   }
4451 
4452   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4453             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4454             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4455             TheCall->getCallee()->getSourceRange(), CallType);
4456 
4457   return false;
4458 }
4459 
4460 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4461 /// such as function pointers returned from functions.
4462 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4463   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4464                                                   TheCall->getCallee());
4465   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4466             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4467             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4468             TheCall->getCallee()->getSourceRange(), CallType);
4469 
4470   return false;
4471 }
4472 
4473 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4474   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4475     return false;
4476 
4477   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4478   switch (Op) {
4479   case AtomicExpr::AO__c11_atomic_init:
4480   case AtomicExpr::AO__opencl_atomic_init:
4481     llvm_unreachable("There is no ordering argument for an init");
4482 
4483   case AtomicExpr::AO__c11_atomic_load:
4484   case AtomicExpr::AO__opencl_atomic_load:
4485   case AtomicExpr::AO__atomic_load_n:
4486   case AtomicExpr::AO__atomic_load:
4487     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4488            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4489 
4490   case AtomicExpr::AO__c11_atomic_store:
4491   case AtomicExpr::AO__opencl_atomic_store:
4492   case AtomicExpr::AO__atomic_store:
4493   case AtomicExpr::AO__atomic_store_n:
4494     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4495            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4496            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4497 
4498   default:
4499     return true;
4500   }
4501 }
4502 
4503 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4504                                          AtomicExpr::AtomicOp Op) {
4505   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4506   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4507   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4508   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4509                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4510                          Op);
4511 }
4512 
4513 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4514                                  SourceLocation RParenLoc, MultiExprArg Args,
4515                                  AtomicExpr::AtomicOp Op,
4516                                  AtomicArgumentOrder ArgOrder) {
4517   // All the non-OpenCL operations take one of the following forms.
4518   // The OpenCL operations take the __c11 forms with one extra argument for
4519   // synchronization scope.
4520   enum {
4521     // C    __c11_atomic_init(A *, C)
4522     Init,
4523 
4524     // C    __c11_atomic_load(A *, int)
4525     Load,
4526 
4527     // void __atomic_load(A *, CP, int)
4528     LoadCopy,
4529 
4530     // void __atomic_store(A *, CP, int)
4531     Copy,
4532 
4533     // C    __c11_atomic_add(A *, M, int)
4534     Arithmetic,
4535 
4536     // C    __atomic_exchange_n(A *, CP, int)
4537     Xchg,
4538 
4539     // void __atomic_exchange(A *, C *, CP, int)
4540     GNUXchg,
4541 
4542     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4543     C11CmpXchg,
4544 
4545     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4546     GNUCmpXchg
4547   } Form = Init;
4548 
4549   const unsigned NumForm = GNUCmpXchg + 1;
4550   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4551   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4552   // where:
4553   //   C is an appropriate type,
4554   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4555   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4556   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4557   //   the int parameters are for orderings.
4558 
4559   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4560       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4561       "need to update code for modified forms");
4562   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4563                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4564                         AtomicExpr::AO__atomic_load,
4565                 "need to update code for modified C11 atomics");
4566   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4567                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4568   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4569                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4570                IsOpenCL;
4571   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4572              Op == AtomicExpr::AO__atomic_store_n ||
4573              Op == AtomicExpr::AO__atomic_exchange_n ||
4574              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4575   bool IsAddSub = false;
4576   bool IsMinMax = false;
4577 
4578   switch (Op) {
4579   case AtomicExpr::AO__c11_atomic_init:
4580   case AtomicExpr::AO__opencl_atomic_init:
4581     Form = Init;
4582     break;
4583 
4584   case AtomicExpr::AO__c11_atomic_load:
4585   case AtomicExpr::AO__opencl_atomic_load:
4586   case AtomicExpr::AO__atomic_load_n:
4587     Form = Load;
4588     break;
4589 
4590   case AtomicExpr::AO__atomic_load:
4591     Form = LoadCopy;
4592     break;
4593 
4594   case AtomicExpr::AO__c11_atomic_store:
4595   case AtomicExpr::AO__opencl_atomic_store:
4596   case AtomicExpr::AO__atomic_store:
4597   case AtomicExpr::AO__atomic_store_n:
4598     Form = Copy;
4599     break;
4600 
4601   case AtomicExpr::AO__c11_atomic_fetch_add:
4602   case AtomicExpr::AO__c11_atomic_fetch_sub:
4603   case AtomicExpr::AO__opencl_atomic_fetch_add:
4604   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4605   case AtomicExpr::AO__opencl_atomic_fetch_min:
4606   case AtomicExpr::AO__opencl_atomic_fetch_max:
4607   case AtomicExpr::AO__atomic_fetch_add:
4608   case AtomicExpr::AO__atomic_fetch_sub:
4609   case AtomicExpr::AO__atomic_add_fetch:
4610   case AtomicExpr::AO__atomic_sub_fetch:
4611     IsAddSub = true;
4612     LLVM_FALLTHROUGH;
4613   case AtomicExpr::AO__c11_atomic_fetch_and:
4614   case AtomicExpr::AO__c11_atomic_fetch_or:
4615   case AtomicExpr::AO__c11_atomic_fetch_xor:
4616   case AtomicExpr::AO__opencl_atomic_fetch_and:
4617   case AtomicExpr::AO__opencl_atomic_fetch_or:
4618   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4619   case AtomicExpr::AO__atomic_fetch_and:
4620   case AtomicExpr::AO__atomic_fetch_or:
4621   case AtomicExpr::AO__atomic_fetch_xor:
4622   case AtomicExpr::AO__atomic_fetch_nand:
4623   case AtomicExpr::AO__atomic_and_fetch:
4624   case AtomicExpr::AO__atomic_or_fetch:
4625   case AtomicExpr::AO__atomic_xor_fetch:
4626   case AtomicExpr::AO__atomic_nand_fetch:
4627     Form = Arithmetic;
4628     break;
4629 
4630   case AtomicExpr::AO__atomic_fetch_min:
4631   case AtomicExpr::AO__atomic_fetch_max:
4632     IsMinMax = true;
4633     Form = Arithmetic;
4634     break;
4635 
4636   case AtomicExpr::AO__c11_atomic_exchange:
4637   case AtomicExpr::AO__opencl_atomic_exchange:
4638   case AtomicExpr::AO__atomic_exchange_n:
4639     Form = Xchg;
4640     break;
4641 
4642   case AtomicExpr::AO__atomic_exchange:
4643     Form = GNUXchg;
4644     break;
4645 
4646   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4647   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4648   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4649   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4650     Form = C11CmpXchg;
4651     break;
4652 
4653   case AtomicExpr::AO__atomic_compare_exchange:
4654   case AtomicExpr::AO__atomic_compare_exchange_n:
4655     Form = GNUCmpXchg;
4656     break;
4657   }
4658 
4659   unsigned AdjustedNumArgs = NumArgs[Form];
4660   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4661     ++AdjustedNumArgs;
4662   // Check we have the right number of arguments.
4663   if (Args.size() < AdjustedNumArgs) {
4664     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4665         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4666         << ExprRange;
4667     return ExprError();
4668   } else if (Args.size() > AdjustedNumArgs) {
4669     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4670          diag::err_typecheck_call_too_many_args)
4671         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4672         << ExprRange;
4673     return ExprError();
4674   }
4675 
4676   // Inspect the first argument of the atomic operation.
4677   Expr *Ptr = Args[0];
4678   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4679   if (ConvertedPtr.isInvalid())
4680     return ExprError();
4681 
4682   Ptr = ConvertedPtr.get();
4683   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4684   if (!pointerType) {
4685     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4686         << Ptr->getType() << Ptr->getSourceRange();
4687     return ExprError();
4688   }
4689 
4690   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4691   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4692   QualType ValType = AtomTy; // 'C'
4693   if (IsC11) {
4694     if (!AtomTy->isAtomicType()) {
4695       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4696           << Ptr->getType() << Ptr->getSourceRange();
4697       return ExprError();
4698     }
4699     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4700         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4701       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4702           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4703           << Ptr->getSourceRange();
4704       return ExprError();
4705     }
4706     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4707   } else if (Form != Load && Form != LoadCopy) {
4708     if (ValType.isConstQualified()) {
4709       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4710           << Ptr->getType() << Ptr->getSourceRange();
4711       return ExprError();
4712     }
4713   }
4714 
4715   // For an arithmetic operation, the implied arithmetic must be well-formed.
4716   if (Form == Arithmetic) {
4717     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4718     if (IsAddSub && !ValType->isIntegerType()
4719         && !ValType->isPointerType()) {
4720       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4721           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4722       return ExprError();
4723     }
4724     if (IsMinMax) {
4725       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4726       if (!BT || (BT->getKind() != BuiltinType::Int &&
4727                   BT->getKind() != BuiltinType::UInt)) {
4728         Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_int32_or_ptr);
4729         return ExprError();
4730       }
4731     }
4732     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4733       Diag(ExprRange.getBegin(), diag::err_atomic_op_bitwise_needs_atomic_int)
4734           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4735       return ExprError();
4736     }
4737     if (IsC11 && ValType->isPointerType() &&
4738         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4739                             diag::err_incomplete_type)) {
4740       return ExprError();
4741     }
4742   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4743     // For __atomic_*_n operations, the value type must be a scalar integral or
4744     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4745     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4746         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4747     return ExprError();
4748   }
4749 
4750   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4751       !AtomTy->isScalarType()) {
4752     // For GNU atomics, require a trivially-copyable type. This is not part of
4753     // the GNU atomics specification, but we enforce it for sanity.
4754     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4755         << Ptr->getType() << Ptr->getSourceRange();
4756     return ExprError();
4757   }
4758 
4759   switch (ValType.getObjCLifetime()) {
4760   case Qualifiers::OCL_None:
4761   case Qualifiers::OCL_ExplicitNone:
4762     // okay
4763     break;
4764 
4765   case Qualifiers::OCL_Weak:
4766   case Qualifiers::OCL_Strong:
4767   case Qualifiers::OCL_Autoreleasing:
4768     // FIXME: Can this happen? By this point, ValType should be known
4769     // to be trivially copyable.
4770     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4771         << ValType << Ptr->getSourceRange();
4772     return ExprError();
4773   }
4774 
4775   // All atomic operations have an overload which takes a pointer to a volatile
4776   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4777   // into the result or the other operands. Similarly atomic_load takes a
4778   // pointer to a const 'A'.
4779   ValType.removeLocalVolatile();
4780   ValType.removeLocalConst();
4781   QualType ResultType = ValType;
4782   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4783       Form == Init)
4784     ResultType = Context.VoidTy;
4785   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4786     ResultType = Context.BoolTy;
4787 
4788   // The type of a parameter passed 'by value'. In the GNU atomics, such
4789   // arguments are actually passed as pointers.
4790   QualType ByValType = ValType; // 'CP'
4791   bool IsPassedByAddress = false;
4792   if (!IsC11 && !IsN) {
4793     ByValType = Ptr->getType();
4794     IsPassedByAddress = true;
4795   }
4796 
4797   SmallVector<Expr *, 5> APIOrderedArgs;
4798   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4799     APIOrderedArgs.push_back(Args[0]);
4800     switch (Form) {
4801     case Init:
4802     case Load:
4803       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4804       break;
4805     case LoadCopy:
4806     case Copy:
4807     case Arithmetic:
4808     case Xchg:
4809       APIOrderedArgs.push_back(Args[2]); // Val1
4810       APIOrderedArgs.push_back(Args[1]); // Order
4811       break;
4812     case GNUXchg:
4813       APIOrderedArgs.push_back(Args[2]); // Val1
4814       APIOrderedArgs.push_back(Args[3]); // Val2
4815       APIOrderedArgs.push_back(Args[1]); // Order
4816       break;
4817     case C11CmpXchg:
4818       APIOrderedArgs.push_back(Args[2]); // Val1
4819       APIOrderedArgs.push_back(Args[4]); // Val2
4820       APIOrderedArgs.push_back(Args[1]); // Order
4821       APIOrderedArgs.push_back(Args[3]); // OrderFail
4822       break;
4823     case GNUCmpXchg:
4824       APIOrderedArgs.push_back(Args[2]); // Val1
4825       APIOrderedArgs.push_back(Args[4]); // Val2
4826       APIOrderedArgs.push_back(Args[5]); // Weak
4827       APIOrderedArgs.push_back(Args[1]); // Order
4828       APIOrderedArgs.push_back(Args[3]); // OrderFail
4829       break;
4830     }
4831   } else
4832     APIOrderedArgs.append(Args.begin(), Args.end());
4833 
4834   // The first argument's non-CV pointer type is used to deduce the type of
4835   // subsequent arguments, except for:
4836   //  - weak flag (always converted to bool)
4837   //  - memory order (always converted to int)
4838   //  - scope  (always converted to int)
4839   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4840     QualType Ty;
4841     if (i < NumVals[Form] + 1) {
4842       switch (i) {
4843       case 0:
4844         // The first argument is always a pointer. It has a fixed type.
4845         // It is always dereferenced, a nullptr is undefined.
4846         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4847         // Nothing else to do: we already know all we want about this pointer.
4848         continue;
4849       case 1:
4850         // The second argument is the non-atomic operand. For arithmetic, this
4851         // is always passed by value, and for a compare_exchange it is always
4852         // passed by address. For the rest, GNU uses by-address and C11 uses
4853         // by-value.
4854         assert(Form != Load);
4855         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4856           Ty = ValType;
4857         else if (Form == Copy || Form == Xchg) {
4858           if (IsPassedByAddress) {
4859             // The value pointer is always dereferenced, a nullptr is undefined.
4860             CheckNonNullArgument(*this, APIOrderedArgs[i],
4861                                  ExprRange.getBegin());
4862           }
4863           Ty = ByValType;
4864         } else if (Form == Arithmetic)
4865           Ty = Context.getPointerDiffType();
4866         else {
4867           Expr *ValArg = APIOrderedArgs[i];
4868           // The value pointer is always dereferenced, a nullptr is undefined.
4869           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4870           LangAS AS = LangAS::Default;
4871           // Keep address space of non-atomic pointer type.
4872           if (const PointerType *PtrTy =
4873                   ValArg->getType()->getAs<PointerType>()) {
4874             AS = PtrTy->getPointeeType().getAddressSpace();
4875           }
4876           Ty = Context.getPointerType(
4877               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4878         }
4879         break;
4880       case 2:
4881         // The third argument to compare_exchange / GNU exchange is the desired
4882         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4883         if (IsPassedByAddress)
4884           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4885         Ty = ByValType;
4886         break;
4887       case 3:
4888         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4889         Ty = Context.BoolTy;
4890         break;
4891       }
4892     } else {
4893       // The order(s) and scope are always converted to int.
4894       Ty = Context.IntTy;
4895     }
4896 
4897     InitializedEntity Entity =
4898         InitializedEntity::InitializeParameter(Context, Ty, false);
4899     ExprResult Arg = APIOrderedArgs[i];
4900     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4901     if (Arg.isInvalid())
4902       return true;
4903     APIOrderedArgs[i] = Arg.get();
4904   }
4905 
4906   // Permute the arguments into a 'consistent' order.
4907   SmallVector<Expr*, 5> SubExprs;
4908   SubExprs.push_back(Ptr);
4909   switch (Form) {
4910   case Init:
4911     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4912     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4913     break;
4914   case Load:
4915     SubExprs.push_back(APIOrderedArgs[1]); // Order
4916     break;
4917   case LoadCopy:
4918   case Copy:
4919   case Arithmetic:
4920   case Xchg:
4921     SubExprs.push_back(APIOrderedArgs[2]); // Order
4922     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4923     break;
4924   case GNUXchg:
4925     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4926     SubExprs.push_back(APIOrderedArgs[3]); // Order
4927     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4928     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4929     break;
4930   case C11CmpXchg:
4931     SubExprs.push_back(APIOrderedArgs[3]); // Order
4932     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4933     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4934     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4935     break;
4936   case GNUCmpXchg:
4937     SubExprs.push_back(APIOrderedArgs[4]); // Order
4938     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4939     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4940     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4941     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4942     break;
4943   }
4944 
4945   if (SubExprs.size() >= 2 && Form != Init) {
4946     llvm::APSInt Result(32);
4947     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4948         !isValidOrderingForOp(Result.getSExtValue(), Op))
4949       Diag(SubExprs[1]->getBeginLoc(),
4950            diag::warn_atomic_op_has_invalid_memory_order)
4951           << SubExprs[1]->getSourceRange();
4952   }
4953 
4954   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4955     auto *Scope = Args[Args.size() - 1];
4956     llvm::APSInt Result(32);
4957     if (Scope->isIntegerConstantExpr(Result, Context) &&
4958         !ScopeModel->isValid(Result.getZExtValue())) {
4959       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4960           << Scope->getSourceRange();
4961     }
4962     SubExprs.push_back(Scope);
4963   }
4964 
4965   AtomicExpr *AE = new (Context)
4966       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4967 
4968   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4969        Op == AtomicExpr::AO__c11_atomic_store ||
4970        Op == AtomicExpr::AO__opencl_atomic_load ||
4971        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4972       Context.AtomicUsesUnsupportedLibcall(AE))
4973     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4974         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4975              Op == AtomicExpr::AO__opencl_atomic_load)
4976                 ? 0
4977                 : 1);
4978 
4979   return AE;
4980 }
4981 
4982 /// checkBuiltinArgument - Given a call to a builtin function, perform
4983 /// normal type-checking on the given argument, updating the call in
4984 /// place.  This is useful when a builtin function requires custom
4985 /// type-checking for some of its arguments but not necessarily all of
4986 /// them.
4987 ///
4988 /// Returns true on error.
4989 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4990   FunctionDecl *Fn = E->getDirectCallee();
4991   assert(Fn && "builtin call without direct callee!");
4992 
4993   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4994   InitializedEntity Entity =
4995     InitializedEntity::InitializeParameter(S.Context, Param);
4996 
4997   ExprResult Arg = E->getArg(0);
4998   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4999   if (Arg.isInvalid())
5000     return true;
5001 
5002   E->setArg(ArgIndex, Arg.get());
5003   return false;
5004 }
5005 
5006 /// We have a call to a function like __sync_fetch_and_add, which is an
5007 /// overloaded function based on the pointer type of its first argument.
5008 /// The main BuildCallExpr routines have already promoted the types of
5009 /// arguments because all of these calls are prototyped as void(...).
5010 ///
5011 /// This function goes through and does final semantic checking for these
5012 /// builtins, as well as generating any warnings.
5013 ExprResult
5014 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5015   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5016   Expr *Callee = TheCall->getCallee();
5017   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5018   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5019 
5020   // Ensure that we have at least one argument to do type inference from.
5021   if (TheCall->getNumArgs() < 1) {
5022     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5023         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5024     return ExprError();
5025   }
5026 
5027   // Inspect the first argument of the atomic builtin.  This should always be
5028   // a pointer type, whose element is an integral scalar or pointer type.
5029   // Because it is a pointer type, we don't have to worry about any implicit
5030   // casts here.
5031   // FIXME: We don't allow floating point scalars as input.
5032   Expr *FirstArg = TheCall->getArg(0);
5033   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5034   if (FirstArgResult.isInvalid())
5035     return ExprError();
5036   FirstArg = FirstArgResult.get();
5037   TheCall->setArg(0, FirstArg);
5038 
5039   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5040   if (!pointerType) {
5041     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5042         << FirstArg->getType() << FirstArg->getSourceRange();
5043     return ExprError();
5044   }
5045 
5046   QualType ValType = pointerType->getPointeeType();
5047   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5048       !ValType->isBlockPointerType()) {
5049     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5050         << FirstArg->getType() << FirstArg->getSourceRange();
5051     return ExprError();
5052   }
5053 
5054   if (ValType.isConstQualified()) {
5055     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5056         << FirstArg->getType() << FirstArg->getSourceRange();
5057     return ExprError();
5058   }
5059 
5060   switch (ValType.getObjCLifetime()) {
5061   case Qualifiers::OCL_None:
5062   case Qualifiers::OCL_ExplicitNone:
5063     // okay
5064     break;
5065 
5066   case Qualifiers::OCL_Weak:
5067   case Qualifiers::OCL_Strong:
5068   case Qualifiers::OCL_Autoreleasing:
5069     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5070         << ValType << FirstArg->getSourceRange();
5071     return ExprError();
5072   }
5073 
5074   // Strip any qualifiers off ValType.
5075   ValType = ValType.getUnqualifiedType();
5076 
5077   // The majority of builtins return a value, but a few have special return
5078   // types, so allow them to override appropriately below.
5079   QualType ResultType = ValType;
5080 
5081   // We need to figure out which concrete builtin this maps onto.  For example,
5082   // __sync_fetch_and_add with a 2 byte object turns into
5083   // __sync_fetch_and_add_2.
5084 #define BUILTIN_ROW(x) \
5085   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5086     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5087 
5088   static const unsigned BuiltinIndices[][5] = {
5089     BUILTIN_ROW(__sync_fetch_and_add),
5090     BUILTIN_ROW(__sync_fetch_and_sub),
5091     BUILTIN_ROW(__sync_fetch_and_or),
5092     BUILTIN_ROW(__sync_fetch_and_and),
5093     BUILTIN_ROW(__sync_fetch_and_xor),
5094     BUILTIN_ROW(__sync_fetch_and_nand),
5095 
5096     BUILTIN_ROW(__sync_add_and_fetch),
5097     BUILTIN_ROW(__sync_sub_and_fetch),
5098     BUILTIN_ROW(__sync_and_and_fetch),
5099     BUILTIN_ROW(__sync_or_and_fetch),
5100     BUILTIN_ROW(__sync_xor_and_fetch),
5101     BUILTIN_ROW(__sync_nand_and_fetch),
5102 
5103     BUILTIN_ROW(__sync_val_compare_and_swap),
5104     BUILTIN_ROW(__sync_bool_compare_and_swap),
5105     BUILTIN_ROW(__sync_lock_test_and_set),
5106     BUILTIN_ROW(__sync_lock_release),
5107     BUILTIN_ROW(__sync_swap)
5108   };
5109 #undef BUILTIN_ROW
5110 
5111   // Determine the index of the size.
5112   unsigned SizeIndex;
5113   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5114   case 1: SizeIndex = 0; break;
5115   case 2: SizeIndex = 1; break;
5116   case 4: SizeIndex = 2; break;
5117   case 8: SizeIndex = 3; break;
5118   case 16: SizeIndex = 4; break;
5119   default:
5120     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5121         << FirstArg->getType() << FirstArg->getSourceRange();
5122     return ExprError();
5123   }
5124 
5125   // Each of these builtins has one pointer argument, followed by some number of
5126   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5127   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5128   // as the number of fixed args.
5129   unsigned BuiltinID = FDecl->getBuiltinID();
5130   unsigned BuiltinIndex, NumFixed = 1;
5131   bool WarnAboutSemanticsChange = false;
5132   switch (BuiltinID) {
5133   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5134   case Builtin::BI__sync_fetch_and_add:
5135   case Builtin::BI__sync_fetch_and_add_1:
5136   case Builtin::BI__sync_fetch_and_add_2:
5137   case Builtin::BI__sync_fetch_and_add_4:
5138   case Builtin::BI__sync_fetch_and_add_8:
5139   case Builtin::BI__sync_fetch_and_add_16:
5140     BuiltinIndex = 0;
5141     break;
5142 
5143   case Builtin::BI__sync_fetch_and_sub:
5144   case Builtin::BI__sync_fetch_and_sub_1:
5145   case Builtin::BI__sync_fetch_and_sub_2:
5146   case Builtin::BI__sync_fetch_and_sub_4:
5147   case Builtin::BI__sync_fetch_and_sub_8:
5148   case Builtin::BI__sync_fetch_and_sub_16:
5149     BuiltinIndex = 1;
5150     break;
5151 
5152   case Builtin::BI__sync_fetch_and_or:
5153   case Builtin::BI__sync_fetch_and_or_1:
5154   case Builtin::BI__sync_fetch_and_or_2:
5155   case Builtin::BI__sync_fetch_and_or_4:
5156   case Builtin::BI__sync_fetch_and_or_8:
5157   case Builtin::BI__sync_fetch_and_or_16:
5158     BuiltinIndex = 2;
5159     break;
5160 
5161   case Builtin::BI__sync_fetch_and_and:
5162   case Builtin::BI__sync_fetch_and_and_1:
5163   case Builtin::BI__sync_fetch_and_and_2:
5164   case Builtin::BI__sync_fetch_and_and_4:
5165   case Builtin::BI__sync_fetch_and_and_8:
5166   case Builtin::BI__sync_fetch_and_and_16:
5167     BuiltinIndex = 3;
5168     break;
5169 
5170   case Builtin::BI__sync_fetch_and_xor:
5171   case Builtin::BI__sync_fetch_and_xor_1:
5172   case Builtin::BI__sync_fetch_and_xor_2:
5173   case Builtin::BI__sync_fetch_and_xor_4:
5174   case Builtin::BI__sync_fetch_and_xor_8:
5175   case Builtin::BI__sync_fetch_and_xor_16:
5176     BuiltinIndex = 4;
5177     break;
5178 
5179   case Builtin::BI__sync_fetch_and_nand:
5180   case Builtin::BI__sync_fetch_and_nand_1:
5181   case Builtin::BI__sync_fetch_and_nand_2:
5182   case Builtin::BI__sync_fetch_and_nand_4:
5183   case Builtin::BI__sync_fetch_and_nand_8:
5184   case Builtin::BI__sync_fetch_and_nand_16:
5185     BuiltinIndex = 5;
5186     WarnAboutSemanticsChange = true;
5187     break;
5188 
5189   case Builtin::BI__sync_add_and_fetch:
5190   case Builtin::BI__sync_add_and_fetch_1:
5191   case Builtin::BI__sync_add_and_fetch_2:
5192   case Builtin::BI__sync_add_and_fetch_4:
5193   case Builtin::BI__sync_add_and_fetch_8:
5194   case Builtin::BI__sync_add_and_fetch_16:
5195     BuiltinIndex = 6;
5196     break;
5197 
5198   case Builtin::BI__sync_sub_and_fetch:
5199   case Builtin::BI__sync_sub_and_fetch_1:
5200   case Builtin::BI__sync_sub_and_fetch_2:
5201   case Builtin::BI__sync_sub_and_fetch_4:
5202   case Builtin::BI__sync_sub_and_fetch_8:
5203   case Builtin::BI__sync_sub_and_fetch_16:
5204     BuiltinIndex = 7;
5205     break;
5206 
5207   case Builtin::BI__sync_and_and_fetch:
5208   case Builtin::BI__sync_and_and_fetch_1:
5209   case Builtin::BI__sync_and_and_fetch_2:
5210   case Builtin::BI__sync_and_and_fetch_4:
5211   case Builtin::BI__sync_and_and_fetch_8:
5212   case Builtin::BI__sync_and_and_fetch_16:
5213     BuiltinIndex = 8;
5214     break;
5215 
5216   case Builtin::BI__sync_or_and_fetch:
5217   case Builtin::BI__sync_or_and_fetch_1:
5218   case Builtin::BI__sync_or_and_fetch_2:
5219   case Builtin::BI__sync_or_and_fetch_4:
5220   case Builtin::BI__sync_or_and_fetch_8:
5221   case Builtin::BI__sync_or_and_fetch_16:
5222     BuiltinIndex = 9;
5223     break;
5224 
5225   case Builtin::BI__sync_xor_and_fetch:
5226   case Builtin::BI__sync_xor_and_fetch_1:
5227   case Builtin::BI__sync_xor_and_fetch_2:
5228   case Builtin::BI__sync_xor_and_fetch_4:
5229   case Builtin::BI__sync_xor_and_fetch_8:
5230   case Builtin::BI__sync_xor_and_fetch_16:
5231     BuiltinIndex = 10;
5232     break;
5233 
5234   case Builtin::BI__sync_nand_and_fetch:
5235   case Builtin::BI__sync_nand_and_fetch_1:
5236   case Builtin::BI__sync_nand_and_fetch_2:
5237   case Builtin::BI__sync_nand_and_fetch_4:
5238   case Builtin::BI__sync_nand_and_fetch_8:
5239   case Builtin::BI__sync_nand_and_fetch_16:
5240     BuiltinIndex = 11;
5241     WarnAboutSemanticsChange = true;
5242     break;
5243 
5244   case Builtin::BI__sync_val_compare_and_swap:
5245   case Builtin::BI__sync_val_compare_and_swap_1:
5246   case Builtin::BI__sync_val_compare_and_swap_2:
5247   case Builtin::BI__sync_val_compare_and_swap_4:
5248   case Builtin::BI__sync_val_compare_and_swap_8:
5249   case Builtin::BI__sync_val_compare_and_swap_16:
5250     BuiltinIndex = 12;
5251     NumFixed = 2;
5252     break;
5253 
5254   case Builtin::BI__sync_bool_compare_and_swap:
5255   case Builtin::BI__sync_bool_compare_and_swap_1:
5256   case Builtin::BI__sync_bool_compare_and_swap_2:
5257   case Builtin::BI__sync_bool_compare_and_swap_4:
5258   case Builtin::BI__sync_bool_compare_and_swap_8:
5259   case Builtin::BI__sync_bool_compare_and_swap_16:
5260     BuiltinIndex = 13;
5261     NumFixed = 2;
5262     ResultType = Context.BoolTy;
5263     break;
5264 
5265   case Builtin::BI__sync_lock_test_and_set:
5266   case Builtin::BI__sync_lock_test_and_set_1:
5267   case Builtin::BI__sync_lock_test_and_set_2:
5268   case Builtin::BI__sync_lock_test_and_set_4:
5269   case Builtin::BI__sync_lock_test_and_set_8:
5270   case Builtin::BI__sync_lock_test_and_set_16:
5271     BuiltinIndex = 14;
5272     break;
5273 
5274   case Builtin::BI__sync_lock_release:
5275   case Builtin::BI__sync_lock_release_1:
5276   case Builtin::BI__sync_lock_release_2:
5277   case Builtin::BI__sync_lock_release_4:
5278   case Builtin::BI__sync_lock_release_8:
5279   case Builtin::BI__sync_lock_release_16:
5280     BuiltinIndex = 15;
5281     NumFixed = 0;
5282     ResultType = Context.VoidTy;
5283     break;
5284 
5285   case Builtin::BI__sync_swap:
5286   case Builtin::BI__sync_swap_1:
5287   case Builtin::BI__sync_swap_2:
5288   case Builtin::BI__sync_swap_4:
5289   case Builtin::BI__sync_swap_8:
5290   case Builtin::BI__sync_swap_16:
5291     BuiltinIndex = 16;
5292     break;
5293   }
5294 
5295   // Now that we know how many fixed arguments we expect, first check that we
5296   // have at least that many.
5297   if (TheCall->getNumArgs() < 1+NumFixed) {
5298     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5299         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5300         << Callee->getSourceRange();
5301     return ExprError();
5302   }
5303 
5304   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5305       << Callee->getSourceRange();
5306 
5307   if (WarnAboutSemanticsChange) {
5308     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5309         << Callee->getSourceRange();
5310   }
5311 
5312   // Get the decl for the concrete builtin from this, we can tell what the
5313   // concrete integer type we should convert to is.
5314   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5315   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5316   FunctionDecl *NewBuiltinDecl;
5317   if (NewBuiltinID == BuiltinID)
5318     NewBuiltinDecl = FDecl;
5319   else {
5320     // Perform builtin lookup to avoid redeclaring it.
5321     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5322     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5323     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5324     assert(Res.getFoundDecl());
5325     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5326     if (!NewBuiltinDecl)
5327       return ExprError();
5328   }
5329 
5330   // The first argument --- the pointer --- has a fixed type; we
5331   // deduce the types of the rest of the arguments accordingly.  Walk
5332   // the remaining arguments, converting them to the deduced value type.
5333   for (unsigned i = 0; i != NumFixed; ++i) {
5334     ExprResult Arg = TheCall->getArg(i+1);
5335 
5336     // GCC does an implicit conversion to the pointer or integer ValType.  This
5337     // can fail in some cases (1i -> int**), check for this error case now.
5338     // Initialize the argument.
5339     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5340                                                    ValType, /*consume*/ false);
5341     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5342     if (Arg.isInvalid())
5343       return ExprError();
5344 
5345     // Okay, we have something that *can* be converted to the right type.  Check
5346     // to see if there is a potentially weird extension going on here.  This can
5347     // happen when you do an atomic operation on something like an char* and
5348     // pass in 42.  The 42 gets converted to char.  This is even more strange
5349     // for things like 45.123 -> char, etc.
5350     // FIXME: Do this check.
5351     TheCall->setArg(i+1, Arg.get());
5352   }
5353 
5354   // Create a new DeclRefExpr to refer to the new decl.
5355   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5356       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5357       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5358       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5359 
5360   // Set the callee in the CallExpr.
5361   // FIXME: This loses syntactic information.
5362   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5363   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5364                                               CK_BuiltinFnToFnPtr);
5365   TheCall->setCallee(PromotedCall.get());
5366 
5367   // Change the result type of the call to match the original value type. This
5368   // is arbitrary, but the codegen for these builtins ins design to handle it
5369   // gracefully.
5370   TheCall->setType(ResultType);
5371 
5372   return TheCallResult;
5373 }
5374 
5375 /// SemaBuiltinNontemporalOverloaded - We have a call to
5376 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5377 /// overloaded function based on the pointer type of its last argument.
5378 ///
5379 /// This function goes through and does final semantic checking for these
5380 /// builtins.
5381 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5382   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5383   DeclRefExpr *DRE =
5384       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5385   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5386   unsigned BuiltinID = FDecl->getBuiltinID();
5387   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5388           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5389          "Unexpected nontemporal load/store builtin!");
5390   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5391   unsigned numArgs = isStore ? 2 : 1;
5392 
5393   // Ensure that we have the proper number of arguments.
5394   if (checkArgCount(*this, TheCall, numArgs))
5395     return ExprError();
5396 
5397   // Inspect the last argument of the nontemporal builtin.  This should always
5398   // be a pointer type, from which we imply the type of the memory access.
5399   // Because it is a pointer type, we don't have to worry about any implicit
5400   // casts here.
5401   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5402   ExprResult PointerArgResult =
5403       DefaultFunctionArrayLvalueConversion(PointerArg);
5404 
5405   if (PointerArgResult.isInvalid())
5406     return ExprError();
5407   PointerArg = PointerArgResult.get();
5408   TheCall->setArg(numArgs - 1, PointerArg);
5409 
5410   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5411   if (!pointerType) {
5412     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5413         << PointerArg->getType() << PointerArg->getSourceRange();
5414     return ExprError();
5415   }
5416 
5417   QualType ValType = pointerType->getPointeeType();
5418 
5419   // Strip any qualifiers off ValType.
5420   ValType = ValType.getUnqualifiedType();
5421   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5422       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5423       !ValType->isVectorType()) {
5424     Diag(DRE->getBeginLoc(),
5425          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5426         << PointerArg->getType() << PointerArg->getSourceRange();
5427     return ExprError();
5428   }
5429 
5430   if (!isStore) {
5431     TheCall->setType(ValType);
5432     return TheCallResult;
5433   }
5434 
5435   ExprResult ValArg = TheCall->getArg(0);
5436   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5437       Context, ValType, /*consume*/ false);
5438   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5439   if (ValArg.isInvalid())
5440     return ExprError();
5441 
5442   TheCall->setArg(0, ValArg.get());
5443   TheCall->setType(Context.VoidTy);
5444   return TheCallResult;
5445 }
5446 
5447 /// CheckObjCString - Checks that the argument to the builtin
5448 /// CFString constructor is correct
5449 /// Note: It might also make sense to do the UTF-16 conversion here (would
5450 /// simplify the backend).
5451 bool Sema::CheckObjCString(Expr *Arg) {
5452   Arg = Arg->IgnoreParenCasts();
5453   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5454 
5455   if (!Literal || !Literal->isAscii()) {
5456     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5457         << Arg->getSourceRange();
5458     return true;
5459   }
5460 
5461   if (Literal->containsNonAsciiOrNull()) {
5462     StringRef String = Literal->getString();
5463     unsigned NumBytes = String.size();
5464     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5465     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5466     llvm::UTF16 *ToPtr = &ToBuf[0];
5467 
5468     llvm::ConversionResult Result =
5469         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5470                                  ToPtr + NumBytes, llvm::strictConversion);
5471     // Check for conversion failure.
5472     if (Result != llvm::conversionOK)
5473       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5474           << Arg->getSourceRange();
5475   }
5476   return false;
5477 }
5478 
5479 /// CheckObjCString - Checks that the format string argument to the os_log()
5480 /// and os_trace() functions is correct, and converts it to const char *.
5481 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5482   Arg = Arg->IgnoreParenCasts();
5483   auto *Literal = dyn_cast<StringLiteral>(Arg);
5484   if (!Literal) {
5485     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5486       Literal = ObjcLiteral->getString();
5487     }
5488   }
5489 
5490   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5491     return ExprError(
5492         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5493         << Arg->getSourceRange());
5494   }
5495 
5496   ExprResult Result(Literal);
5497   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5498   InitializedEntity Entity =
5499       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5500   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5501   return Result;
5502 }
5503 
5504 /// Check that the user is calling the appropriate va_start builtin for the
5505 /// target and calling convention.
5506 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5507   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5508   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5509   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5510   bool IsWindows = TT.isOSWindows();
5511   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5512   if (IsX64 || IsAArch64) {
5513     CallingConv CC = CC_C;
5514     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5515       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5516     if (IsMSVAStart) {
5517       // Don't allow this in System V ABI functions.
5518       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5519         return S.Diag(Fn->getBeginLoc(),
5520                       diag::err_ms_va_start_used_in_sysv_function);
5521     } else {
5522       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5523       // On x64 Windows, don't allow this in System V ABI functions.
5524       // (Yes, that means there's no corresponding way to support variadic
5525       // System V ABI functions on Windows.)
5526       if ((IsWindows && CC == CC_X86_64SysV) ||
5527           (!IsWindows && CC == CC_Win64))
5528         return S.Diag(Fn->getBeginLoc(),
5529                       diag::err_va_start_used_in_wrong_abi_function)
5530                << !IsWindows;
5531     }
5532     return false;
5533   }
5534 
5535   if (IsMSVAStart)
5536     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5537   return false;
5538 }
5539 
5540 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5541                                              ParmVarDecl **LastParam = nullptr) {
5542   // Determine whether the current function, block, or obj-c method is variadic
5543   // and get its parameter list.
5544   bool IsVariadic = false;
5545   ArrayRef<ParmVarDecl *> Params;
5546   DeclContext *Caller = S.CurContext;
5547   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5548     IsVariadic = Block->isVariadic();
5549     Params = Block->parameters();
5550   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5551     IsVariadic = FD->isVariadic();
5552     Params = FD->parameters();
5553   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5554     IsVariadic = MD->isVariadic();
5555     // FIXME: This isn't correct for methods (results in bogus warning).
5556     Params = MD->parameters();
5557   } else if (isa<CapturedDecl>(Caller)) {
5558     // We don't support va_start in a CapturedDecl.
5559     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5560     return true;
5561   } else {
5562     // This must be some other declcontext that parses exprs.
5563     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5564     return true;
5565   }
5566 
5567   if (!IsVariadic) {
5568     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5569     return true;
5570   }
5571 
5572   if (LastParam)
5573     *LastParam = Params.empty() ? nullptr : Params.back();
5574 
5575   return false;
5576 }
5577 
5578 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5579 /// for validity.  Emit an error and return true on failure; return false
5580 /// on success.
5581 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5582   Expr *Fn = TheCall->getCallee();
5583 
5584   if (checkVAStartABI(*this, BuiltinID, Fn))
5585     return true;
5586 
5587   if (TheCall->getNumArgs() > 2) {
5588     Diag(TheCall->getArg(2)->getBeginLoc(),
5589          diag::err_typecheck_call_too_many_args)
5590         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5591         << Fn->getSourceRange()
5592         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5593                        (*(TheCall->arg_end() - 1))->getEndLoc());
5594     return true;
5595   }
5596 
5597   if (TheCall->getNumArgs() < 2) {
5598     return Diag(TheCall->getEndLoc(),
5599                 diag::err_typecheck_call_too_few_args_at_least)
5600            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5601   }
5602 
5603   // Type-check the first argument normally.
5604   if (checkBuiltinArgument(*this, TheCall, 0))
5605     return true;
5606 
5607   // Check that the current function is variadic, and get its last parameter.
5608   ParmVarDecl *LastParam;
5609   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5610     return true;
5611 
5612   // Verify that the second argument to the builtin is the last argument of the
5613   // current function or method.
5614   bool SecondArgIsLastNamedArgument = false;
5615   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5616 
5617   // These are valid if SecondArgIsLastNamedArgument is false after the next
5618   // block.
5619   QualType Type;
5620   SourceLocation ParamLoc;
5621   bool IsCRegister = false;
5622 
5623   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5624     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5625       SecondArgIsLastNamedArgument = PV == LastParam;
5626 
5627       Type = PV->getType();
5628       ParamLoc = PV->getLocation();
5629       IsCRegister =
5630           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5631     }
5632   }
5633 
5634   if (!SecondArgIsLastNamedArgument)
5635     Diag(TheCall->getArg(1)->getBeginLoc(),
5636          diag::warn_second_arg_of_va_start_not_last_named_param);
5637   else if (IsCRegister || Type->isReferenceType() ||
5638            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5639              // Promotable integers are UB, but enumerations need a bit of
5640              // extra checking to see what their promotable type actually is.
5641              if (!Type->isPromotableIntegerType())
5642                return false;
5643              if (!Type->isEnumeralType())
5644                return true;
5645              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5646              return !(ED &&
5647                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5648            }()) {
5649     unsigned Reason = 0;
5650     if (Type->isReferenceType())  Reason = 1;
5651     else if (IsCRegister)         Reason = 2;
5652     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5653     Diag(ParamLoc, diag::note_parameter_type) << Type;
5654   }
5655 
5656   TheCall->setType(Context.VoidTy);
5657   return false;
5658 }
5659 
5660 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5661   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5662   //                 const char *named_addr);
5663 
5664   Expr *Func = Call->getCallee();
5665 
5666   if (Call->getNumArgs() < 3)
5667     return Diag(Call->getEndLoc(),
5668                 diag::err_typecheck_call_too_few_args_at_least)
5669            << 0 /*function call*/ << 3 << Call->getNumArgs();
5670 
5671   // Type-check the first argument normally.
5672   if (checkBuiltinArgument(*this, Call, 0))
5673     return true;
5674 
5675   // Check that the current function is variadic.
5676   if (checkVAStartIsInVariadicFunction(*this, Func))
5677     return true;
5678 
5679   // __va_start on Windows does not validate the parameter qualifiers
5680 
5681   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5682   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5683 
5684   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5685   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5686 
5687   const QualType &ConstCharPtrTy =
5688       Context.getPointerType(Context.CharTy.withConst());
5689   if (!Arg1Ty->isPointerType() ||
5690       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5691     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5692         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5693         << 0                                      /* qualifier difference */
5694         << 3                                      /* parameter mismatch */
5695         << 2 << Arg1->getType() << ConstCharPtrTy;
5696 
5697   const QualType SizeTy = Context.getSizeType();
5698   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5699     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5700         << Arg2->getType() << SizeTy << 1 /* different class */
5701         << 0                              /* qualifier difference */
5702         << 3                              /* parameter mismatch */
5703         << 3 << Arg2->getType() << SizeTy;
5704 
5705   return false;
5706 }
5707 
5708 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5709 /// friends.  This is declared to take (...), so we have to check everything.
5710 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5711   if (TheCall->getNumArgs() < 2)
5712     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5713            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5714   if (TheCall->getNumArgs() > 2)
5715     return Diag(TheCall->getArg(2)->getBeginLoc(),
5716                 diag::err_typecheck_call_too_many_args)
5717            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5718            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5719                           (*(TheCall->arg_end() - 1))->getEndLoc());
5720 
5721   ExprResult OrigArg0 = TheCall->getArg(0);
5722   ExprResult OrigArg1 = TheCall->getArg(1);
5723 
5724   // Do standard promotions between the two arguments, returning their common
5725   // type.
5726   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5727   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5728     return true;
5729 
5730   // Make sure any conversions are pushed back into the call; this is
5731   // type safe since unordered compare builtins are declared as "_Bool
5732   // foo(...)".
5733   TheCall->setArg(0, OrigArg0.get());
5734   TheCall->setArg(1, OrigArg1.get());
5735 
5736   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5737     return false;
5738 
5739   // If the common type isn't a real floating type, then the arguments were
5740   // invalid for this operation.
5741   if (Res.isNull() || !Res->isRealFloatingType())
5742     return Diag(OrigArg0.get()->getBeginLoc(),
5743                 diag::err_typecheck_call_invalid_ordered_compare)
5744            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5745            << SourceRange(OrigArg0.get()->getBeginLoc(),
5746                           OrigArg1.get()->getEndLoc());
5747 
5748   return false;
5749 }
5750 
5751 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5752 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5753 /// to check everything. We expect the last argument to be a floating point
5754 /// value.
5755 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5756   if (TheCall->getNumArgs() < NumArgs)
5757     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5758            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5759   if (TheCall->getNumArgs() > NumArgs)
5760     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5761                 diag::err_typecheck_call_too_many_args)
5762            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5763            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5764                           (*(TheCall->arg_end() - 1))->getEndLoc());
5765 
5766   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5767 
5768   if (OrigArg->isTypeDependent())
5769     return false;
5770 
5771   // This operation requires a non-_Complex floating-point number.
5772   if (!OrigArg->getType()->isRealFloatingType())
5773     return Diag(OrigArg->getBeginLoc(),
5774                 diag::err_typecheck_call_invalid_unary_fp)
5775            << OrigArg->getType() << OrigArg->getSourceRange();
5776 
5777   // If this is an implicit conversion from float -> float, double, or
5778   // long double, remove it.
5779   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5780     // Only remove standard FloatCasts, leaving other casts inplace
5781     if (Cast->getCastKind() == CK_FloatingCast) {
5782       Expr *CastArg = Cast->getSubExpr();
5783       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5784         assert(
5785             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5786              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5787              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5788             "promotion from float to either float, double, or long double is "
5789             "the only expected cast here");
5790         Cast->setSubExpr(nullptr);
5791         TheCall->setArg(NumArgs-1, CastArg);
5792       }
5793     }
5794   }
5795 
5796   return false;
5797 }
5798 
5799 // Customized Sema Checking for VSX builtins that have the following signature:
5800 // vector [...] builtinName(vector [...], vector [...], const int);
5801 // Which takes the same type of vectors (any legal vector type) for the first
5802 // two arguments and takes compile time constant for the third argument.
5803 // Example builtins are :
5804 // vector double vec_xxpermdi(vector double, vector double, int);
5805 // vector short vec_xxsldwi(vector short, vector short, int);
5806 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5807   unsigned ExpectedNumArgs = 3;
5808   if (TheCall->getNumArgs() < ExpectedNumArgs)
5809     return Diag(TheCall->getEndLoc(),
5810                 diag::err_typecheck_call_too_few_args_at_least)
5811            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5812            << TheCall->getSourceRange();
5813 
5814   if (TheCall->getNumArgs() > ExpectedNumArgs)
5815     return Diag(TheCall->getEndLoc(),
5816                 diag::err_typecheck_call_too_many_args_at_most)
5817            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5818            << TheCall->getSourceRange();
5819 
5820   // Check the third argument is a compile time constant
5821   llvm::APSInt Value;
5822   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5823     return Diag(TheCall->getBeginLoc(),
5824                 diag::err_vsx_builtin_nonconstant_argument)
5825            << 3 /* argument index */ << TheCall->getDirectCallee()
5826            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5827                           TheCall->getArg(2)->getEndLoc());
5828 
5829   QualType Arg1Ty = TheCall->getArg(0)->getType();
5830   QualType Arg2Ty = TheCall->getArg(1)->getType();
5831 
5832   // Check the type of argument 1 and argument 2 are vectors.
5833   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5834   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5835       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5836     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5837            << TheCall->getDirectCallee()
5838            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5839                           TheCall->getArg(1)->getEndLoc());
5840   }
5841 
5842   // Check the first two arguments are the same type.
5843   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5844     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5845            << TheCall->getDirectCallee()
5846            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5847                           TheCall->getArg(1)->getEndLoc());
5848   }
5849 
5850   // When default clang type checking is turned off and the customized type
5851   // checking is used, the returning type of the function must be explicitly
5852   // set. Otherwise it is _Bool by default.
5853   TheCall->setType(Arg1Ty);
5854 
5855   return false;
5856 }
5857 
5858 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5859 // This is declared to take (...), so we have to check everything.
5860 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5861   if (TheCall->getNumArgs() < 2)
5862     return ExprError(Diag(TheCall->getEndLoc(),
5863                           diag::err_typecheck_call_too_few_args_at_least)
5864                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5865                      << TheCall->getSourceRange());
5866 
5867   // Determine which of the following types of shufflevector we're checking:
5868   // 1) unary, vector mask: (lhs, mask)
5869   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5870   QualType resType = TheCall->getArg(0)->getType();
5871   unsigned numElements = 0;
5872 
5873   if (!TheCall->getArg(0)->isTypeDependent() &&
5874       !TheCall->getArg(1)->isTypeDependent()) {
5875     QualType LHSType = TheCall->getArg(0)->getType();
5876     QualType RHSType = TheCall->getArg(1)->getType();
5877 
5878     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5879       return ExprError(
5880           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5881           << TheCall->getDirectCallee()
5882           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5883                          TheCall->getArg(1)->getEndLoc()));
5884 
5885     numElements = LHSType->castAs<VectorType>()->getNumElements();
5886     unsigned numResElements = TheCall->getNumArgs() - 2;
5887 
5888     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5889     // with mask.  If so, verify that RHS is an integer vector type with the
5890     // same number of elts as lhs.
5891     if (TheCall->getNumArgs() == 2) {
5892       if (!RHSType->hasIntegerRepresentation() ||
5893           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5894         return ExprError(Diag(TheCall->getBeginLoc(),
5895                               diag::err_vec_builtin_incompatible_vector)
5896                          << TheCall->getDirectCallee()
5897                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5898                                         TheCall->getArg(1)->getEndLoc()));
5899     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5900       return ExprError(Diag(TheCall->getBeginLoc(),
5901                             diag::err_vec_builtin_incompatible_vector)
5902                        << TheCall->getDirectCallee()
5903                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5904                                       TheCall->getArg(1)->getEndLoc()));
5905     } else if (numElements != numResElements) {
5906       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5907       resType = Context.getVectorType(eltType, numResElements,
5908                                       VectorType::GenericVector);
5909     }
5910   }
5911 
5912   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5913     if (TheCall->getArg(i)->isTypeDependent() ||
5914         TheCall->getArg(i)->isValueDependent())
5915       continue;
5916 
5917     llvm::APSInt Result(32);
5918     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5919       return ExprError(Diag(TheCall->getBeginLoc(),
5920                             diag::err_shufflevector_nonconstant_argument)
5921                        << TheCall->getArg(i)->getSourceRange());
5922 
5923     // Allow -1 which will be translated to undef in the IR.
5924     if (Result.isSigned() && Result.isAllOnesValue())
5925       continue;
5926 
5927     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5928       return ExprError(Diag(TheCall->getBeginLoc(),
5929                             diag::err_shufflevector_argument_too_large)
5930                        << TheCall->getArg(i)->getSourceRange());
5931   }
5932 
5933   SmallVector<Expr*, 32> exprs;
5934 
5935   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5936     exprs.push_back(TheCall->getArg(i));
5937     TheCall->setArg(i, nullptr);
5938   }
5939 
5940   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5941                                          TheCall->getCallee()->getBeginLoc(),
5942                                          TheCall->getRParenLoc());
5943 }
5944 
5945 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5946 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5947                                        SourceLocation BuiltinLoc,
5948                                        SourceLocation RParenLoc) {
5949   ExprValueKind VK = VK_RValue;
5950   ExprObjectKind OK = OK_Ordinary;
5951   QualType DstTy = TInfo->getType();
5952   QualType SrcTy = E->getType();
5953 
5954   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5955     return ExprError(Diag(BuiltinLoc,
5956                           diag::err_convertvector_non_vector)
5957                      << E->getSourceRange());
5958   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5959     return ExprError(Diag(BuiltinLoc,
5960                           diag::err_convertvector_non_vector_type));
5961 
5962   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5963     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5964     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5965     if (SrcElts != DstElts)
5966       return ExprError(Diag(BuiltinLoc,
5967                             diag::err_convertvector_incompatible_vector)
5968                        << E->getSourceRange());
5969   }
5970 
5971   return new (Context)
5972       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5973 }
5974 
5975 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5976 // This is declared to take (const void*, ...) and can take two
5977 // optional constant int args.
5978 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5979   unsigned NumArgs = TheCall->getNumArgs();
5980 
5981   if (NumArgs > 3)
5982     return Diag(TheCall->getEndLoc(),
5983                 diag::err_typecheck_call_too_many_args_at_most)
5984            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5985 
5986   // Argument 0 is checked for us and the remaining arguments must be
5987   // constant integers.
5988   for (unsigned i = 1; i != NumArgs; ++i)
5989     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5990       return true;
5991 
5992   return false;
5993 }
5994 
5995 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5996 // __assume does not evaluate its arguments, and should warn if its argument
5997 // has side effects.
5998 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5999   Expr *Arg = TheCall->getArg(0);
6000   if (Arg->isInstantiationDependent()) return false;
6001 
6002   if (Arg->HasSideEffects(Context))
6003     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6004         << Arg->getSourceRange()
6005         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6006 
6007   return false;
6008 }
6009 
6010 /// Handle __builtin_alloca_with_align. This is declared
6011 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6012 /// than 8.
6013 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6014   // The alignment must be a constant integer.
6015   Expr *Arg = TheCall->getArg(1);
6016 
6017   // We can't check the value of a dependent argument.
6018   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6019     if (const auto *UE =
6020             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6021       if (UE->getKind() == UETT_AlignOf ||
6022           UE->getKind() == UETT_PreferredAlignOf)
6023         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6024             << Arg->getSourceRange();
6025 
6026     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6027 
6028     if (!Result.isPowerOf2())
6029       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6030              << Arg->getSourceRange();
6031 
6032     if (Result < Context.getCharWidth())
6033       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6034              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6035 
6036     if (Result > std::numeric_limits<int32_t>::max())
6037       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6038              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6039   }
6040 
6041   return false;
6042 }
6043 
6044 /// Handle __builtin_assume_aligned. This is declared
6045 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6046 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6047   unsigned NumArgs = TheCall->getNumArgs();
6048 
6049   if (NumArgs > 3)
6050     return Diag(TheCall->getEndLoc(),
6051                 diag::err_typecheck_call_too_many_args_at_most)
6052            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6053 
6054   // The alignment must be a constant integer.
6055   Expr *Arg = TheCall->getArg(1);
6056 
6057   // We can't check the value of a dependent argument.
6058   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6059     llvm::APSInt Result;
6060     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6061       return true;
6062 
6063     if (!Result.isPowerOf2())
6064       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6065              << Arg->getSourceRange();
6066   }
6067 
6068   if (NumArgs > 2) {
6069     ExprResult Arg(TheCall->getArg(2));
6070     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6071       Context.getSizeType(), false);
6072     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6073     if (Arg.isInvalid()) return true;
6074     TheCall->setArg(2, Arg.get());
6075   }
6076 
6077   return false;
6078 }
6079 
6080 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6081   unsigned BuiltinID =
6082       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6083   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6084 
6085   unsigned NumArgs = TheCall->getNumArgs();
6086   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6087   if (NumArgs < NumRequiredArgs) {
6088     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6089            << 0 /* function call */ << NumRequiredArgs << NumArgs
6090            << TheCall->getSourceRange();
6091   }
6092   if (NumArgs >= NumRequiredArgs + 0x100) {
6093     return Diag(TheCall->getEndLoc(),
6094                 diag::err_typecheck_call_too_many_args_at_most)
6095            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6096            << TheCall->getSourceRange();
6097   }
6098   unsigned i = 0;
6099 
6100   // For formatting call, check buffer arg.
6101   if (!IsSizeCall) {
6102     ExprResult Arg(TheCall->getArg(i));
6103     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6104         Context, Context.VoidPtrTy, false);
6105     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6106     if (Arg.isInvalid())
6107       return true;
6108     TheCall->setArg(i, Arg.get());
6109     i++;
6110   }
6111 
6112   // Check string literal arg.
6113   unsigned FormatIdx = i;
6114   {
6115     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6116     if (Arg.isInvalid())
6117       return true;
6118     TheCall->setArg(i, Arg.get());
6119     i++;
6120   }
6121 
6122   // Make sure variadic args are scalar.
6123   unsigned FirstDataArg = i;
6124   while (i < NumArgs) {
6125     ExprResult Arg = DefaultVariadicArgumentPromotion(
6126         TheCall->getArg(i), VariadicFunction, nullptr);
6127     if (Arg.isInvalid())
6128       return true;
6129     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6130     if (ArgSize.getQuantity() >= 0x100) {
6131       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6132              << i << (int)ArgSize.getQuantity() << 0xff
6133              << TheCall->getSourceRange();
6134     }
6135     TheCall->setArg(i, Arg.get());
6136     i++;
6137   }
6138 
6139   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6140   // call to avoid duplicate diagnostics.
6141   if (!IsSizeCall) {
6142     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6143     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6144     bool Success = CheckFormatArguments(
6145         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6146         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6147         CheckedVarArgs);
6148     if (!Success)
6149       return true;
6150   }
6151 
6152   if (IsSizeCall) {
6153     TheCall->setType(Context.getSizeType());
6154   } else {
6155     TheCall->setType(Context.VoidPtrTy);
6156   }
6157   return false;
6158 }
6159 
6160 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6161 /// TheCall is a constant expression.
6162 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6163                                   llvm::APSInt &Result) {
6164   Expr *Arg = TheCall->getArg(ArgNum);
6165   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6166   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6167 
6168   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6169 
6170   if (!Arg->isIntegerConstantExpr(Result, Context))
6171     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6172            << FDecl->getDeclName() << Arg->getSourceRange();
6173 
6174   return false;
6175 }
6176 
6177 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6178 /// TheCall is a constant expression in the range [Low, High].
6179 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6180                                        int Low, int High, bool RangeIsError) {
6181   if (isConstantEvaluated())
6182     return false;
6183   llvm::APSInt Result;
6184 
6185   // We can't check the value of a dependent argument.
6186   Expr *Arg = TheCall->getArg(ArgNum);
6187   if (Arg->isTypeDependent() || Arg->isValueDependent())
6188     return false;
6189 
6190   // Check constant-ness first.
6191   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6192     return true;
6193 
6194   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6195     if (RangeIsError)
6196       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6197              << Result.toString(10) << Low << High << Arg->getSourceRange();
6198     else
6199       // Defer the warning until we know if the code will be emitted so that
6200       // dead code can ignore this.
6201       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6202                           PDiag(diag::warn_argument_invalid_range)
6203                               << Result.toString(10) << Low << High
6204                               << Arg->getSourceRange());
6205   }
6206 
6207   return false;
6208 }
6209 
6210 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6211 /// TheCall is a constant expression is a multiple of Num..
6212 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6213                                           unsigned Num) {
6214   llvm::APSInt Result;
6215 
6216   // We can't check the value of a dependent argument.
6217   Expr *Arg = TheCall->getArg(ArgNum);
6218   if (Arg->isTypeDependent() || Arg->isValueDependent())
6219     return false;
6220 
6221   // Check constant-ness first.
6222   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6223     return true;
6224 
6225   if (Result.getSExtValue() % Num != 0)
6226     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6227            << Num << Arg->getSourceRange();
6228 
6229   return false;
6230 }
6231 
6232 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6233 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6234   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6235     if (checkArgCount(*this, TheCall, 2))
6236       return true;
6237     Expr *Arg0 = TheCall->getArg(0);
6238     Expr *Arg1 = TheCall->getArg(1);
6239 
6240     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6241     if (FirstArg.isInvalid())
6242       return true;
6243     QualType FirstArgType = FirstArg.get()->getType();
6244     if (!FirstArgType->isAnyPointerType())
6245       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6246                << "first" << FirstArgType << Arg0->getSourceRange();
6247     TheCall->setArg(0, FirstArg.get());
6248 
6249     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6250     if (SecArg.isInvalid())
6251       return true;
6252     QualType SecArgType = SecArg.get()->getType();
6253     if (!SecArgType->isIntegerType())
6254       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6255                << "second" << SecArgType << Arg1->getSourceRange();
6256 
6257     // Derive the return type from the pointer argument.
6258     TheCall->setType(FirstArgType);
6259     return false;
6260   }
6261 
6262   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6263     if (checkArgCount(*this, TheCall, 2))
6264       return true;
6265 
6266     Expr *Arg0 = TheCall->getArg(0);
6267     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6268     if (FirstArg.isInvalid())
6269       return true;
6270     QualType FirstArgType = FirstArg.get()->getType();
6271     if (!FirstArgType->isAnyPointerType())
6272       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6273                << "first" << FirstArgType << Arg0->getSourceRange();
6274     TheCall->setArg(0, FirstArg.get());
6275 
6276     // Derive the return type from the pointer argument.
6277     TheCall->setType(FirstArgType);
6278 
6279     // Second arg must be an constant in range [0,15]
6280     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6281   }
6282 
6283   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6284     if (checkArgCount(*this, TheCall, 2))
6285       return true;
6286     Expr *Arg0 = TheCall->getArg(0);
6287     Expr *Arg1 = TheCall->getArg(1);
6288 
6289     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6290     if (FirstArg.isInvalid())
6291       return true;
6292     QualType FirstArgType = FirstArg.get()->getType();
6293     if (!FirstArgType->isAnyPointerType())
6294       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6295                << "first" << FirstArgType << Arg0->getSourceRange();
6296 
6297     QualType SecArgType = Arg1->getType();
6298     if (!SecArgType->isIntegerType())
6299       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6300                << "second" << SecArgType << Arg1->getSourceRange();
6301     TheCall->setType(Context.IntTy);
6302     return false;
6303   }
6304 
6305   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6306       BuiltinID == AArch64::BI__builtin_arm_stg) {
6307     if (checkArgCount(*this, TheCall, 1))
6308       return true;
6309     Expr *Arg0 = TheCall->getArg(0);
6310     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6311     if (FirstArg.isInvalid())
6312       return true;
6313 
6314     QualType FirstArgType = FirstArg.get()->getType();
6315     if (!FirstArgType->isAnyPointerType())
6316       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6317                << "first" << FirstArgType << Arg0->getSourceRange();
6318     TheCall->setArg(0, FirstArg.get());
6319 
6320     // Derive the return type from the pointer argument.
6321     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6322       TheCall->setType(FirstArgType);
6323     return false;
6324   }
6325 
6326   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6327     Expr *ArgA = TheCall->getArg(0);
6328     Expr *ArgB = TheCall->getArg(1);
6329 
6330     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6331     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6332 
6333     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6334       return true;
6335 
6336     QualType ArgTypeA = ArgExprA.get()->getType();
6337     QualType ArgTypeB = ArgExprB.get()->getType();
6338 
6339     auto isNull = [&] (Expr *E) -> bool {
6340       return E->isNullPointerConstant(
6341                         Context, Expr::NPC_ValueDependentIsNotNull); };
6342 
6343     // argument should be either a pointer or null
6344     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6345       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6346         << "first" << ArgTypeA << ArgA->getSourceRange();
6347 
6348     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6349       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6350         << "second" << ArgTypeB << ArgB->getSourceRange();
6351 
6352     // Ensure Pointee types are compatible
6353     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6354         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6355       QualType pointeeA = ArgTypeA->getPointeeType();
6356       QualType pointeeB = ArgTypeB->getPointeeType();
6357       if (!Context.typesAreCompatible(
6358              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6359              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6360         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6361           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6362           << ArgB->getSourceRange();
6363       }
6364     }
6365 
6366     // at least one argument should be pointer type
6367     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6368       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6369         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6370 
6371     if (isNull(ArgA)) // adopt type of the other pointer
6372       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6373 
6374     if (isNull(ArgB))
6375       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6376 
6377     TheCall->setArg(0, ArgExprA.get());
6378     TheCall->setArg(1, ArgExprB.get());
6379     TheCall->setType(Context.LongLongTy);
6380     return false;
6381   }
6382   assert(false && "Unhandled ARM MTE intrinsic");
6383   return true;
6384 }
6385 
6386 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6387 /// TheCall is an ARM/AArch64 special register string literal.
6388 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6389                                     int ArgNum, unsigned ExpectedFieldNum,
6390                                     bool AllowName) {
6391   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6392                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6393                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6394                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6395                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6396                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6397   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6398                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6399                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6400                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6401                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6402                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6403   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6404 
6405   // We can't check the value of a dependent argument.
6406   Expr *Arg = TheCall->getArg(ArgNum);
6407   if (Arg->isTypeDependent() || Arg->isValueDependent())
6408     return false;
6409 
6410   // Check if the argument is a string literal.
6411   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6412     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6413            << Arg->getSourceRange();
6414 
6415   // Check the type of special register given.
6416   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6417   SmallVector<StringRef, 6> Fields;
6418   Reg.split(Fields, ":");
6419 
6420   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6421     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6422            << Arg->getSourceRange();
6423 
6424   // If the string is the name of a register then we cannot check that it is
6425   // valid here but if the string is of one the forms described in ACLE then we
6426   // can check that the supplied fields are integers and within the valid
6427   // ranges.
6428   if (Fields.size() > 1) {
6429     bool FiveFields = Fields.size() == 5;
6430 
6431     bool ValidString = true;
6432     if (IsARMBuiltin) {
6433       ValidString &= Fields[0].startswith_lower("cp") ||
6434                      Fields[0].startswith_lower("p");
6435       if (ValidString)
6436         Fields[0] =
6437           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6438 
6439       ValidString &= Fields[2].startswith_lower("c");
6440       if (ValidString)
6441         Fields[2] = Fields[2].drop_front(1);
6442 
6443       if (FiveFields) {
6444         ValidString &= Fields[3].startswith_lower("c");
6445         if (ValidString)
6446           Fields[3] = Fields[3].drop_front(1);
6447       }
6448     }
6449 
6450     SmallVector<int, 5> Ranges;
6451     if (FiveFields)
6452       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6453     else
6454       Ranges.append({15, 7, 15});
6455 
6456     for (unsigned i=0; i<Fields.size(); ++i) {
6457       int IntField;
6458       ValidString &= !Fields[i].getAsInteger(10, IntField);
6459       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6460     }
6461 
6462     if (!ValidString)
6463       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6464              << Arg->getSourceRange();
6465   } else if (IsAArch64Builtin && Fields.size() == 1) {
6466     // If the register name is one of those that appear in the condition below
6467     // and the special register builtin being used is one of the write builtins,
6468     // then we require that the argument provided for writing to the register
6469     // is an integer constant expression. This is because it will be lowered to
6470     // an MSR (immediate) instruction, so we need to know the immediate at
6471     // compile time.
6472     if (TheCall->getNumArgs() != 2)
6473       return false;
6474 
6475     std::string RegLower = Reg.lower();
6476     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6477         RegLower != "pan" && RegLower != "uao")
6478       return false;
6479 
6480     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6481   }
6482 
6483   return false;
6484 }
6485 
6486 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6487 /// This checks that the target supports __builtin_longjmp and
6488 /// that val is a constant 1.
6489 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6490   if (!Context.getTargetInfo().hasSjLjLowering())
6491     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6492            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6493 
6494   Expr *Arg = TheCall->getArg(1);
6495   llvm::APSInt Result;
6496 
6497   // TODO: This is less than ideal. Overload this to take a value.
6498   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6499     return true;
6500 
6501   if (Result != 1)
6502     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6503            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6504 
6505   return false;
6506 }
6507 
6508 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6509 /// This checks that the target supports __builtin_setjmp.
6510 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6511   if (!Context.getTargetInfo().hasSjLjLowering())
6512     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6513            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6514   return false;
6515 }
6516 
6517 namespace {
6518 
6519 class UncoveredArgHandler {
6520   enum { Unknown = -1, AllCovered = -2 };
6521 
6522   signed FirstUncoveredArg = Unknown;
6523   SmallVector<const Expr *, 4> DiagnosticExprs;
6524 
6525 public:
6526   UncoveredArgHandler() = default;
6527 
6528   bool hasUncoveredArg() const {
6529     return (FirstUncoveredArg >= 0);
6530   }
6531 
6532   unsigned getUncoveredArg() const {
6533     assert(hasUncoveredArg() && "no uncovered argument");
6534     return FirstUncoveredArg;
6535   }
6536 
6537   void setAllCovered() {
6538     // A string has been found with all arguments covered, so clear out
6539     // the diagnostics.
6540     DiagnosticExprs.clear();
6541     FirstUncoveredArg = AllCovered;
6542   }
6543 
6544   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6545     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6546 
6547     // Don't update if a previous string covers all arguments.
6548     if (FirstUncoveredArg == AllCovered)
6549       return;
6550 
6551     // UncoveredArgHandler tracks the highest uncovered argument index
6552     // and with it all the strings that match this index.
6553     if (NewFirstUncoveredArg == FirstUncoveredArg)
6554       DiagnosticExprs.push_back(StrExpr);
6555     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6556       DiagnosticExprs.clear();
6557       DiagnosticExprs.push_back(StrExpr);
6558       FirstUncoveredArg = NewFirstUncoveredArg;
6559     }
6560   }
6561 
6562   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6563 };
6564 
6565 enum StringLiteralCheckType {
6566   SLCT_NotALiteral,
6567   SLCT_UncheckedLiteral,
6568   SLCT_CheckedLiteral
6569 };
6570 
6571 } // namespace
6572 
6573 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6574                                      BinaryOperatorKind BinOpKind,
6575                                      bool AddendIsRight) {
6576   unsigned BitWidth = Offset.getBitWidth();
6577   unsigned AddendBitWidth = Addend.getBitWidth();
6578   // There might be negative interim results.
6579   if (Addend.isUnsigned()) {
6580     Addend = Addend.zext(++AddendBitWidth);
6581     Addend.setIsSigned(true);
6582   }
6583   // Adjust the bit width of the APSInts.
6584   if (AddendBitWidth > BitWidth) {
6585     Offset = Offset.sext(AddendBitWidth);
6586     BitWidth = AddendBitWidth;
6587   } else if (BitWidth > AddendBitWidth) {
6588     Addend = Addend.sext(BitWidth);
6589   }
6590 
6591   bool Ov = false;
6592   llvm::APSInt ResOffset = Offset;
6593   if (BinOpKind == BO_Add)
6594     ResOffset = Offset.sadd_ov(Addend, Ov);
6595   else {
6596     assert(AddendIsRight && BinOpKind == BO_Sub &&
6597            "operator must be add or sub with addend on the right");
6598     ResOffset = Offset.ssub_ov(Addend, Ov);
6599   }
6600 
6601   // We add an offset to a pointer here so we should support an offset as big as
6602   // possible.
6603   if (Ov) {
6604     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6605            "index (intermediate) result too big");
6606     Offset = Offset.sext(2 * BitWidth);
6607     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6608     return;
6609   }
6610 
6611   Offset = ResOffset;
6612 }
6613 
6614 namespace {
6615 
6616 // This is a wrapper class around StringLiteral to support offsetted string
6617 // literals as format strings. It takes the offset into account when returning
6618 // the string and its length or the source locations to display notes correctly.
6619 class FormatStringLiteral {
6620   const StringLiteral *FExpr;
6621   int64_t Offset;
6622 
6623  public:
6624   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6625       : FExpr(fexpr), Offset(Offset) {}
6626 
6627   StringRef getString() const {
6628     return FExpr->getString().drop_front(Offset);
6629   }
6630 
6631   unsigned getByteLength() const {
6632     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6633   }
6634 
6635   unsigned getLength() const { return FExpr->getLength() - Offset; }
6636   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6637 
6638   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6639 
6640   QualType getType() const { return FExpr->getType(); }
6641 
6642   bool isAscii() const { return FExpr->isAscii(); }
6643   bool isWide() const { return FExpr->isWide(); }
6644   bool isUTF8() const { return FExpr->isUTF8(); }
6645   bool isUTF16() const { return FExpr->isUTF16(); }
6646   bool isUTF32() const { return FExpr->isUTF32(); }
6647   bool isPascal() const { return FExpr->isPascal(); }
6648 
6649   SourceLocation getLocationOfByte(
6650       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6651       const TargetInfo &Target, unsigned *StartToken = nullptr,
6652       unsigned *StartTokenByteOffset = nullptr) const {
6653     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6654                                     StartToken, StartTokenByteOffset);
6655   }
6656 
6657   SourceLocation getBeginLoc() const LLVM_READONLY {
6658     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6659   }
6660 
6661   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6662 };
6663 
6664 }  // namespace
6665 
6666 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6667                               const Expr *OrigFormatExpr,
6668                               ArrayRef<const Expr *> Args,
6669                               bool HasVAListArg, unsigned format_idx,
6670                               unsigned firstDataArg,
6671                               Sema::FormatStringType Type,
6672                               bool inFunctionCall,
6673                               Sema::VariadicCallType CallType,
6674                               llvm::SmallBitVector &CheckedVarArgs,
6675                               UncoveredArgHandler &UncoveredArg,
6676                               bool IgnoreStringsWithoutSpecifiers);
6677 
6678 // Determine if an expression is a string literal or constant string.
6679 // If this function returns false on the arguments to a function expecting a
6680 // format string, we will usually need to emit a warning.
6681 // True string literals are then checked by CheckFormatString.
6682 static StringLiteralCheckType
6683 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6684                       bool HasVAListArg, unsigned format_idx,
6685                       unsigned firstDataArg, Sema::FormatStringType Type,
6686                       Sema::VariadicCallType CallType, bool InFunctionCall,
6687                       llvm::SmallBitVector &CheckedVarArgs,
6688                       UncoveredArgHandler &UncoveredArg,
6689                       llvm::APSInt Offset,
6690                       bool IgnoreStringsWithoutSpecifiers = false) {
6691   if (S.isConstantEvaluated())
6692     return SLCT_NotALiteral;
6693  tryAgain:
6694   assert(Offset.isSigned() && "invalid offset");
6695 
6696   if (E->isTypeDependent() || E->isValueDependent())
6697     return SLCT_NotALiteral;
6698 
6699   E = E->IgnoreParenCasts();
6700 
6701   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6702     // Technically -Wformat-nonliteral does not warn about this case.
6703     // The behavior of printf and friends in this case is implementation
6704     // dependent.  Ideally if the format string cannot be null then
6705     // it should have a 'nonnull' attribute in the function prototype.
6706     return SLCT_UncheckedLiteral;
6707 
6708   switch (E->getStmtClass()) {
6709   case Stmt::BinaryConditionalOperatorClass:
6710   case Stmt::ConditionalOperatorClass: {
6711     // The expression is a literal if both sub-expressions were, and it was
6712     // completely checked only if both sub-expressions were checked.
6713     const AbstractConditionalOperator *C =
6714         cast<AbstractConditionalOperator>(E);
6715 
6716     // Determine whether it is necessary to check both sub-expressions, for
6717     // example, because the condition expression is a constant that can be
6718     // evaluated at compile time.
6719     bool CheckLeft = true, CheckRight = true;
6720 
6721     bool Cond;
6722     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6723                                                  S.isConstantEvaluated())) {
6724       if (Cond)
6725         CheckRight = false;
6726       else
6727         CheckLeft = false;
6728     }
6729 
6730     // We need to maintain the offsets for the right and the left hand side
6731     // separately to check if every possible indexed expression is a valid
6732     // string literal. They might have different offsets for different string
6733     // literals in the end.
6734     StringLiteralCheckType Left;
6735     if (!CheckLeft)
6736       Left = SLCT_UncheckedLiteral;
6737     else {
6738       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6739                                    HasVAListArg, format_idx, firstDataArg,
6740                                    Type, CallType, InFunctionCall,
6741                                    CheckedVarArgs, UncoveredArg, Offset,
6742                                    IgnoreStringsWithoutSpecifiers);
6743       if (Left == SLCT_NotALiteral || !CheckRight) {
6744         return Left;
6745       }
6746     }
6747 
6748     StringLiteralCheckType Right = checkFormatStringExpr(
6749         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6750         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6751         IgnoreStringsWithoutSpecifiers);
6752 
6753     return (CheckLeft && Left < Right) ? Left : Right;
6754   }
6755 
6756   case Stmt::ImplicitCastExprClass:
6757     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6758     goto tryAgain;
6759 
6760   case Stmt::OpaqueValueExprClass:
6761     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6762       E = src;
6763       goto tryAgain;
6764     }
6765     return SLCT_NotALiteral;
6766 
6767   case Stmt::PredefinedExprClass:
6768     // While __func__, etc., are technically not string literals, they
6769     // cannot contain format specifiers and thus are not a security
6770     // liability.
6771     return SLCT_UncheckedLiteral;
6772 
6773   case Stmt::DeclRefExprClass: {
6774     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6775 
6776     // As an exception, do not flag errors for variables binding to
6777     // const string literals.
6778     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6779       bool isConstant = false;
6780       QualType T = DR->getType();
6781 
6782       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6783         isConstant = AT->getElementType().isConstant(S.Context);
6784       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6785         isConstant = T.isConstant(S.Context) &&
6786                      PT->getPointeeType().isConstant(S.Context);
6787       } else if (T->isObjCObjectPointerType()) {
6788         // In ObjC, there is usually no "const ObjectPointer" type,
6789         // so don't check if the pointee type is constant.
6790         isConstant = T.isConstant(S.Context);
6791       }
6792 
6793       if (isConstant) {
6794         if (const Expr *Init = VD->getAnyInitializer()) {
6795           // Look through initializers like const char c[] = { "foo" }
6796           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6797             if (InitList->isStringLiteralInit())
6798               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6799           }
6800           return checkFormatStringExpr(S, Init, Args,
6801                                        HasVAListArg, format_idx,
6802                                        firstDataArg, Type, CallType,
6803                                        /*InFunctionCall*/ false, CheckedVarArgs,
6804                                        UncoveredArg, Offset);
6805         }
6806       }
6807 
6808       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6809       // special check to see if the format string is a function parameter
6810       // of the function calling the printf function.  If the function
6811       // has an attribute indicating it is a printf-like function, then we
6812       // should suppress warnings concerning non-literals being used in a call
6813       // to a vprintf function.  For example:
6814       //
6815       // void
6816       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6817       //      va_list ap;
6818       //      va_start(ap, fmt);
6819       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6820       //      ...
6821       // }
6822       if (HasVAListArg) {
6823         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6824           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6825             int PVIndex = PV->getFunctionScopeIndex() + 1;
6826             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6827               // adjust for implicit parameter
6828               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6829                 if (MD->isInstance())
6830                   ++PVIndex;
6831               // We also check if the formats are compatible.
6832               // We can't pass a 'scanf' string to a 'printf' function.
6833               if (PVIndex == PVFormat->getFormatIdx() &&
6834                   Type == S.GetFormatStringType(PVFormat))
6835                 return SLCT_UncheckedLiteral;
6836             }
6837           }
6838         }
6839       }
6840     }
6841 
6842     return SLCT_NotALiteral;
6843   }
6844 
6845   case Stmt::CallExprClass:
6846   case Stmt::CXXMemberCallExprClass: {
6847     const CallExpr *CE = cast<CallExpr>(E);
6848     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6849       bool IsFirst = true;
6850       StringLiteralCheckType CommonResult;
6851       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6852         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6853         StringLiteralCheckType Result = checkFormatStringExpr(
6854             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6855             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6856             IgnoreStringsWithoutSpecifiers);
6857         if (IsFirst) {
6858           CommonResult = Result;
6859           IsFirst = false;
6860         }
6861       }
6862       if (!IsFirst)
6863         return CommonResult;
6864 
6865       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6866         unsigned BuiltinID = FD->getBuiltinID();
6867         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6868             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6869           const Expr *Arg = CE->getArg(0);
6870           return checkFormatStringExpr(S, Arg, Args,
6871                                        HasVAListArg, format_idx,
6872                                        firstDataArg, Type, CallType,
6873                                        InFunctionCall, CheckedVarArgs,
6874                                        UncoveredArg, Offset,
6875                                        IgnoreStringsWithoutSpecifiers);
6876         }
6877       }
6878     }
6879 
6880     return SLCT_NotALiteral;
6881   }
6882   case Stmt::ObjCMessageExprClass: {
6883     const auto *ME = cast<ObjCMessageExpr>(E);
6884     if (const auto *MD = ME->getMethodDecl()) {
6885       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6886         // As a special case heuristic, if we're using the method -[NSBundle
6887         // localizedStringForKey:value:table:], ignore any key strings that lack
6888         // format specifiers. The idea is that if the key doesn't have any
6889         // format specifiers then its probably just a key to map to the
6890         // localized strings. If it does have format specifiers though, then its
6891         // likely that the text of the key is the format string in the
6892         // programmer's language, and should be checked.
6893         const ObjCInterfaceDecl *IFace;
6894         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6895             IFace->getIdentifier()->isStr("NSBundle") &&
6896             MD->getSelector().isKeywordSelector(
6897                 {"localizedStringForKey", "value", "table"})) {
6898           IgnoreStringsWithoutSpecifiers = true;
6899         }
6900 
6901         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6902         return checkFormatStringExpr(
6903             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6904             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6905             IgnoreStringsWithoutSpecifiers);
6906       }
6907     }
6908 
6909     return SLCT_NotALiteral;
6910   }
6911   case Stmt::ObjCStringLiteralClass:
6912   case Stmt::StringLiteralClass: {
6913     const StringLiteral *StrE = nullptr;
6914 
6915     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6916       StrE = ObjCFExpr->getString();
6917     else
6918       StrE = cast<StringLiteral>(E);
6919 
6920     if (StrE) {
6921       if (Offset.isNegative() || Offset > StrE->getLength()) {
6922         // TODO: It would be better to have an explicit warning for out of
6923         // bounds literals.
6924         return SLCT_NotALiteral;
6925       }
6926       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6927       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6928                         firstDataArg, Type, InFunctionCall, CallType,
6929                         CheckedVarArgs, UncoveredArg,
6930                         IgnoreStringsWithoutSpecifiers);
6931       return SLCT_CheckedLiteral;
6932     }
6933 
6934     return SLCT_NotALiteral;
6935   }
6936   case Stmt::BinaryOperatorClass: {
6937     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6938 
6939     // A string literal + an int offset is still a string literal.
6940     if (BinOp->isAdditiveOp()) {
6941       Expr::EvalResult LResult, RResult;
6942 
6943       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6944           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6945       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6946           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6947 
6948       if (LIsInt != RIsInt) {
6949         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6950 
6951         if (LIsInt) {
6952           if (BinOpKind == BO_Add) {
6953             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6954             E = BinOp->getRHS();
6955             goto tryAgain;
6956           }
6957         } else {
6958           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6959           E = BinOp->getLHS();
6960           goto tryAgain;
6961         }
6962       }
6963     }
6964 
6965     return SLCT_NotALiteral;
6966   }
6967   case Stmt::UnaryOperatorClass: {
6968     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6969     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6970     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6971       Expr::EvalResult IndexResult;
6972       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6973                                        Expr::SE_NoSideEffects,
6974                                        S.isConstantEvaluated())) {
6975         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6976                    /*RHS is int*/ true);
6977         E = ASE->getBase();
6978         goto tryAgain;
6979       }
6980     }
6981 
6982     return SLCT_NotALiteral;
6983   }
6984 
6985   default:
6986     return SLCT_NotALiteral;
6987   }
6988 }
6989 
6990 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6991   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6992       .Case("scanf", FST_Scanf)
6993       .Cases("printf", "printf0", FST_Printf)
6994       .Cases("NSString", "CFString", FST_NSString)
6995       .Case("strftime", FST_Strftime)
6996       .Case("strfmon", FST_Strfmon)
6997       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6998       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6999       .Case("os_trace", FST_OSLog)
7000       .Case("os_log", FST_OSLog)
7001       .Default(FST_Unknown);
7002 }
7003 
7004 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7005 /// functions) for correct use of format strings.
7006 /// Returns true if a format string has been fully checked.
7007 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7008                                 ArrayRef<const Expr *> Args,
7009                                 bool IsCXXMember,
7010                                 VariadicCallType CallType,
7011                                 SourceLocation Loc, SourceRange Range,
7012                                 llvm::SmallBitVector &CheckedVarArgs) {
7013   FormatStringInfo FSI;
7014   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7015     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7016                                 FSI.FirstDataArg, GetFormatStringType(Format),
7017                                 CallType, Loc, Range, CheckedVarArgs);
7018   return false;
7019 }
7020 
7021 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7022                                 bool HasVAListArg, unsigned format_idx,
7023                                 unsigned firstDataArg, FormatStringType Type,
7024                                 VariadicCallType CallType,
7025                                 SourceLocation Loc, SourceRange Range,
7026                                 llvm::SmallBitVector &CheckedVarArgs) {
7027   // CHECK: printf/scanf-like function is called with no format string.
7028   if (format_idx >= Args.size()) {
7029     Diag(Loc, diag::warn_missing_format_string) << Range;
7030     return false;
7031   }
7032 
7033   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7034 
7035   // CHECK: format string is not a string literal.
7036   //
7037   // Dynamically generated format strings are difficult to
7038   // automatically vet at compile time.  Requiring that format strings
7039   // are string literals: (1) permits the checking of format strings by
7040   // the compiler and thereby (2) can practically remove the source of
7041   // many format string exploits.
7042 
7043   // Format string can be either ObjC string (e.g. @"%d") or
7044   // C string (e.g. "%d")
7045   // ObjC string uses the same format specifiers as C string, so we can use
7046   // the same format string checking logic for both ObjC and C strings.
7047   UncoveredArgHandler UncoveredArg;
7048   StringLiteralCheckType CT =
7049       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7050                             format_idx, firstDataArg, Type, CallType,
7051                             /*IsFunctionCall*/ true, CheckedVarArgs,
7052                             UncoveredArg,
7053                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7054 
7055   // Generate a diagnostic where an uncovered argument is detected.
7056   if (UncoveredArg.hasUncoveredArg()) {
7057     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7058     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7059     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7060   }
7061 
7062   if (CT != SLCT_NotALiteral)
7063     // Literal format string found, check done!
7064     return CT == SLCT_CheckedLiteral;
7065 
7066   // Strftime is particular as it always uses a single 'time' argument,
7067   // so it is safe to pass a non-literal string.
7068   if (Type == FST_Strftime)
7069     return false;
7070 
7071   // Do not emit diag when the string param is a macro expansion and the
7072   // format is either NSString or CFString. This is a hack to prevent
7073   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7074   // which are usually used in place of NS and CF string literals.
7075   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7076   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7077     return false;
7078 
7079   // If there are no arguments specified, warn with -Wformat-security, otherwise
7080   // warn only with -Wformat-nonliteral.
7081   if (Args.size() == firstDataArg) {
7082     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7083       << OrigFormatExpr->getSourceRange();
7084     switch (Type) {
7085     default:
7086       break;
7087     case FST_Kprintf:
7088     case FST_FreeBSDKPrintf:
7089     case FST_Printf:
7090       Diag(FormatLoc, diag::note_format_security_fixit)
7091         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7092       break;
7093     case FST_NSString:
7094       Diag(FormatLoc, diag::note_format_security_fixit)
7095         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7096       break;
7097     }
7098   } else {
7099     Diag(FormatLoc, diag::warn_format_nonliteral)
7100       << OrigFormatExpr->getSourceRange();
7101   }
7102   return false;
7103 }
7104 
7105 namespace {
7106 
7107 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7108 protected:
7109   Sema &S;
7110   const FormatStringLiteral *FExpr;
7111   const Expr *OrigFormatExpr;
7112   const Sema::FormatStringType FSType;
7113   const unsigned FirstDataArg;
7114   const unsigned NumDataArgs;
7115   const char *Beg; // Start of format string.
7116   const bool HasVAListArg;
7117   ArrayRef<const Expr *> Args;
7118   unsigned FormatIdx;
7119   llvm::SmallBitVector CoveredArgs;
7120   bool usesPositionalArgs = false;
7121   bool atFirstArg = true;
7122   bool inFunctionCall;
7123   Sema::VariadicCallType CallType;
7124   llvm::SmallBitVector &CheckedVarArgs;
7125   UncoveredArgHandler &UncoveredArg;
7126 
7127 public:
7128   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7129                      const Expr *origFormatExpr,
7130                      const Sema::FormatStringType type, unsigned firstDataArg,
7131                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7132                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7133                      bool inFunctionCall, Sema::VariadicCallType callType,
7134                      llvm::SmallBitVector &CheckedVarArgs,
7135                      UncoveredArgHandler &UncoveredArg)
7136       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7137         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7138         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7139         inFunctionCall(inFunctionCall), CallType(callType),
7140         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7141     CoveredArgs.resize(numDataArgs);
7142     CoveredArgs.reset();
7143   }
7144 
7145   void DoneProcessing();
7146 
7147   void HandleIncompleteSpecifier(const char *startSpecifier,
7148                                  unsigned specifierLen) override;
7149 
7150   void HandleInvalidLengthModifier(
7151                            const analyze_format_string::FormatSpecifier &FS,
7152                            const analyze_format_string::ConversionSpecifier &CS,
7153                            const char *startSpecifier, unsigned specifierLen,
7154                            unsigned DiagID);
7155 
7156   void HandleNonStandardLengthModifier(
7157                     const analyze_format_string::FormatSpecifier &FS,
7158                     const char *startSpecifier, unsigned specifierLen);
7159 
7160   void HandleNonStandardConversionSpecifier(
7161                     const analyze_format_string::ConversionSpecifier &CS,
7162                     const char *startSpecifier, unsigned specifierLen);
7163 
7164   void HandlePosition(const char *startPos, unsigned posLen) override;
7165 
7166   void HandleInvalidPosition(const char *startSpecifier,
7167                              unsigned specifierLen,
7168                              analyze_format_string::PositionContext p) override;
7169 
7170   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7171 
7172   void HandleNullChar(const char *nullCharacter) override;
7173 
7174   template <typename Range>
7175   static void
7176   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7177                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7178                        bool IsStringLocation, Range StringRange,
7179                        ArrayRef<FixItHint> Fixit = None);
7180 
7181 protected:
7182   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7183                                         const char *startSpec,
7184                                         unsigned specifierLen,
7185                                         const char *csStart, unsigned csLen);
7186 
7187   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7188                                          const char *startSpec,
7189                                          unsigned specifierLen);
7190 
7191   SourceRange getFormatStringRange();
7192   CharSourceRange getSpecifierRange(const char *startSpecifier,
7193                                     unsigned specifierLen);
7194   SourceLocation getLocationOfByte(const char *x);
7195 
7196   const Expr *getDataArg(unsigned i) const;
7197 
7198   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7199                     const analyze_format_string::ConversionSpecifier &CS,
7200                     const char *startSpecifier, unsigned specifierLen,
7201                     unsigned argIndex);
7202 
7203   template <typename Range>
7204   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7205                             bool IsStringLocation, Range StringRange,
7206                             ArrayRef<FixItHint> Fixit = None);
7207 };
7208 
7209 } // namespace
7210 
7211 SourceRange CheckFormatHandler::getFormatStringRange() {
7212   return OrigFormatExpr->getSourceRange();
7213 }
7214 
7215 CharSourceRange CheckFormatHandler::
7216 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7217   SourceLocation Start = getLocationOfByte(startSpecifier);
7218   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7219 
7220   // Advance the end SourceLocation by one due to half-open ranges.
7221   End = End.getLocWithOffset(1);
7222 
7223   return CharSourceRange::getCharRange(Start, End);
7224 }
7225 
7226 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7227   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7228                                   S.getLangOpts(), S.Context.getTargetInfo());
7229 }
7230 
7231 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7232                                                    unsigned specifierLen){
7233   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7234                        getLocationOfByte(startSpecifier),
7235                        /*IsStringLocation*/true,
7236                        getSpecifierRange(startSpecifier, specifierLen));
7237 }
7238 
7239 void CheckFormatHandler::HandleInvalidLengthModifier(
7240     const analyze_format_string::FormatSpecifier &FS,
7241     const analyze_format_string::ConversionSpecifier &CS,
7242     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7243   using namespace analyze_format_string;
7244 
7245   const LengthModifier &LM = FS.getLengthModifier();
7246   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7247 
7248   // See if we know how to fix this length modifier.
7249   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7250   if (FixedLM) {
7251     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7252                          getLocationOfByte(LM.getStart()),
7253                          /*IsStringLocation*/true,
7254                          getSpecifierRange(startSpecifier, specifierLen));
7255 
7256     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7257       << FixedLM->toString()
7258       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7259 
7260   } else {
7261     FixItHint Hint;
7262     if (DiagID == diag::warn_format_nonsensical_length)
7263       Hint = FixItHint::CreateRemoval(LMRange);
7264 
7265     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7266                          getLocationOfByte(LM.getStart()),
7267                          /*IsStringLocation*/true,
7268                          getSpecifierRange(startSpecifier, specifierLen),
7269                          Hint);
7270   }
7271 }
7272 
7273 void CheckFormatHandler::HandleNonStandardLengthModifier(
7274     const analyze_format_string::FormatSpecifier &FS,
7275     const char *startSpecifier, unsigned specifierLen) {
7276   using namespace analyze_format_string;
7277 
7278   const LengthModifier &LM = FS.getLengthModifier();
7279   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7280 
7281   // See if we know how to fix this length modifier.
7282   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7283   if (FixedLM) {
7284     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7285                            << LM.toString() << 0,
7286                          getLocationOfByte(LM.getStart()),
7287                          /*IsStringLocation*/true,
7288                          getSpecifierRange(startSpecifier, specifierLen));
7289 
7290     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7291       << FixedLM->toString()
7292       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7293 
7294   } else {
7295     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7296                            << LM.toString() << 0,
7297                          getLocationOfByte(LM.getStart()),
7298                          /*IsStringLocation*/true,
7299                          getSpecifierRange(startSpecifier, specifierLen));
7300   }
7301 }
7302 
7303 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7304     const analyze_format_string::ConversionSpecifier &CS,
7305     const char *startSpecifier, unsigned specifierLen) {
7306   using namespace analyze_format_string;
7307 
7308   // See if we know how to fix this conversion specifier.
7309   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7310   if (FixedCS) {
7311     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7312                           << CS.toString() << /*conversion specifier*/1,
7313                          getLocationOfByte(CS.getStart()),
7314                          /*IsStringLocation*/true,
7315                          getSpecifierRange(startSpecifier, specifierLen));
7316 
7317     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7318     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7319       << FixedCS->toString()
7320       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7321   } else {
7322     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7323                           << CS.toString() << /*conversion specifier*/1,
7324                          getLocationOfByte(CS.getStart()),
7325                          /*IsStringLocation*/true,
7326                          getSpecifierRange(startSpecifier, specifierLen));
7327   }
7328 }
7329 
7330 void CheckFormatHandler::HandlePosition(const char *startPos,
7331                                         unsigned posLen) {
7332   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7333                                getLocationOfByte(startPos),
7334                                /*IsStringLocation*/true,
7335                                getSpecifierRange(startPos, posLen));
7336 }
7337 
7338 void
7339 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7340                                      analyze_format_string::PositionContext p) {
7341   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7342                          << (unsigned) p,
7343                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7344                        getSpecifierRange(startPos, posLen));
7345 }
7346 
7347 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7348                                             unsigned posLen) {
7349   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7350                                getLocationOfByte(startPos),
7351                                /*IsStringLocation*/true,
7352                                getSpecifierRange(startPos, posLen));
7353 }
7354 
7355 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7356   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7357     // The presence of a null character is likely an error.
7358     EmitFormatDiagnostic(
7359       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7360       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7361       getFormatStringRange());
7362   }
7363 }
7364 
7365 // Note that this may return NULL if there was an error parsing or building
7366 // one of the argument expressions.
7367 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7368   return Args[FirstDataArg + i];
7369 }
7370 
7371 void CheckFormatHandler::DoneProcessing() {
7372   // Does the number of data arguments exceed the number of
7373   // format conversions in the format string?
7374   if (!HasVAListArg) {
7375       // Find any arguments that weren't covered.
7376     CoveredArgs.flip();
7377     signed notCoveredArg = CoveredArgs.find_first();
7378     if (notCoveredArg >= 0) {
7379       assert((unsigned)notCoveredArg < NumDataArgs);
7380       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7381     } else {
7382       UncoveredArg.setAllCovered();
7383     }
7384   }
7385 }
7386 
7387 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7388                                    const Expr *ArgExpr) {
7389   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7390          "Invalid state");
7391 
7392   if (!ArgExpr)
7393     return;
7394 
7395   SourceLocation Loc = ArgExpr->getBeginLoc();
7396 
7397   if (S.getSourceManager().isInSystemMacro(Loc))
7398     return;
7399 
7400   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7401   for (auto E : DiagnosticExprs)
7402     PDiag << E->getSourceRange();
7403 
7404   CheckFormatHandler::EmitFormatDiagnostic(
7405                                   S, IsFunctionCall, DiagnosticExprs[0],
7406                                   PDiag, Loc, /*IsStringLocation*/false,
7407                                   DiagnosticExprs[0]->getSourceRange());
7408 }
7409 
7410 bool
7411 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7412                                                      SourceLocation Loc,
7413                                                      const char *startSpec,
7414                                                      unsigned specifierLen,
7415                                                      const char *csStart,
7416                                                      unsigned csLen) {
7417   bool keepGoing = true;
7418   if (argIndex < NumDataArgs) {
7419     // Consider the argument coverered, even though the specifier doesn't
7420     // make sense.
7421     CoveredArgs.set(argIndex);
7422   }
7423   else {
7424     // If argIndex exceeds the number of data arguments we
7425     // don't issue a warning because that is just a cascade of warnings (and
7426     // they may have intended '%%' anyway). We don't want to continue processing
7427     // the format string after this point, however, as we will like just get
7428     // gibberish when trying to match arguments.
7429     keepGoing = false;
7430   }
7431 
7432   StringRef Specifier(csStart, csLen);
7433 
7434   // If the specifier in non-printable, it could be the first byte of a UTF-8
7435   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7436   // hex value.
7437   std::string CodePointStr;
7438   if (!llvm::sys::locale::isPrint(*csStart)) {
7439     llvm::UTF32 CodePoint;
7440     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7441     const llvm::UTF8 *E =
7442         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7443     llvm::ConversionResult Result =
7444         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7445 
7446     if (Result != llvm::conversionOK) {
7447       unsigned char FirstChar = *csStart;
7448       CodePoint = (llvm::UTF32)FirstChar;
7449     }
7450 
7451     llvm::raw_string_ostream OS(CodePointStr);
7452     if (CodePoint < 256)
7453       OS << "\\x" << llvm::format("%02x", CodePoint);
7454     else if (CodePoint <= 0xFFFF)
7455       OS << "\\u" << llvm::format("%04x", CodePoint);
7456     else
7457       OS << "\\U" << llvm::format("%08x", CodePoint);
7458     OS.flush();
7459     Specifier = CodePointStr;
7460   }
7461 
7462   EmitFormatDiagnostic(
7463       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7464       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7465 
7466   return keepGoing;
7467 }
7468 
7469 void
7470 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7471                                                       const char *startSpec,
7472                                                       unsigned specifierLen) {
7473   EmitFormatDiagnostic(
7474     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7475     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7476 }
7477 
7478 bool
7479 CheckFormatHandler::CheckNumArgs(
7480   const analyze_format_string::FormatSpecifier &FS,
7481   const analyze_format_string::ConversionSpecifier &CS,
7482   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7483 
7484   if (argIndex >= NumDataArgs) {
7485     PartialDiagnostic PDiag = FS.usesPositionalArg()
7486       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7487            << (argIndex+1) << NumDataArgs)
7488       : S.PDiag(diag::warn_printf_insufficient_data_args);
7489     EmitFormatDiagnostic(
7490       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7491       getSpecifierRange(startSpecifier, specifierLen));
7492 
7493     // Since more arguments than conversion tokens are given, by extension
7494     // all arguments are covered, so mark this as so.
7495     UncoveredArg.setAllCovered();
7496     return false;
7497   }
7498   return true;
7499 }
7500 
7501 template<typename Range>
7502 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7503                                               SourceLocation Loc,
7504                                               bool IsStringLocation,
7505                                               Range StringRange,
7506                                               ArrayRef<FixItHint> FixIt) {
7507   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7508                        Loc, IsStringLocation, StringRange, FixIt);
7509 }
7510 
7511 /// If the format string is not within the function call, emit a note
7512 /// so that the function call and string are in diagnostic messages.
7513 ///
7514 /// \param InFunctionCall if true, the format string is within the function
7515 /// call and only one diagnostic message will be produced.  Otherwise, an
7516 /// extra note will be emitted pointing to location of the format string.
7517 ///
7518 /// \param ArgumentExpr the expression that is passed as the format string
7519 /// argument in the function call.  Used for getting locations when two
7520 /// diagnostics are emitted.
7521 ///
7522 /// \param PDiag the callee should already have provided any strings for the
7523 /// diagnostic message.  This function only adds locations and fixits
7524 /// to diagnostics.
7525 ///
7526 /// \param Loc primary location for diagnostic.  If two diagnostics are
7527 /// required, one will be at Loc and a new SourceLocation will be created for
7528 /// the other one.
7529 ///
7530 /// \param IsStringLocation if true, Loc points to the format string should be
7531 /// used for the note.  Otherwise, Loc points to the argument list and will
7532 /// be used with PDiag.
7533 ///
7534 /// \param StringRange some or all of the string to highlight.  This is
7535 /// templated so it can accept either a CharSourceRange or a SourceRange.
7536 ///
7537 /// \param FixIt optional fix it hint for the format string.
7538 template <typename Range>
7539 void CheckFormatHandler::EmitFormatDiagnostic(
7540     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7541     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7542     Range StringRange, ArrayRef<FixItHint> FixIt) {
7543   if (InFunctionCall) {
7544     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7545     D << StringRange;
7546     D << FixIt;
7547   } else {
7548     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7549       << ArgumentExpr->getSourceRange();
7550 
7551     const Sema::SemaDiagnosticBuilder &Note =
7552       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7553              diag::note_format_string_defined);
7554 
7555     Note << StringRange;
7556     Note << FixIt;
7557   }
7558 }
7559 
7560 //===--- CHECK: Printf format string checking ------------------------------===//
7561 
7562 namespace {
7563 
7564 class CheckPrintfHandler : public CheckFormatHandler {
7565 public:
7566   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7567                      const Expr *origFormatExpr,
7568                      const Sema::FormatStringType type, unsigned firstDataArg,
7569                      unsigned numDataArgs, bool isObjC, const char *beg,
7570                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7571                      unsigned formatIdx, bool inFunctionCall,
7572                      Sema::VariadicCallType CallType,
7573                      llvm::SmallBitVector &CheckedVarArgs,
7574                      UncoveredArgHandler &UncoveredArg)
7575       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7576                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7577                            inFunctionCall, CallType, CheckedVarArgs,
7578                            UncoveredArg) {}
7579 
7580   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7581 
7582   /// Returns true if '%@' specifiers are allowed in the format string.
7583   bool allowsObjCArg() const {
7584     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7585            FSType == Sema::FST_OSTrace;
7586   }
7587 
7588   bool HandleInvalidPrintfConversionSpecifier(
7589                                       const analyze_printf::PrintfSpecifier &FS,
7590                                       const char *startSpecifier,
7591                                       unsigned specifierLen) override;
7592 
7593   void handleInvalidMaskType(StringRef MaskType) override;
7594 
7595   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7596                              const char *startSpecifier,
7597                              unsigned specifierLen) override;
7598   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7599                        const char *StartSpecifier,
7600                        unsigned SpecifierLen,
7601                        const Expr *E);
7602 
7603   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7604                     const char *startSpecifier, unsigned specifierLen);
7605   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7606                            const analyze_printf::OptionalAmount &Amt,
7607                            unsigned type,
7608                            const char *startSpecifier, unsigned specifierLen);
7609   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7610                   const analyze_printf::OptionalFlag &flag,
7611                   const char *startSpecifier, unsigned specifierLen);
7612   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7613                          const analyze_printf::OptionalFlag &ignoredFlag,
7614                          const analyze_printf::OptionalFlag &flag,
7615                          const char *startSpecifier, unsigned specifierLen);
7616   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7617                            const Expr *E);
7618 
7619   void HandleEmptyObjCModifierFlag(const char *startFlag,
7620                                    unsigned flagLen) override;
7621 
7622   void HandleInvalidObjCModifierFlag(const char *startFlag,
7623                                             unsigned flagLen) override;
7624 
7625   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7626                                            const char *flagsEnd,
7627                                            const char *conversionPosition)
7628                                              override;
7629 };
7630 
7631 } // namespace
7632 
7633 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7634                                       const analyze_printf::PrintfSpecifier &FS,
7635                                       const char *startSpecifier,
7636                                       unsigned specifierLen) {
7637   const analyze_printf::PrintfConversionSpecifier &CS =
7638     FS.getConversionSpecifier();
7639 
7640   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7641                                           getLocationOfByte(CS.getStart()),
7642                                           startSpecifier, specifierLen,
7643                                           CS.getStart(), CS.getLength());
7644 }
7645 
7646 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7647   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7648 }
7649 
7650 bool CheckPrintfHandler::HandleAmount(
7651                                const analyze_format_string::OptionalAmount &Amt,
7652                                unsigned k, const char *startSpecifier,
7653                                unsigned specifierLen) {
7654   if (Amt.hasDataArgument()) {
7655     if (!HasVAListArg) {
7656       unsigned argIndex = Amt.getArgIndex();
7657       if (argIndex >= NumDataArgs) {
7658         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7659                                << k,
7660                              getLocationOfByte(Amt.getStart()),
7661                              /*IsStringLocation*/true,
7662                              getSpecifierRange(startSpecifier, specifierLen));
7663         // Don't do any more checking.  We will just emit
7664         // spurious errors.
7665         return false;
7666       }
7667 
7668       // Type check the data argument.  It should be an 'int'.
7669       // Although not in conformance with C99, we also allow the argument to be
7670       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7671       // doesn't emit a warning for that case.
7672       CoveredArgs.set(argIndex);
7673       const Expr *Arg = getDataArg(argIndex);
7674       if (!Arg)
7675         return false;
7676 
7677       QualType T = Arg->getType();
7678 
7679       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7680       assert(AT.isValid());
7681 
7682       if (!AT.matchesType(S.Context, T)) {
7683         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7684                                << k << AT.getRepresentativeTypeName(S.Context)
7685                                << T << Arg->getSourceRange(),
7686                              getLocationOfByte(Amt.getStart()),
7687                              /*IsStringLocation*/true,
7688                              getSpecifierRange(startSpecifier, specifierLen));
7689         // Don't do any more checking.  We will just emit
7690         // spurious errors.
7691         return false;
7692       }
7693     }
7694   }
7695   return true;
7696 }
7697 
7698 void CheckPrintfHandler::HandleInvalidAmount(
7699                                       const analyze_printf::PrintfSpecifier &FS,
7700                                       const analyze_printf::OptionalAmount &Amt,
7701                                       unsigned type,
7702                                       const char *startSpecifier,
7703                                       unsigned specifierLen) {
7704   const analyze_printf::PrintfConversionSpecifier &CS =
7705     FS.getConversionSpecifier();
7706 
7707   FixItHint fixit =
7708     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7709       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7710                                  Amt.getConstantLength()))
7711       : FixItHint();
7712 
7713   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7714                          << type << CS.toString(),
7715                        getLocationOfByte(Amt.getStart()),
7716                        /*IsStringLocation*/true,
7717                        getSpecifierRange(startSpecifier, specifierLen),
7718                        fixit);
7719 }
7720 
7721 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7722                                     const analyze_printf::OptionalFlag &flag,
7723                                     const char *startSpecifier,
7724                                     unsigned specifierLen) {
7725   // Warn about pointless flag with a fixit removal.
7726   const analyze_printf::PrintfConversionSpecifier &CS =
7727     FS.getConversionSpecifier();
7728   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7729                          << flag.toString() << CS.toString(),
7730                        getLocationOfByte(flag.getPosition()),
7731                        /*IsStringLocation*/true,
7732                        getSpecifierRange(startSpecifier, specifierLen),
7733                        FixItHint::CreateRemoval(
7734                          getSpecifierRange(flag.getPosition(), 1)));
7735 }
7736 
7737 void CheckPrintfHandler::HandleIgnoredFlag(
7738                                 const analyze_printf::PrintfSpecifier &FS,
7739                                 const analyze_printf::OptionalFlag &ignoredFlag,
7740                                 const analyze_printf::OptionalFlag &flag,
7741                                 const char *startSpecifier,
7742                                 unsigned specifierLen) {
7743   // Warn about ignored flag with a fixit removal.
7744   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7745                          << ignoredFlag.toString() << flag.toString(),
7746                        getLocationOfByte(ignoredFlag.getPosition()),
7747                        /*IsStringLocation*/true,
7748                        getSpecifierRange(startSpecifier, specifierLen),
7749                        FixItHint::CreateRemoval(
7750                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7751 }
7752 
7753 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7754                                                      unsigned flagLen) {
7755   // Warn about an empty flag.
7756   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7757                        getLocationOfByte(startFlag),
7758                        /*IsStringLocation*/true,
7759                        getSpecifierRange(startFlag, flagLen));
7760 }
7761 
7762 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7763                                                        unsigned flagLen) {
7764   // Warn about an invalid flag.
7765   auto Range = getSpecifierRange(startFlag, flagLen);
7766   StringRef flag(startFlag, flagLen);
7767   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7768                       getLocationOfByte(startFlag),
7769                       /*IsStringLocation*/true,
7770                       Range, FixItHint::CreateRemoval(Range));
7771 }
7772 
7773 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7774     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7775     // Warn about using '[...]' without a '@' conversion.
7776     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7777     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7778     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7779                          getLocationOfByte(conversionPosition),
7780                          /*IsStringLocation*/true,
7781                          Range, FixItHint::CreateRemoval(Range));
7782 }
7783 
7784 // Determines if the specified is a C++ class or struct containing
7785 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7786 // "c_str()").
7787 template<typename MemberKind>
7788 static llvm::SmallPtrSet<MemberKind*, 1>
7789 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7790   const RecordType *RT = Ty->getAs<RecordType>();
7791   llvm::SmallPtrSet<MemberKind*, 1> Results;
7792 
7793   if (!RT)
7794     return Results;
7795   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7796   if (!RD || !RD->getDefinition())
7797     return Results;
7798 
7799   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7800                  Sema::LookupMemberName);
7801   R.suppressDiagnostics();
7802 
7803   // We just need to include all members of the right kind turned up by the
7804   // filter, at this point.
7805   if (S.LookupQualifiedName(R, RT->getDecl()))
7806     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7807       NamedDecl *decl = (*I)->getUnderlyingDecl();
7808       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7809         Results.insert(FK);
7810     }
7811   return Results;
7812 }
7813 
7814 /// Check if we could call '.c_str()' on an object.
7815 ///
7816 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7817 /// allow the call, or if it would be ambiguous).
7818 bool Sema::hasCStrMethod(const Expr *E) {
7819   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7820 
7821   MethodSet Results =
7822       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7823   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7824        MI != ME; ++MI)
7825     if ((*MI)->getMinRequiredArguments() == 0)
7826       return true;
7827   return false;
7828 }
7829 
7830 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7831 // better diagnostic if so. AT is assumed to be valid.
7832 // Returns true when a c_str() conversion method is found.
7833 bool CheckPrintfHandler::checkForCStrMembers(
7834     const analyze_printf::ArgType &AT, const Expr *E) {
7835   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7836 
7837   MethodSet Results =
7838       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7839 
7840   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7841        MI != ME; ++MI) {
7842     const CXXMethodDecl *Method = *MI;
7843     if (Method->getMinRequiredArguments() == 0 &&
7844         AT.matchesType(S.Context, Method->getReturnType())) {
7845       // FIXME: Suggest parens if the expression needs them.
7846       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7847       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7848           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7849       return true;
7850     }
7851   }
7852 
7853   return false;
7854 }
7855 
7856 bool
7857 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7858                                             &FS,
7859                                           const char *startSpecifier,
7860                                           unsigned specifierLen) {
7861   using namespace analyze_format_string;
7862   using namespace analyze_printf;
7863 
7864   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7865 
7866   if (FS.consumesDataArgument()) {
7867     if (atFirstArg) {
7868         atFirstArg = false;
7869         usesPositionalArgs = FS.usesPositionalArg();
7870     }
7871     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7872       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7873                                         startSpecifier, specifierLen);
7874       return false;
7875     }
7876   }
7877 
7878   // First check if the field width, precision, and conversion specifier
7879   // have matching data arguments.
7880   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7881                     startSpecifier, specifierLen)) {
7882     return false;
7883   }
7884 
7885   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7886                     startSpecifier, specifierLen)) {
7887     return false;
7888   }
7889 
7890   if (!CS.consumesDataArgument()) {
7891     // FIXME: Technically specifying a precision or field width here
7892     // makes no sense.  Worth issuing a warning at some point.
7893     return true;
7894   }
7895 
7896   // Consume the argument.
7897   unsigned argIndex = FS.getArgIndex();
7898   if (argIndex < NumDataArgs) {
7899     // The check to see if the argIndex is valid will come later.
7900     // We set the bit here because we may exit early from this
7901     // function if we encounter some other error.
7902     CoveredArgs.set(argIndex);
7903   }
7904 
7905   // FreeBSD kernel extensions.
7906   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7907       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7908     // We need at least two arguments.
7909     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7910       return false;
7911 
7912     // Claim the second argument.
7913     CoveredArgs.set(argIndex + 1);
7914 
7915     // Type check the first argument (int for %b, pointer for %D)
7916     const Expr *Ex = getDataArg(argIndex);
7917     const analyze_printf::ArgType &AT =
7918       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7919         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7920     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7921       EmitFormatDiagnostic(
7922           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7923               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7924               << false << Ex->getSourceRange(),
7925           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7926           getSpecifierRange(startSpecifier, specifierLen));
7927 
7928     // Type check the second argument (char * for both %b and %D)
7929     Ex = getDataArg(argIndex + 1);
7930     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7931     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7932       EmitFormatDiagnostic(
7933           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7934               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7935               << false << Ex->getSourceRange(),
7936           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7937           getSpecifierRange(startSpecifier, specifierLen));
7938 
7939      return true;
7940   }
7941 
7942   // Check for using an Objective-C specific conversion specifier
7943   // in a non-ObjC literal.
7944   if (!allowsObjCArg() && CS.isObjCArg()) {
7945     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7946                                                   specifierLen);
7947   }
7948 
7949   // %P can only be used with os_log.
7950   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7951     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7952                                                   specifierLen);
7953   }
7954 
7955   // %n is not allowed with os_log.
7956   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7957     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7958                          getLocationOfByte(CS.getStart()),
7959                          /*IsStringLocation*/ false,
7960                          getSpecifierRange(startSpecifier, specifierLen));
7961 
7962     return true;
7963   }
7964 
7965   // Only scalars are allowed for os_trace.
7966   if (FSType == Sema::FST_OSTrace &&
7967       (CS.getKind() == ConversionSpecifier::PArg ||
7968        CS.getKind() == ConversionSpecifier::sArg ||
7969        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7970     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7971                                                   specifierLen);
7972   }
7973 
7974   // Check for use of public/private annotation outside of os_log().
7975   if (FSType != Sema::FST_OSLog) {
7976     if (FS.isPublic().isSet()) {
7977       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7978                                << "public",
7979                            getLocationOfByte(FS.isPublic().getPosition()),
7980                            /*IsStringLocation*/ false,
7981                            getSpecifierRange(startSpecifier, specifierLen));
7982     }
7983     if (FS.isPrivate().isSet()) {
7984       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7985                                << "private",
7986                            getLocationOfByte(FS.isPrivate().getPosition()),
7987                            /*IsStringLocation*/ false,
7988                            getSpecifierRange(startSpecifier, specifierLen));
7989     }
7990   }
7991 
7992   // Check for invalid use of field width
7993   if (!FS.hasValidFieldWidth()) {
7994     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7995         startSpecifier, specifierLen);
7996   }
7997 
7998   // Check for invalid use of precision
7999   if (!FS.hasValidPrecision()) {
8000     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8001         startSpecifier, specifierLen);
8002   }
8003 
8004   // Precision is mandatory for %P specifier.
8005   if (CS.getKind() == ConversionSpecifier::PArg &&
8006       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8007     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8008                          getLocationOfByte(startSpecifier),
8009                          /*IsStringLocation*/ false,
8010                          getSpecifierRange(startSpecifier, specifierLen));
8011   }
8012 
8013   // Check each flag does not conflict with any other component.
8014   if (!FS.hasValidThousandsGroupingPrefix())
8015     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8016   if (!FS.hasValidLeadingZeros())
8017     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8018   if (!FS.hasValidPlusPrefix())
8019     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8020   if (!FS.hasValidSpacePrefix())
8021     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8022   if (!FS.hasValidAlternativeForm())
8023     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8024   if (!FS.hasValidLeftJustified())
8025     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8026 
8027   // Check that flags are not ignored by another flag
8028   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8029     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8030         startSpecifier, specifierLen);
8031   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8032     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8033             startSpecifier, specifierLen);
8034 
8035   // Check the length modifier is valid with the given conversion specifier.
8036   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8037                                  S.getLangOpts()))
8038     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8039                                 diag::warn_format_nonsensical_length);
8040   else if (!FS.hasStandardLengthModifier())
8041     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8042   else if (!FS.hasStandardLengthConversionCombination())
8043     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8044                                 diag::warn_format_non_standard_conversion_spec);
8045 
8046   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8047     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8048 
8049   // The remaining checks depend on the data arguments.
8050   if (HasVAListArg)
8051     return true;
8052 
8053   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8054     return false;
8055 
8056   const Expr *Arg = getDataArg(argIndex);
8057   if (!Arg)
8058     return true;
8059 
8060   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8061 }
8062 
8063 static bool requiresParensToAddCast(const Expr *E) {
8064   // FIXME: We should have a general way to reason about operator
8065   // precedence and whether parens are actually needed here.
8066   // Take care of a few common cases where they aren't.
8067   const Expr *Inside = E->IgnoreImpCasts();
8068   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8069     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8070 
8071   switch (Inside->getStmtClass()) {
8072   case Stmt::ArraySubscriptExprClass:
8073   case Stmt::CallExprClass:
8074   case Stmt::CharacterLiteralClass:
8075   case Stmt::CXXBoolLiteralExprClass:
8076   case Stmt::DeclRefExprClass:
8077   case Stmt::FloatingLiteralClass:
8078   case Stmt::IntegerLiteralClass:
8079   case Stmt::MemberExprClass:
8080   case Stmt::ObjCArrayLiteralClass:
8081   case Stmt::ObjCBoolLiteralExprClass:
8082   case Stmt::ObjCBoxedExprClass:
8083   case Stmt::ObjCDictionaryLiteralClass:
8084   case Stmt::ObjCEncodeExprClass:
8085   case Stmt::ObjCIvarRefExprClass:
8086   case Stmt::ObjCMessageExprClass:
8087   case Stmt::ObjCPropertyRefExprClass:
8088   case Stmt::ObjCStringLiteralClass:
8089   case Stmt::ObjCSubscriptRefExprClass:
8090   case Stmt::ParenExprClass:
8091   case Stmt::StringLiteralClass:
8092   case Stmt::UnaryOperatorClass:
8093     return false;
8094   default:
8095     return true;
8096   }
8097 }
8098 
8099 static std::pair<QualType, StringRef>
8100 shouldNotPrintDirectly(const ASTContext &Context,
8101                        QualType IntendedTy,
8102                        const Expr *E) {
8103   // Use a 'while' to peel off layers of typedefs.
8104   QualType TyTy = IntendedTy;
8105   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8106     StringRef Name = UserTy->getDecl()->getName();
8107     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8108       .Case("CFIndex", Context.getNSIntegerType())
8109       .Case("NSInteger", Context.getNSIntegerType())
8110       .Case("NSUInteger", Context.getNSUIntegerType())
8111       .Case("SInt32", Context.IntTy)
8112       .Case("UInt32", Context.UnsignedIntTy)
8113       .Default(QualType());
8114 
8115     if (!CastTy.isNull())
8116       return std::make_pair(CastTy, Name);
8117 
8118     TyTy = UserTy->desugar();
8119   }
8120 
8121   // Strip parens if necessary.
8122   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8123     return shouldNotPrintDirectly(Context,
8124                                   PE->getSubExpr()->getType(),
8125                                   PE->getSubExpr());
8126 
8127   // If this is a conditional expression, then its result type is constructed
8128   // via usual arithmetic conversions and thus there might be no necessary
8129   // typedef sugar there.  Recurse to operands to check for NSInteger &
8130   // Co. usage condition.
8131   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8132     QualType TrueTy, FalseTy;
8133     StringRef TrueName, FalseName;
8134 
8135     std::tie(TrueTy, TrueName) =
8136       shouldNotPrintDirectly(Context,
8137                              CO->getTrueExpr()->getType(),
8138                              CO->getTrueExpr());
8139     std::tie(FalseTy, FalseName) =
8140       shouldNotPrintDirectly(Context,
8141                              CO->getFalseExpr()->getType(),
8142                              CO->getFalseExpr());
8143 
8144     if (TrueTy == FalseTy)
8145       return std::make_pair(TrueTy, TrueName);
8146     else if (TrueTy.isNull())
8147       return std::make_pair(FalseTy, FalseName);
8148     else if (FalseTy.isNull())
8149       return std::make_pair(TrueTy, TrueName);
8150   }
8151 
8152   return std::make_pair(QualType(), StringRef());
8153 }
8154 
8155 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8156 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8157 /// type do not count.
8158 static bool
8159 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8160   QualType From = ICE->getSubExpr()->getType();
8161   QualType To = ICE->getType();
8162   // It's an integer promotion if the destination type is the promoted
8163   // source type.
8164   if (ICE->getCastKind() == CK_IntegralCast &&
8165       From->isPromotableIntegerType() &&
8166       S.Context.getPromotedIntegerType(From) == To)
8167     return true;
8168   // Look through vector types, since we do default argument promotion for
8169   // those in OpenCL.
8170   if (const auto *VecTy = From->getAs<ExtVectorType>())
8171     From = VecTy->getElementType();
8172   if (const auto *VecTy = To->getAs<ExtVectorType>())
8173     To = VecTy->getElementType();
8174   // It's a floating promotion if the source type is a lower rank.
8175   return ICE->getCastKind() == CK_FloatingCast &&
8176          S.Context.getFloatingTypeOrder(From, To) < 0;
8177 }
8178 
8179 bool
8180 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8181                                     const char *StartSpecifier,
8182                                     unsigned SpecifierLen,
8183                                     const Expr *E) {
8184   using namespace analyze_format_string;
8185   using namespace analyze_printf;
8186 
8187   // Now type check the data expression that matches the
8188   // format specifier.
8189   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8190   if (!AT.isValid())
8191     return true;
8192 
8193   QualType ExprTy = E->getType();
8194   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8195     ExprTy = TET->getUnderlyingExpr()->getType();
8196   }
8197 
8198   // Diagnose attempts to print a boolean value as a character. Unlike other
8199   // -Wformat diagnostics, this is fine from a type perspective, but it still
8200   // doesn't make sense.
8201   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8202       E->isKnownToHaveBooleanValue()) {
8203     const CharSourceRange &CSR =
8204         getSpecifierRange(StartSpecifier, SpecifierLen);
8205     SmallString<4> FSString;
8206     llvm::raw_svector_ostream os(FSString);
8207     FS.toString(os);
8208     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8209                              << FSString,
8210                          E->getExprLoc(), false, CSR);
8211     return true;
8212   }
8213 
8214   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8215   if (Match == analyze_printf::ArgType::Match)
8216     return true;
8217 
8218   // Look through argument promotions for our error message's reported type.
8219   // This includes the integral and floating promotions, but excludes array
8220   // and function pointer decay (seeing that an argument intended to be a
8221   // string has type 'char [6]' is probably more confusing than 'char *') and
8222   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8223   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8224     if (isArithmeticArgumentPromotion(S, ICE)) {
8225       E = ICE->getSubExpr();
8226       ExprTy = E->getType();
8227 
8228       // Check if we didn't match because of an implicit cast from a 'char'
8229       // or 'short' to an 'int'.  This is done because printf is a varargs
8230       // function.
8231       if (ICE->getType() == S.Context.IntTy ||
8232           ICE->getType() == S.Context.UnsignedIntTy) {
8233         // All further checking is done on the subexpression
8234         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8235             AT.matchesType(S.Context, ExprTy);
8236         if (ImplicitMatch == analyze_printf::ArgType::Match)
8237           return true;
8238         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8239             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8240           Match = ImplicitMatch;
8241       }
8242     }
8243   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8244     // Special case for 'a', which has type 'int' in C.
8245     // Note, however, that we do /not/ want to treat multibyte constants like
8246     // 'MooV' as characters! This form is deprecated but still exists.
8247     if (ExprTy == S.Context.IntTy)
8248       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8249         ExprTy = S.Context.CharTy;
8250   }
8251 
8252   // Look through enums to their underlying type.
8253   bool IsEnum = false;
8254   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8255     ExprTy = EnumTy->getDecl()->getIntegerType();
8256     IsEnum = true;
8257   }
8258 
8259   // %C in an Objective-C context prints a unichar, not a wchar_t.
8260   // If the argument is an integer of some kind, believe the %C and suggest
8261   // a cast instead of changing the conversion specifier.
8262   QualType IntendedTy = ExprTy;
8263   if (isObjCContext() &&
8264       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8265     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8266         !ExprTy->isCharType()) {
8267       // 'unichar' is defined as a typedef of unsigned short, but we should
8268       // prefer using the typedef if it is visible.
8269       IntendedTy = S.Context.UnsignedShortTy;
8270 
8271       // While we are here, check if the value is an IntegerLiteral that happens
8272       // to be within the valid range.
8273       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8274         const llvm::APInt &V = IL->getValue();
8275         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8276           return true;
8277       }
8278 
8279       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8280                           Sema::LookupOrdinaryName);
8281       if (S.LookupName(Result, S.getCurScope())) {
8282         NamedDecl *ND = Result.getFoundDecl();
8283         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8284           if (TD->getUnderlyingType() == IntendedTy)
8285             IntendedTy = S.Context.getTypedefType(TD);
8286       }
8287     }
8288   }
8289 
8290   // Special-case some of Darwin's platform-independence types by suggesting
8291   // casts to primitive types that are known to be large enough.
8292   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8293   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8294     QualType CastTy;
8295     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8296     if (!CastTy.isNull()) {
8297       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8298       // (long in ASTContext). Only complain to pedants.
8299       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8300           (AT.isSizeT() || AT.isPtrdiffT()) &&
8301           AT.matchesType(S.Context, CastTy))
8302         Match = ArgType::NoMatchPedantic;
8303       IntendedTy = CastTy;
8304       ShouldNotPrintDirectly = true;
8305     }
8306   }
8307 
8308   // We may be able to offer a FixItHint if it is a supported type.
8309   PrintfSpecifier fixedFS = FS;
8310   bool Success =
8311       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8312 
8313   if (Success) {
8314     // Get the fix string from the fixed format specifier
8315     SmallString<16> buf;
8316     llvm::raw_svector_ostream os(buf);
8317     fixedFS.toString(os);
8318 
8319     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8320 
8321     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8322       unsigned Diag;
8323       switch (Match) {
8324       case ArgType::Match: llvm_unreachable("expected non-matching");
8325       case ArgType::NoMatchPedantic:
8326         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8327         break;
8328       case ArgType::NoMatchTypeConfusion:
8329         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8330         break;
8331       case ArgType::NoMatch:
8332         Diag = diag::warn_format_conversion_argument_type_mismatch;
8333         break;
8334       }
8335 
8336       // In this case, the specifier is wrong and should be changed to match
8337       // the argument.
8338       EmitFormatDiagnostic(S.PDiag(Diag)
8339                                << AT.getRepresentativeTypeName(S.Context)
8340                                << IntendedTy << IsEnum << E->getSourceRange(),
8341                            E->getBeginLoc(),
8342                            /*IsStringLocation*/ false, SpecRange,
8343                            FixItHint::CreateReplacement(SpecRange, os.str()));
8344     } else {
8345       // The canonical type for formatting this value is different from the
8346       // actual type of the expression. (This occurs, for example, with Darwin's
8347       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8348       // should be printed as 'long' for 64-bit compatibility.)
8349       // Rather than emitting a normal format/argument mismatch, we want to
8350       // add a cast to the recommended type (and correct the format string
8351       // if necessary).
8352       SmallString<16> CastBuf;
8353       llvm::raw_svector_ostream CastFix(CastBuf);
8354       CastFix << "(";
8355       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8356       CastFix << ")";
8357 
8358       SmallVector<FixItHint,4> Hints;
8359       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8360         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8361 
8362       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8363         // If there's already a cast present, just replace it.
8364         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8365         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8366 
8367       } else if (!requiresParensToAddCast(E)) {
8368         // If the expression has high enough precedence,
8369         // just write the C-style cast.
8370         Hints.push_back(
8371             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8372       } else {
8373         // Otherwise, add parens around the expression as well as the cast.
8374         CastFix << "(";
8375         Hints.push_back(
8376             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8377 
8378         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8379         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8380       }
8381 
8382       if (ShouldNotPrintDirectly) {
8383         // The expression has a type that should not be printed directly.
8384         // We extract the name from the typedef because we don't want to show
8385         // the underlying type in the diagnostic.
8386         StringRef Name;
8387         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8388           Name = TypedefTy->getDecl()->getName();
8389         else
8390           Name = CastTyName;
8391         unsigned Diag = Match == ArgType::NoMatchPedantic
8392                             ? diag::warn_format_argument_needs_cast_pedantic
8393                             : diag::warn_format_argument_needs_cast;
8394         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8395                                            << E->getSourceRange(),
8396                              E->getBeginLoc(), /*IsStringLocation=*/false,
8397                              SpecRange, Hints);
8398       } else {
8399         // In this case, the expression could be printed using a different
8400         // specifier, but we've decided that the specifier is probably correct
8401         // and we should cast instead. Just use the normal warning message.
8402         EmitFormatDiagnostic(
8403             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8404                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8405                 << E->getSourceRange(),
8406             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8407       }
8408     }
8409   } else {
8410     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8411                                                    SpecifierLen);
8412     // Since the warning for passing non-POD types to variadic functions
8413     // was deferred until now, we emit a warning for non-POD
8414     // arguments here.
8415     switch (S.isValidVarArgType(ExprTy)) {
8416     case Sema::VAK_Valid:
8417     case Sema::VAK_ValidInCXX11: {
8418       unsigned Diag;
8419       switch (Match) {
8420       case ArgType::Match: llvm_unreachable("expected non-matching");
8421       case ArgType::NoMatchPedantic:
8422         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8423         break;
8424       case ArgType::NoMatchTypeConfusion:
8425         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8426         break;
8427       case ArgType::NoMatch:
8428         Diag = diag::warn_format_conversion_argument_type_mismatch;
8429         break;
8430       }
8431 
8432       EmitFormatDiagnostic(
8433           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8434                         << IsEnum << CSR << E->getSourceRange(),
8435           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8436       break;
8437     }
8438     case Sema::VAK_Undefined:
8439     case Sema::VAK_MSVCUndefined:
8440       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8441                                << S.getLangOpts().CPlusPlus11 << ExprTy
8442                                << CallType
8443                                << AT.getRepresentativeTypeName(S.Context) << CSR
8444                                << E->getSourceRange(),
8445                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8446       checkForCStrMembers(AT, E);
8447       break;
8448 
8449     case Sema::VAK_Invalid:
8450       if (ExprTy->isObjCObjectType())
8451         EmitFormatDiagnostic(
8452             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8453                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8454                 << AT.getRepresentativeTypeName(S.Context) << CSR
8455                 << E->getSourceRange(),
8456             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8457       else
8458         // FIXME: If this is an initializer list, suggest removing the braces
8459         // or inserting a cast to the target type.
8460         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8461             << isa<InitListExpr>(E) << ExprTy << CallType
8462             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8463       break;
8464     }
8465 
8466     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8467            "format string specifier index out of range");
8468     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8469   }
8470 
8471   return true;
8472 }
8473 
8474 //===--- CHECK: Scanf format string checking ------------------------------===//
8475 
8476 namespace {
8477 
8478 class CheckScanfHandler : public CheckFormatHandler {
8479 public:
8480   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8481                     const Expr *origFormatExpr, Sema::FormatStringType type,
8482                     unsigned firstDataArg, unsigned numDataArgs,
8483                     const char *beg, bool hasVAListArg,
8484                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8485                     bool inFunctionCall, Sema::VariadicCallType CallType,
8486                     llvm::SmallBitVector &CheckedVarArgs,
8487                     UncoveredArgHandler &UncoveredArg)
8488       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8489                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8490                            inFunctionCall, CallType, CheckedVarArgs,
8491                            UncoveredArg) {}
8492 
8493   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8494                             const char *startSpecifier,
8495                             unsigned specifierLen) override;
8496 
8497   bool HandleInvalidScanfConversionSpecifier(
8498           const analyze_scanf::ScanfSpecifier &FS,
8499           const char *startSpecifier,
8500           unsigned specifierLen) override;
8501 
8502   void HandleIncompleteScanList(const char *start, const char *end) override;
8503 };
8504 
8505 } // namespace
8506 
8507 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8508                                                  const char *end) {
8509   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8510                        getLocationOfByte(end), /*IsStringLocation*/true,
8511                        getSpecifierRange(start, end - start));
8512 }
8513 
8514 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8515                                         const analyze_scanf::ScanfSpecifier &FS,
8516                                         const char *startSpecifier,
8517                                         unsigned specifierLen) {
8518   const analyze_scanf::ScanfConversionSpecifier &CS =
8519     FS.getConversionSpecifier();
8520 
8521   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8522                                           getLocationOfByte(CS.getStart()),
8523                                           startSpecifier, specifierLen,
8524                                           CS.getStart(), CS.getLength());
8525 }
8526 
8527 bool CheckScanfHandler::HandleScanfSpecifier(
8528                                        const analyze_scanf::ScanfSpecifier &FS,
8529                                        const char *startSpecifier,
8530                                        unsigned specifierLen) {
8531   using namespace analyze_scanf;
8532   using namespace analyze_format_string;
8533 
8534   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8535 
8536   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8537   // be used to decide if we are using positional arguments consistently.
8538   if (FS.consumesDataArgument()) {
8539     if (atFirstArg) {
8540       atFirstArg = false;
8541       usesPositionalArgs = FS.usesPositionalArg();
8542     }
8543     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8544       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8545                                         startSpecifier, specifierLen);
8546       return false;
8547     }
8548   }
8549 
8550   // Check if the field with is non-zero.
8551   const OptionalAmount &Amt = FS.getFieldWidth();
8552   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8553     if (Amt.getConstantAmount() == 0) {
8554       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8555                                                    Amt.getConstantLength());
8556       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8557                            getLocationOfByte(Amt.getStart()),
8558                            /*IsStringLocation*/true, R,
8559                            FixItHint::CreateRemoval(R));
8560     }
8561   }
8562 
8563   if (!FS.consumesDataArgument()) {
8564     // FIXME: Technically specifying a precision or field width here
8565     // makes no sense.  Worth issuing a warning at some point.
8566     return true;
8567   }
8568 
8569   // Consume the argument.
8570   unsigned argIndex = FS.getArgIndex();
8571   if (argIndex < NumDataArgs) {
8572       // The check to see if the argIndex is valid will come later.
8573       // We set the bit here because we may exit early from this
8574       // function if we encounter some other error.
8575     CoveredArgs.set(argIndex);
8576   }
8577 
8578   // Check the length modifier is valid with the given conversion specifier.
8579   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8580                                  S.getLangOpts()))
8581     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8582                                 diag::warn_format_nonsensical_length);
8583   else if (!FS.hasStandardLengthModifier())
8584     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8585   else if (!FS.hasStandardLengthConversionCombination())
8586     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8587                                 diag::warn_format_non_standard_conversion_spec);
8588 
8589   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8590     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8591 
8592   // The remaining checks depend on the data arguments.
8593   if (HasVAListArg)
8594     return true;
8595 
8596   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8597     return false;
8598 
8599   // Check that the argument type matches the format specifier.
8600   const Expr *Ex = getDataArg(argIndex);
8601   if (!Ex)
8602     return true;
8603 
8604   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8605 
8606   if (!AT.isValid()) {
8607     return true;
8608   }
8609 
8610   analyze_format_string::ArgType::MatchKind Match =
8611       AT.matchesType(S.Context, Ex->getType());
8612   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8613   if (Match == analyze_format_string::ArgType::Match)
8614     return true;
8615 
8616   ScanfSpecifier fixedFS = FS;
8617   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8618                                  S.getLangOpts(), S.Context);
8619 
8620   unsigned Diag =
8621       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8622                : diag::warn_format_conversion_argument_type_mismatch;
8623 
8624   if (Success) {
8625     // Get the fix string from the fixed format specifier.
8626     SmallString<128> buf;
8627     llvm::raw_svector_ostream os(buf);
8628     fixedFS.toString(os);
8629 
8630     EmitFormatDiagnostic(
8631         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8632                       << Ex->getType() << false << Ex->getSourceRange(),
8633         Ex->getBeginLoc(),
8634         /*IsStringLocation*/ false,
8635         getSpecifierRange(startSpecifier, specifierLen),
8636         FixItHint::CreateReplacement(
8637             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8638   } else {
8639     EmitFormatDiagnostic(S.PDiag(Diag)
8640                              << AT.getRepresentativeTypeName(S.Context)
8641                              << Ex->getType() << false << Ex->getSourceRange(),
8642                          Ex->getBeginLoc(),
8643                          /*IsStringLocation*/ false,
8644                          getSpecifierRange(startSpecifier, specifierLen));
8645   }
8646 
8647   return true;
8648 }
8649 
8650 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8651                               const Expr *OrigFormatExpr,
8652                               ArrayRef<const Expr *> Args,
8653                               bool HasVAListArg, unsigned format_idx,
8654                               unsigned firstDataArg,
8655                               Sema::FormatStringType Type,
8656                               bool inFunctionCall,
8657                               Sema::VariadicCallType CallType,
8658                               llvm::SmallBitVector &CheckedVarArgs,
8659                               UncoveredArgHandler &UncoveredArg,
8660                               bool IgnoreStringsWithoutSpecifiers) {
8661   // CHECK: is the format string a wide literal?
8662   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8663     CheckFormatHandler::EmitFormatDiagnostic(
8664         S, inFunctionCall, Args[format_idx],
8665         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8666         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8667     return;
8668   }
8669 
8670   // Str - The format string.  NOTE: this is NOT null-terminated!
8671   StringRef StrRef = FExpr->getString();
8672   const char *Str = StrRef.data();
8673   // Account for cases where the string literal is truncated in a declaration.
8674   const ConstantArrayType *T =
8675     S.Context.getAsConstantArrayType(FExpr->getType());
8676   assert(T && "String literal not of constant array type!");
8677   size_t TypeSize = T->getSize().getZExtValue();
8678   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8679   const unsigned numDataArgs = Args.size() - firstDataArg;
8680 
8681   if (IgnoreStringsWithoutSpecifiers &&
8682       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8683           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8684     return;
8685 
8686   // Emit a warning if the string literal is truncated and does not contain an
8687   // embedded null character.
8688   if (TypeSize <= StrRef.size() &&
8689       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8690     CheckFormatHandler::EmitFormatDiagnostic(
8691         S, inFunctionCall, Args[format_idx],
8692         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8693         FExpr->getBeginLoc(),
8694         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8695     return;
8696   }
8697 
8698   // CHECK: empty format string?
8699   if (StrLen == 0 && numDataArgs > 0) {
8700     CheckFormatHandler::EmitFormatDiagnostic(
8701         S, inFunctionCall, Args[format_idx],
8702         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8703         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8704     return;
8705   }
8706 
8707   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8708       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8709       Type == Sema::FST_OSTrace) {
8710     CheckPrintfHandler H(
8711         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8712         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8713         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8714         CheckedVarArgs, UncoveredArg);
8715 
8716     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8717                                                   S.getLangOpts(),
8718                                                   S.Context.getTargetInfo(),
8719                                             Type == Sema::FST_FreeBSDKPrintf))
8720       H.DoneProcessing();
8721   } else if (Type == Sema::FST_Scanf) {
8722     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8723                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8724                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8725 
8726     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8727                                                  S.getLangOpts(),
8728                                                  S.Context.getTargetInfo()))
8729       H.DoneProcessing();
8730   } // TODO: handle other formats
8731 }
8732 
8733 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8734   // Str - The format string.  NOTE: this is NOT null-terminated!
8735   StringRef StrRef = FExpr->getString();
8736   const char *Str = StrRef.data();
8737   // Account for cases where the string literal is truncated in a declaration.
8738   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8739   assert(T && "String literal not of constant array type!");
8740   size_t TypeSize = T->getSize().getZExtValue();
8741   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8742   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8743                                                          getLangOpts(),
8744                                                          Context.getTargetInfo());
8745 }
8746 
8747 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8748 
8749 // Returns the related absolute value function that is larger, of 0 if one
8750 // does not exist.
8751 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8752   switch (AbsFunction) {
8753   default:
8754     return 0;
8755 
8756   case Builtin::BI__builtin_abs:
8757     return Builtin::BI__builtin_labs;
8758   case Builtin::BI__builtin_labs:
8759     return Builtin::BI__builtin_llabs;
8760   case Builtin::BI__builtin_llabs:
8761     return 0;
8762 
8763   case Builtin::BI__builtin_fabsf:
8764     return Builtin::BI__builtin_fabs;
8765   case Builtin::BI__builtin_fabs:
8766     return Builtin::BI__builtin_fabsl;
8767   case Builtin::BI__builtin_fabsl:
8768     return 0;
8769 
8770   case Builtin::BI__builtin_cabsf:
8771     return Builtin::BI__builtin_cabs;
8772   case Builtin::BI__builtin_cabs:
8773     return Builtin::BI__builtin_cabsl;
8774   case Builtin::BI__builtin_cabsl:
8775     return 0;
8776 
8777   case Builtin::BIabs:
8778     return Builtin::BIlabs;
8779   case Builtin::BIlabs:
8780     return Builtin::BIllabs;
8781   case Builtin::BIllabs:
8782     return 0;
8783 
8784   case Builtin::BIfabsf:
8785     return Builtin::BIfabs;
8786   case Builtin::BIfabs:
8787     return Builtin::BIfabsl;
8788   case Builtin::BIfabsl:
8789     return 0;
8790 
8791   case Builtin::BIcabsf:
8792    return Builtin::BIcabs;
8793   case Builtin::BIcabs:
8794     return Builtin::BIcabsl;
8795   case Builtin::BIcabsl:
8796     return 0;
8797   }
8798 }
8799 
8800 // Returns the argument type of the absolute value function.
8801 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8802                                              unsigned AbsType) {
8803   if (AbsType == 0)
8804     return QualType();
8805 
8806   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8807   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8808   if (Error != ASTContext::GE_None)
8809     return QualType();
8810 
8811   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8812   if (!FT)
8813     return QualType();
8814 
8815   if (FT->getNumParams() != 1)
8816     return QualType();
8817 
8818   return FT->getParamType(0);
8819 }
8820 
8821 // Returns the best absolute value function, or zero, based on type and
8822 // current absolute value function.
8823 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8824                                    unsigned AbsFunctionKind) {
8825   unsigned BestKind = 0;
8826   uint64_t ArgSize = Context.getTypeSize(ArgType);
8827   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8828        Kind = getLargerAbsoluteValueFunction(Kind)) {
8829     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8830     if (Context.getTypeSize(ParamType) >= ArgSize) {
8831       if (BestKind == 0)
8832         BestKind = Kind;
8833       else if (Context.hasSameType(ParamType, ArgType)) {
8834         BestKind = Kind;
8835         break;
8836       }
8837     }
8838   }
8839   return BestKind;
8840 }
8841 
8842 enum AbsoluteValueKind {
8843   AVK_Integer,
8844   AVK_Floating,
8845   AVK_Complex
8846 };
8847 
8848 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8849   if (T->isIntegralOrEnumerationType())
8850     return AVK_Integer;
8851   if (T->isRealFloatingType())
8852     return AVK_Floating;
8853   if (T->isAnyComplexType())
8854     return AVK_Complex;
8855 
8856   llvm_unreachable("Type not integer, floating, or complex");
8857 }
8858 
8859 // Changes the absolute value function to a different type.  Preserves whether
8860 // the function is a builtin.
8861 static unsigned changeAbsFunction(unsigned AbsKind,
8862                                   AbsoluteValueKind ValueKind) {
8863   switch (ValueKind) {
8864   case AVK_Integer:
8865     switch (AbsKind) {
8866     default:
8867       return 0;
8868     case Builtin::BI__builtin_fabsf:
8869     case Builtin::BI__builtin_fabs:
8870     case Builtin::BI__builtin_fabsl:
8871     case Builtin::BI__builtin_cabsf:
8872     case Builtin::BI__builtin_cabs:
8873     case Builtin::BI__builtin_cabsl:
8874       return Builtin::BI__builtin_abs;
8875     case Builtin::BIfabsf:
8876     case Builtin::BIfabs:
8877     case Builtin::BIfabsl:
8878     case Builtin::BIcabsf:
8879     case Builtin::BIcabs:
8880     case Builtin::BIcabsl:
8881       return Builtin::BIabs;
8882     }
8883   case AVK_Floating:
8884     switch (AbsKind) {
8885     default:
8886       return 0;
8887     case Builtin::BI__builtin_abs:
8888     case Builtin::BI__builtin_labs:
8889     case Builtin::BI__builtin_llabs:
8890     case Builtin::BI__builtin_cabsf:
8891     case Builtin::BI__builtin_cabs:
8892     case Builtin::BI__builtin_cabsl:
8893       return Builtin::BI__builtin_fabsf;
8894     case Builtin::BIabs:
8895     case Builtin::BIlabs:
8896     case Builtin::BIllabs:
8897     case Builtin::BIcabsf:
8898     case Builtin::BIcabs:
8899     case Builtin::BIcabsl:
8900       return Builtin::BIfabsf;
8901     }
8902   case AVK_Complex:
8903     switch (AbsKind) {
8904     default:
8905       return 0;
8906     case Builtin::BI__builtin_abs:
8907     case Builtin::BI__builtin_labs:
8908     case Builtin::BI__builtin_llabs:
8909     case Builtin::BI__builtin_fabsf:
8910     case Builtin::BI__builtin_fabs:
8911     case Builtin::BI__builtin_fabsl:
8912       return Builtin::BI__builtin_cabsf;
8913     case Builtin::BIabs:
8914     case Builtin::BIlabs:
8915     case Builtin::BIllabs:
8916     case Builtin::BIfabsf:
8917     case Builtin::BIfabs:
8918     case Builtin::BIfabsl:
8919       return Builtin::BIcabsf;
8920     }
8921   }
8922   llvm_unreachable("Unable to convert function");
8923 }
8924 
8925 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8926   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8927   if (!FnInfo)
8928     return 0;
8929 
8930   switch (FDecl->getBuiltinID()) {
8931   default:
8932     return 0;
8933   case Builtin::BI__builtin_abs:
8934   case Builtin::BI__builtin_fabs:
8935   case Builtin::BI__builtin_fabsf:
8936   case Builtin::BI__builtin_fabsl:
8937   case Builtin::BI__builtin_labs:
8938   case Builtin::BI__builtin_llabs:
8939   case Builtin::BI__builtin_cabs:
8940   case Builtin::BI__builtin_cabsf:
8941   case Builtin::BI__builtin_cabsl:
8942   case Builtin::BIabs:
8943   case Builtin::BIlabs:
8944   case Builtin::BIllabs:
8945   case Builtin::BIfabs:
8946   case Builtin::BIfabsf:
8947   case Builtin::BIfabsl:
8948   case Builtin::BIcabs:
8949   case Builtin::BIcabsf:
8950   case Builtin::BIcabsl:
8951     return FDecl->getBuiltinID();
8952   }
8953   llvm_unreachable("Unknown Builtin type");
8954 }
8955 
8956 // If the replacement is valid, emit a note with replacement function.
8957 // Additionally, suggest including the proper header if not already included.
8958 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8959                             unsigned AbsKind, QualType ArgType) {
8960   bool EmitHeaderHint = true;
8961   const char *HeaderName = nullptr;
8962   const char *FunctionName = nullptr;
8963   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8964     FunctionName = "std::abs";
8965     if (ArgType->isIntegralOrEnumerationType()) {
8966       HeaderName = "cstdlib";
8967     } else if (ArgType->isRealFloatingType()) {
8968       HeaderName = "cmath";
8969     } else {
8970       llvm_unreachable("Invalid Type");
8971     }
8972 
8973     // Lookup all std::abs
8974     if (NamespaceDecl *Std = S.getStdNamespace()) {
8975       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8976       R.suppressDiagnostics();
8977       S.LookupQualifiedName(R, Std);
8978 
8979       for (const auto *I : R) {
8980         const FunctionDecl *FDecl = nullptr;
8981         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8982           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8983         } else {
8984           FDecl = dyn_cast<FunctionDecl>(I);
8985         }
8986         if (!FDecl)
8987           continue;
8988 
8989         // Found std::abs(), check that they are the right ones.
8990         if (FDecl->getNumParams() != 1)
8991           continue;
8992 
8993         // Check that the parameter type can handle the argument.
8994         QualType ParamType = FDecl->getParamDecl(0)->getType();
8995         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8996             S.Context.getTypeSize(ArgType) <=
8997                 S.Context.getTypeSize(ParamType)) {
8998           // Found a function, don't need the header hint.
8999           EmitHeaderHint = false;
9000           break;
9001         }
9002       }
9003     }
9004   } else {
9005     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9006     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9007 
9008     if (HeaderName) {
9009       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9010       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9011       R.suppressDiagnostics();
9012       S.LookupName(R, S.getCurScope());
9013 
9014       if (R.isSingleResult()) {
9015         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9016         if (FD && FD->getBuiltinID() == AbsKind) {
9017           EmitHeaderHint = false;
9018         } else {
9019           return;
9020         }
9021       } else if (!R.empty()) {
9022         return;
9023       }
9024     }
9025   }
9026 
9027   S.Diag(Loc, diag::note_replace_abs_function)
9028       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9029 
9030   if (!HeaderName)
9031     return;
9032 
9033   if (!EmitHeaderHint)
9034     return;
9035 
9036   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9037                                                     << FunctionName;
9038 }
9039 
9040 template <std::size_t StrLen>
9041 static bool IsStdFunction(const FunctionDecl *FDecl,
9042                           const char (&Str)[StrLen]) {
9043   if (!FDecl)
9044     return false;
9045   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9046     return false;
9047   if (!FDecl->isInStdNamespace())
9048     return false;
9049 
9050   return true;
9051 }
9052 
9053 // Warn when using the wrong abs() function.
9054 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9055                                       const FunctionDecl *FDecl) {
9056   if (Call->getNumArgs() != 1)
9057     return;
9058 
9059   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9060   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9061   if (AbsKind == 0 && !IsStdAbs)
9062     return;
9063 
9064   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9065   QualType ParamType = Call->getArg(0)->getType();
9066 
9067   // Unsigned types cannot be negative.  Suggest removing the absolute value
9068   // function call.
9069   if (ArgType->isUnsignedIntegerType()) {
9070     const char *FunctionName =
9071         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9072     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9073     Diag(Call->getExprLoc(), diag::note_remove_abs)
9074         << FunctionName
9075         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9076     return;
9077   }
9078 
9079   // Taking the absolute value of a pointer is very suspicious, they probably
9080   // wanted to index into an array, dereference a pointer, call a function, etc.
9081   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9082     unsigned DiagType = 0;
9083     if (ArgType->isFunctionType())
9084       DiagType = 1;
9085     else if (ArgType->isArrayType())
9086       DiagType = 2;
9087 
9088     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9089     return;
9090   }
9091 
9092   // std::abs has overloads which prevent most of the absolute value problems
9093   // from occurring.
9094   if (IsStdAbs)
9095     return;
9096 
9097   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9098   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9099 
9100   // The argument and parameter are the same kind.  Check if they are the right
9101   // size.
9102   if (ArgValueKind == ParamValueKind) {
9103     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9104       return;
9105 
9106     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9107     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9108         << FDecl << ArgType << ParamType;
9109 
9110     if (NewAbsKind == 0)
9111       return;
9112 
9113     emitReplacement(*this, Call->getExprLoc(),
9114                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9115     return;
9116   }
9117 
9118   // ArgValueKind != ParamValueKind
9119   // The wrong type of absolute value function was used.  Attempt to find the
9120   // proper one.
9121   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9122   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9123   if (NewAbsKind == 0)
9124     return;
9125 
9126   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9127       << FDecl << ParamValueKind << ArgValueKind;
9128 
9129   emitReplacement(*this, Call->getExprLoc(),
9130                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9131 }
9132 
9133 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9134 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9135                                 const FunctionDecl *FDecl) {
9136   if (!Call || !FDecl) return;
9137 
9138   // Ignore template specializations and macros.
9139   if (inTemplateInstantiation()) return;
9140   if (Call->getExprLoc().isMacroID()) return;
9141 
9142   // Only care about the one template argument, two function parameter std::max
9143   if (Call->getNumArgs() != 2) return;
9144   if (!IsStdFunction(FDecl, "max")) return;
9145   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9146   if (!ArgList) return;
9147   if (ArgList->size() != 1) return;
9148 
9149   // Check that template type argument is unsigned integer.
9150   const auto& TA = ArgList->get(0);
9151   if (TA.getKind() != TemplateArgument::Type) return;
9152   QualType ArgType = TA.getAsType();
9153   if (!ArgType->isUnsignedIntegerType()) return;
9154 
9155   // See if either argument is a literal zero.
9156   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9157     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9158     if (!MTE) return false;
9159     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
9160     if (!Num) return false;
9161     if (Num->getValue() != 0) return false;
9162     return true;
9163   };
9164 
9165   const Expr *FirstArg = Call->getArg(0);
9166   const Expr *SecondArg = Call->getArg(1);
9167   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9168   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9169 
9170   // Only warn when exactly one argument is zero.
9171   if (IsFirstArgZero == IsSecondArgZero) return;
9172 
9173   SourceRange FirstRange = FirstArg->getSourceRange();
9174   SourceRange SecondRange = SecondArg->getSourceRange();
9175 
9176   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9177 
9178   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9179       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9180 
9181   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9182   SourceRange RemovalRange;
9183   if (IsFirstArgZero) {
9184     RemovalRange = SourceRange(FirstRange.getBegin(),
9185                                SecondRange.getBegin().getLocWithOffset(-1));
9186   } else {
9187     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9188                                SecondRange.getEnd());
9189   }
9190 
9191   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9192         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9193         << FixItHint::CreateRemoval(RemovalRange);
9194 }
9195 
9196 //===--- CHECK: Standard memory functions ---------------------------------===//
9197 
9198 /// Takes the expression passed to the size_t parameter of functions
9199 /// such as memcmp, strncat, etc and warns if it's a comparison.
9200 ///
9201 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9202 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9203                                            IdentifierInfo *FnName,
9204                                            SourceLocation FnLoc,
9205                                            SourceLocation RParenLoc) {
9206   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9207   if (!Size)
9208     return false;
9209 
9210   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9211   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9212     return false;
9213 
9214   SourceRange SizeRange = Size->getSourceRange();
9215   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9216       << SizeRange << FnName;
9217   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9218       << FnName
9219       << FixItHint::CreateInsertion(
9220              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9221       << FixItHint::CreateRemoval(RParenLoc);
9222   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9223       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9224       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9225                                     ")");
9226 
9227   return true;
9228 }
9229 
9230 /// Determine whether the given type is or contains a dynamic class type
9231 /// (e.g., whether it has a vtable).
9232 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9233                                                      bool &IsContained) {
9234   // Look through array types while ignoring qualifiers.
9235   const Type *Ty = T->getBaseElementTypeUnsafe();
9236   IsContained = false;
9237 
9238   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9239   RD = RD ? RD->getDefinition() : nullptr;
9240   if (!RD || RD->isInvalidDecl())
9241     return nullptr;
9242 
9243   if (RD->isDynamicClass())
9244     return RD;
9245 
9246   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9247   // It's impossible for a class to transitively contain itself by value, so
9248   // infinite recursion is impossible.
9249   for (auto *FD : RD->fields()) {
9250     bool SubContained;
9251     if (const CXXRecordDecl *ContainedRD =
9252             getContainedDynamicClass(FD->getType(), SubContained)) {
9253       IsContained = true;
9254       return ContainedRD;
9255     }
9256   }
9257 
9258   return nullptr;
9259 }
9260 
9261 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9262   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9263     if (Unary->getKind() == UETT_SizeOf)
9264       return Unary;
9265   return nullptr;
9266 }
9267 
9268 /// If E is a sizeof expression, returns its argument expression,
9269 /// otherwise returns NULL.
9270 static const Expr *getSizeOfExprArg(const Expr *E) {
9271   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9272     if (!SizeOf->isArgumentType())
9273       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9274   return nullptr;
9275 }
9276 
9277 /// If E is a sizeof expression, returns its argument type.
9278 static QualType getSizeOfArgType(const Expr *E) {
9279   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9280     return SizeOf->getTypeOfArgument();
9281   return QualType();
9282 }
9283 
9284 namespace {
9285 
9286 struct SearchNonTrivialToInitializeField
9287     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9288   using Super =
9289       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9290 
9291   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9292 
9293   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9294                      SourceLocation SL) {
9295     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9296       asDerived().visitArray(PDIK, AT, SL);
9297       return;
9298     }
9299 
9300     Super::visitWithKind(PDIK, FT, SL);
9301   }
9302 
9303   void visitARCStrong(QualType FT, SourceLocation SL) {
9304     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9305   }
9306   void visitARCWeak(QualType FT, SourceLocation SL) {
9307     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9308   }
9309   void visitStruct(QualType FT, SourceLocation SL) {
9310     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9311       visit(FD->getType(), FD->getLocation());
9312   }
9313   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9314                   const ArrayType *AT, SourceLocation SL) {
9315     visit(getContext().getBaseElementType(AT), SL);
9316   }
9317   void visitTrivial(QualType FT, SourceLocation SL) {}
9318 
9319   static void diag(QualType RT, const Expr *E, Sema &S) {
9320     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9321   }
9322 
9323   ASTContext &getContext() { return S.getASTContext(); }
9324 
9325   const Expr *E;
9326   Sema &S;
9327 };
9328 
9329 struct SearchNonTrivialToCopyField
9330     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9331   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9332 
9333   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9334 
9335   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9336                      SourceLocation SL) {
9337     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9338       asDerived().visitArray(PCK, AT, SL);
9339       return;
9340     }
9341 
9342     Super::visitWithKind(PCK, FT, SL);
9343   }
9344 
9345   void visitARCStrong(QualType FT, SourceLocation SL) {
9346     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9347   }
9348   void visitARCWeak(QualType FT, SourceLocation SL) {
9349     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9350   }
9351   void visitStruct(QualType FT, SourceLocation SL) {
9352     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9353       visit(FD->getType(), FD->getLocation());
9354   }
9355   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9356                   SourceLocation SL) {
9357     visit(getContext().getBaseElementType(AT), SL);
9358   }
9359   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9360                 SourceLocation SL) {}
9361   void visitTrivial(QualType FT, SourceLocation SL) {}
9362   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9363 
9364   static void diag(QualType RT, const Expr *E, Sema &S) {
9365     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9366   }
9367 
9368   ASTContext &getContext() { return S.getASTContext(); }
9369 
9370   const Expr *E;
9371   Sema &S;
9372 };
9373 
9374 }
9375 
9376 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9377 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9378   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9379 
9380   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9381     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9382       return false;
9383 
9384     return doesExprLikelyComputeSize(BO->getLHS()) ||
9385            doesExprLikelyComputeSize(BO->getRHS());
9386   }
9387 
9388   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9389 }
9390 
9391 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9392 ///
9393 /// \code
9394 ///   #define MACRO 0
9395 ///   foo(MACRO);
9396 ///   foo(0);
9397 /// \endcode
9398 ///
9399 /// This should return true for the first call to foo, but not for the second
9400 /// (regardless of whether foo is a macro or function).
9401 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9402                                         SourceLocation CallLoc,
9403                                         SourceLocation ArgLoc) {
9404   if (!CallLoc.isMacroID())
9405     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9406 
9407   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9408          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9409 }
9410 
9411 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9412 /// last two arguments transposed.
9413 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9414   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9415     return;
9416 
9417   const Expr *SizeArg =
9418     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9419 
9420   auto isLiteralZero = [](const Expr *E) {
9421     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9422   };
9423 
9424   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9425   SourceLocation CallLoc = Call->getRParenLoc();
9426   SourceManager &SM = S.getSourceManager();
9427   if (isLiteralZero(SizeArg) &&
9428       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9429 
9430     SourceLocation DiagLoc = SizeArg->getExprLoc();
9431 
9432     // Some platforms #define bzero to __builtin_memset. See if this is the
9433     // case, and if so, emit a better diagnostic.
9434     if (BId == Builtin::BIbzero ||
9435         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9436                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9437       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9438       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9439     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9440       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9441       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9442     }
9443     return;
9444   }
9445 
9446   // If the second argument to a memset is a sizeof expression and the third
9447   // isn't, this is also likely an error. This should catch
9448   // 'memset(buf, sizeof(buf), 0xff)'.
9449   if (BId == Builtin::BImemset &&
9450       doesExprLikelyComputeSize(Call->getArg(1)) &&
9451       !doesExprLikelyComputeSize(Call->getArg(2))) {
9452     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9453     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9454     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9455     return;
9456   }
9457 }
9458 
9459 /// Check for dangerous or invalid arguments to memset().
9460 ///
9461 /// This issues warnings on known problematic, dangerous or unspecified
9462 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9463 /// function calls.
9464 ///
9465 /// \param Call The call expression to diagnose.
9466 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9467                                    unsigned BId,
9468                                    IdentifierInfo *FnName) {
9469   assert(BId != 0);
9470 
9471   // It is possible to have a non-standard definition of memset.  Validate
9472   // we have enough arguments, and if not, abort further checking.
9473   unsigned ExpectedNumArgs =
9474       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9475   if (Call->getNumArgs() < ExpectedNumArgs)
9476     return;
9477 
9478   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9479                       BId == Builtin::BIstrndup ? 1 : 2);
9480   unsigned LenArg =
9481       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9482   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9483 
9484   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9485                                      Call->getBeginLoc(), Call->getRParenLoc()))
9486     return;
9487 
9488   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9489   CheckMemaccessSize(*this, BId, Call);
9490 
9491   // We have special checking when the length is a sizeof expression.
9492   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9493   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9494   llvm::FoldingSetNodeID SizeOfArgID;
9495 
9496   // Although widely used, 'bzero' is not a standard function. Be more strict
9497   // with the argument types before allowing diagnostics and only allow the
9498   // form bzero(ptr, sizeof(...)).
9499   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9500   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9501     return;
9502 
9503   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9504     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9505     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9506 
9507     QualType DestTy = Dest->getType();
9508     QualType PointeeTy;
9509     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9510       PointeeTy = DestPtrTy->getPointeeType();
9511 
9512       // Never warn about void type pointers. This can be used to suppress
9513       // false positives.
9514       if (PointeeTy->isVoidType())
9515         continue;
9516 
9517       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9518       // actually comparing the expressions for equality. Because computing the
9519       // expression IDs can be expensive, we only do this if the diagnostic is
9520       // enabled.
9521       if (SizeOfArg &&
9522           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9523                            SizeOfArg->getExprLoc())) {
9524         // We only compute IDs for expressions if the warning is enabled, and
9525         // cache the sizeof arg's ID.
9526         if (SizeOfArgID == llvm::FoldingSetNodeID())
9527           SizeOfArg->Profile(SizeOfArgID, Context, true);
9528         llvm::FoldingSetNodeID DestID;
9529         Dest->Profile(DestID, Context, true);
9530         if (DestID == SizeOfArgID) {
9531           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9532           //       over sizeof(src) as well.
9533           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9534           StringRef ReadableName = FnName->getName();
9535 
9536           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9537             if (UnaryOp->getOpcode() == UO_AddrOf)
9538               ActionIdx = 1; // If its an address-of operator, just remove it.
9539           if (!PointeeTy->isIncompleteType() &&
9540               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9541             ActionIdx = 2; // If the pointee's size is sizeof(char),
9542                            // suggest an explicit length.
9543 
9544           // If the function is defined as a builtin macro, do not show macro
9545           // expansion.
9546           SourceLocation SL = SizeOfArg->getExprLoc();
9547           SourceRange DSR = Dest->getSourceRange();
9548           SourceRange SSR = SizeOfArg->getSourceRange();
9549           SourceManager &SM = getSourceManager();
9550 
9551           if (SM.isMacroArgExpansion(SL)) {
9552             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9553             SL = SM.getSpellingLoc(SL);
9554             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9555                              SM.getSpellingLoc(DSR.getEnd()));
9556             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9557                              SM.getSpellingLoc(SSR.getEnd()));
9558           }
9559 
9560           DiagRuntimeBehavior(SL, SizeOfArg,
9561                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9562                                 << ReadableName
9563                                 << PointeeTy
9564                                 << DestTy
9565                                 << DSR
9566                                 << SSR);
9567           DiagRuntimeBehavior(SL, SizeOfArg,
9568                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9569                                 << ActionIdx
9570                                 << SSR);
9571 
9572           break;
9573         }
9574       }
9575 
9576       // Also check for cases where the sizeof argument is the exact same
9577       // type as the memory argument, and where it points to a user-defined
9578       // record type.
9579       if (SizeOfArgTy != QualType()) {
9580         if (PointeeTy->isRecordType() &&
9581             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9582           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9583                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9584                                 << FnName << SizeOfArgTy << ArgIdx
9585                                 << PointeeTy << Dest->getSourceRange()
9586                                 << LenExpr->getSourceRange());
9587           break;
9588         }
9589       }
9590     } else if (DestTy->isArrayType()) {
9591       PointeeTy = DestTy;
9592     }
9593 
9594     if (PointeeTy == QualType())
9595       continue;
9596 
9597     // Always complain about dynamic classes.
9598     bool IsContained;
9599     if (const CXXRecordDecl *ContainedRD =
9600             getContainedDynamicClass(PointeeTy, IsContained)) {
9601 
9602       unsigned OperationType = 0;
9603       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9604       // "overwritten" if we're warning about the destination for any call
9605       // but memcmp; otherwise a verb appropriate to the call.
9606       if (ArgIdx != 0 || IsCmp) {
9607         if (BId == Builtin::BImemcpy)
9608           OperationType = 1;
9609         else if(BId == Builtin::BImemmove)
9610           OperationType = 2;
9611         else if (IsCmp)
9612           OperationType = 3;
9613       }
9614 
9615       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9616                           PDiag(diag::warn_dyn_class_memaccess)
9617                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9618                               << IsContained << ContainedRD << OperationType
9619                               << Call->getCallee()->getSourceRange());
9620     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9621              BId != Builtin::BImemset)
9622       DiagRuntimeBehavior(
9623         Dest->getExprLoc(), Dest,
9624         PDiag(diag::warn_arc_object_memaccess)
9625           << ArgIdx << FnName << PointeeTy
9626           << Call->getCallee()->getSourceRange());
9627     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9628       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9629           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9630         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9631                             PDiag(diag::warn_cstruct_memaccess)
9632                                 << ArgIdx << FnName << PointeeTy << 0);
9633         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9634       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9635                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9636         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9637                             PDiag(diag::warn_cstruct_memaccess)
9638                                 << ArgIdx << FnName << PointeeTy << 1);
9639         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9640       } else {
9641         continue;
9642       }
9643     } else
9644       continue;
9645 
9646     DiagRuntimeBehavior(
9647       Dest->getExprLoc(), Dest,
9648       PDiag(diag::note_bad_memaccess_silence)
9649         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9650     break;
9651   }
9652 }
9653 
9654 // A little helper routine: ignore addition and subtraction of integer literals.
9655 // This intentionally does not ignore all integer constant expressions because
9656 // we don't want to remove sizeof().
9657 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9658   Ex = Ex->IgnoreParenCasts();
9659 
9660   while (true) {
9661     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9662     if (!BO || !BO->isAdditiveOp())
9663       break;
9664 
9665     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9666     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9667 
9668     if (isa<IntegerLiteral>(RHS))
9669       Ex = LHS;
9670     else if (isa<IntegerLiteral>(LHS))
9671       Ex = RHS;
9672     else
9673       break;
9674   }
9675 
9676   return Ex;
9677 }
9678 
9679 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9680                                                       ASTContext &Context) {
9681   // Only handle constant-sized or VLAs, but not flexible members.
9682   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9683     // Only issue the FIXIT for arrays of size > 1.
9684     if (CAT->getSize().getSExtValue() <= 1)
9685       return false;
9686   } else if (!Ty->isVariableArrayType()) {
9687     return false;
9688   }
9689   return true;
9690 }
9691 
9692 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9693 // be the size of the source, instead of the destination.
9694 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9695                                     IdentifierInfo *FnName) {
9696 
9697   // Don't crash if the user has the wrong number of arguments
9698   unsigned NumArgs = Call->getNumArgs();
9699   if ((NumArgs != 3) && (NumArgs != 4))
9700     return;
9701 
9702   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9703   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9704   const Expr *CompareWithSrc = nullptr;
9705 
9706   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9707                                      Call->getBeginLoc(), Call->getRParenLoc()))
9708     return;
9709 
9710   // Look for 'strlcpy(dst, x, sizeof(x))'
9711   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9712     CompareWithSrc = Ex;
9713   else {
9714     // Look for 'strlcpy(dst, x, strlen(x))'
9715     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9716       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9717           SizeCall->getNumArgs() == 1)
9718         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9719     }
9720   }
9721 
9722   if (!CompareWithSrc)
9723     return;
9724 
9725   // Determine if the argument to sizeof/strlen is equal to the source
9726   // argument.  In principle there's all kinds of things you could do
9727   // here, for instance creating an == expression and evaluating it with
9728   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9729   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9730   if (!SrcArgDRE)
9731     return;
9732 
9733   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9734   if (!CompareWithSrcDRE ||
9735       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9736     return;
9737 
9738   const Expr *OriginalSizeArg = Call->getArg(2);
9739   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9740       << OriginalSizeArg->getSourceRange() << FnName;
9741 
9742   // Output a FIXIT hint if the destination is an array (rather than a
9743   // pointer to an array).  This could be enhanced to handle some
9744   // pointers if we know the actual size, like if DstArg is 'array+2'
9745   // we could say 'sizeof(array)-2'.
9746   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9747   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9748     return;
9749 
9750   SmallString<128> sizeString;
9751   llvm::raw_svector_ostream OS(sizeString);
9752   OS << "sizeof(";
9753   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9754   OS << ")";
9755 
9756   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9757       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9758                                       OS.str());
9759 }
9760 
9761 /// Check if two expressions refer to the same declaration.
9762 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9763   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9764     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9765       return D1->getDecl() == D2->getDecl();
9766   return false;
9767 }
9768 
9769 static const Expr *getStrlenExprArg(const Expr *E) {
9770   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9771     const FunctionDecl *FD = CE->getDirectCallee();
9772     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9773       return nullptr;
9774     return CE->getArg(0)->IgnoreParenCasts();
9775   }
9776   return nullptr;
9777 }
9778 
9779 // Warn on anti-patterns as the 'size' argument to strncat.
9780 // The correct size argument should look like following:
9781 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9782 void Sema::CheckStrncatArguments(const CallExpr *CE,
9783                                  IdentifierInfo *FnName) {
9784   // Don't crash if the user has the wrong number of arguments.
9785   if (CE->getNumArgs() < 3)
9786     return;
9787   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9788   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9789   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9790 
9791   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9792                                      CE->getRParenLoc()))
9793     return;
9794 
9795   // Identify common expressions, which are wrongly used as the size argument
9796   // to strncat and may lead to buffer overflows.
9797   unsigned PatternType = 0;
9798   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9799     // - sizeof(dst)
9800     if (referToTheSameDecl(SizeOfArg, DstArg))
9801       PatternType = 1;
9802     // - sizeof(src)
9803     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9804       PatternType = 2;
9805   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9806     if (BE->getOpcode() == BO_Sub) {
9807       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9808       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9809       // - sizeof(dst) - strlen(dst)
9810       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9811           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9812         PatternType = 1;
9813       // - sizeof(src) - (anything)
9814       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9815         PatternType = 2;
9816     }
9817   }
9818 
9819   if (PatternType == 0)
9820     return;
9821 
9822   // Generate the diagnostic.
9823   SourceLocation SL = LenArg->getBeginLoc();
9824   SourceRange SR = LenArg->getSourceRange();
9825   SourceManager &SM = getSourceManager();
9826 
9827   // If the function is defined as a builtin macro, do not show macro expansion.
9828   if (SM.isMacroArgExpansion(SL)) {
9829     SL = SM.getSpellingLoc(SL);
9830     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9831                      SM.getSpellingLoc(SR.getEnd()));
9832   }
9833 
9834   // Check if the destination is an array (rather than a pointer to an array).
9835   QualType DstTy = DstArg->getType();
9836   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9837                                                                     Context);
9838   if (!isKnownSizeArray) {
9839     if (PatternType == 1)
9840       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9841     else
9842       Diag(SL, diag::warn_strncat_src_size) << SR;
9843     return;
9844   }
9845 
9846   if (PatternType == 1)
9847     Diag(SL, diag::warn_strncat_large_size) << SR;
9848   else
9849     Diag(SL, diag::warn_strncat_src_size) << SR;
9850 
9851   SmallString<128> sizeString;
9852   llvm::raw_svector_ostream OS(sizeString);
9853   OS << "sizeof(";
9854   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9855   OS << ") - ";
9856   OS << "strlen(";
9857   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9858   OS << ") - 1";
9859 
9860   Diag(SL, diag::note_strncat_wrong_size)
9861     << FixItHint::CreateReplacement(SR, OS.str());
9862 }
9863 
9864 void
9865 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9866                          SourceLocation ReturnLoc,
9867                          bool isObjCMethod,
9868                          const AttrVec *Attrs,
9869                          const FunctionDecl *FD) {
9870   // Check if the return value is null but should not be.
9871   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9872        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9873       CheckNonNullExpr(*this, RetValExp))
9874     Diag(ReturnLoc, diag::warn_null_ret)
9875       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9876 
9877   // C++11 [basic.stc.dynamic.allocation]p4:
9878   //   If an allocation function declared with a non-throwing
9879   //   exception-specification fails to allocate storage, it shall return
9880   //   a null pointer. Any other allocation function that fails to allocate
9881   //   storage shall indicate failure only by throwing an exception [...]
9882   if (FD) {
9883     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9884     if (Op == OO_New || Op == OO_Array_New) {
9885       const FunctionProtoType *Proto
9886         = FD->getType()->castAs<FunctionProtoType>();
9887       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9888           CheckNonNullExpr(*this, RetValExp))
9889         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9890           << FD << getLangOpts().CPlusPlus11;
9891     }
9892   }
9893 }
9894 
9895 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9896 
9897 /// Check for comparisons of floating point operands using != and ==.
9898 /// Issue a warning if these are no self-comparisons, as they are not likely
9899 /// to do what the programmer intended.
9900 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9901   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9902   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9903 
9904   // Special case: check for x == x (which is OK).
9905   // Do not emit warnings for such cases.
9906   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9907     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9908       if (DRL->getDecl() == DRR->getDecl())
9909         return;
9910 
9911   // Special case: check for comparisons against literals that can be exactly
9912   //  represented by APFloat.  In such cases, do not emit a warning.  This
9913   //  is a heuristic: often comparison against such literals are used to
9914   //  detect if a value in a variable has not changed.  This clearly can
9915   //  lead to false negatives.
9916   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9917     if (FLL->isExact())
9918       return;
9919   } else
9920     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9921       if (FLR->isExact())
9922         return;
9923 
9924   // Check for comparisons with builtin types.
9925   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9926     if (CL->getBuiltinCallee())
9927       return;
9928 
9929   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9930     if (CR->getBuiltinCallee())
9931       return;
9932 
9933   // Emit the diagnostic.
9934   Diag(Loc, diag::warn_floatingpoint_eq)
9935     << LHS->getSourceRange() << RHS->getSourceRange();
9936 }
9937 
9938 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9939 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9940 
9941 namespace {
9942 
9943 /// Structure recording the 'active' range of an integer-valued
9944 /// expression.
9945 struct IntRange {
9946   /// The number of bits active in the int.
9947   unsigned Width;
9948 
9949   /// True if the int is known not to have negative values.
9950   bool NonNegative;
9951 
9952   IntRange(unsigned Width, bool NonNegative)
9953       : Width(Width), NonNegative(NonNegative) {}
9954 
9955   /// Returns the range of the bool type.
9956   static IntRange forBoolType() {
9957     return IntRange(1, true);
9958   }
9959 
9960   /// Returns the range of an opaque value of the given integral type.
9961   static IntRange forValueOfType(ASTContext &C, QualType T) {
9962     return forValueOfCanonicalType(C,
9963                           T->getCanonicalTypeInternal().getTypePtr());
9964   }
9965 
9966   /// Returns the range of an opaque value of a canonical integral type.
9967   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9968     assert(T->isCanonicalUnqualified());
9969 
9970     if (const VectorType *VT = dyn_cast<VectorType>(T))
9971       T = VT->getElementType().getTypePtr();
9972     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9973       T = CT->getElementType().getTypePtr();
9974     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9975       T = AT->getValueType().getTypePtr();
9976 
9977     if (!C.getLangOpts().CPlusPlus) {
9978       // For enum types in C code, use the underlying datatype.
9979       if (const EnumType *ET = dyn_cast<EnumType>(T))
9980         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9981     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9982       // For enum types in C++, use the known bit width of the enumerators.
9983       EnumDecl *Enum = ET->getDecl();
9984       // In C++11, enums can have a fixed underlying type. Use this type to
9985       // compute the range.
9986       if (Enum->isFixed()) {
9987         return IntRange(C.getIntWidth(QualType(T, 0)),
9988                         !ET->isSignedIntegerOrEnumerationType());
9989       }
9990 
9991       unsigned NumPositive = Enum->getNumPositiveBits();
9992       unsigned NumNegative = Enum->getNumNegativeBits();
9993 
9994       if (NumNegative == 0)
9995         return IntRange(NumPositive, true/*NonNegative*/);
9996       else
9997         return IntRange(std::max(NumPositive + 1, NumNegative),
9998                         false/*NonNegative*/);
9999     }
10000 
10001     const BuiltinType *BT = cast<BuiltinType>(T);
10002     assert(BT->isInteger());
10003 
10004     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10005   }
10006 
10007   /// Returns the "target" range of a canonical integral type, i.e.
10008   /// the range of values expressible in the type.
10009   ///
10010   /// This matches forValueOfCanonicalType except that enums have the
10011   /// full range of their type, not the range of their enumerators.
10012   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10013     assert(T->isCanonicalUnqualified());
10014 
10015     if (const VectorType *VT = dyn_cast<VectorType>(T))
10016       T = VT->getElementType().getTypePtr();
10017     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10018       T = CT->getElementType().getTypePtr();
10019     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10020       T = AT->getValueType().getTypePtr();
10021     if (const EnumType *ET = dyn_cast<EnumType>(T))
10022       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10023 
10024     const BuiltinType *BT = cast<BuiltinType>(T);
10025     assert(BT->isInteger());
10026 
10027     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10028   }
10029 
10030   /// Returns the supremum of two ranges: i.e. their conservative merge.
10031   static IntRange join(IntRange L, IntRange R) {
10032     return IntRange(std::max(L.Width, R.Width),
10033                     L.NonNegative && R.NonNegative);
10034   }
10035 
10036   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10037   static IntRange meet(IntRange L, IntRange R) {
10038     return IntRange(std::min(L.Width, R.Width),
10039                     L.NonNegative || R.NonNegative);
10040   }
10041 };
10042 
10043 } // namespace
10044 
10045 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10046                               unsigned MaxWidth) {
10047   if (value.isSigned() && value.isNegative())
10048     return IntRange(value.getMinSignedBits(), false);
10049 
10050   if (value.getBitWidth() > MaxWidth)
10051     value = value.trunc(MaxWidth);
10052 
10053   // isNonNegative() just checks the sign bit without considering
10054   // signedness.
10055   return IntRange(value.getActiveBits(), true);
10056 }
10057 
10058 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10059                               unsigned MaxWidth) {
10060   if (result.isInt())
10061     return GetValueRange(C, result.getInt(), MaxWidth);
10062 
10063   if (result.isVector()) {
10064     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10065     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10066       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10067       R = IntRange::join(R, El);
10068     }
10069     return R;
10070   }
10071 
10072   if (result.isComplexInt()) {
10073     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10074     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10075     return IntRange::join(R, I);
10076   }
10077 
10078   // This can happen with lossless casts to intptr_t of "based" lvalues.
10079   // Assume it might use arbitrary bits.
10080   // FIXME: The only reason we need to pass the type in here is to get
10081   // the sign right on this one case.  It would be nice if APValue
10082   // preserved this.
10083   assert(result.isLValue() || result.isAddrLabelDiff());
10084   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10085 }
10086 
10087 static QualType GetExprType(const Expr *E) {
10088   QualType Ty = E->getType();
10089   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10090     Ty = AtomicRHS->getValueType();
10091   return Ty;
10092 }
10093 
10094 /// Pseudo-evaluate the given integer expression, estimating the
10095 /// range of values it might take.
10096 ///
10097 /// \param MaxWidth - the width to which the value will be truncated
10098 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10099                              bool InConstantContext) {
10100   E = E->IgnoreParens();
10101 
10102   // Try a full evaluation first.
10103   Expr::EvalResult result;
10104   if (E->EvaluateAsRValue(result, C, InConstantContext))
10105     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10106 
10107   // I think we only want to look through implicit casts here; if the
10108   // user has an explicit widening cast, we should treat the value as
10109   // being of the new, wider type.
10110   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10111     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10112       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10113 
10114     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10115 
10116     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10117                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10118 
10119     // Assume that non-integer casts can span the full range of the type.
10120     if (!isIntegerCast)
10121       return OutputTypeRange;
10122 
10123     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10124                                      std::min(MaxWidth, OutputTypeRange.Width),
10125                                      InConstantContext);
10126 
10127     // Bail out if the subexpr's range is as wide as the cast type.
10128     if (SubRange.Width >= OutputTypeRange.Width)
10129       return OutputTypeRange;
10130 
10131     // Otherwise, we take the smaller width, and we're non-negative if
10132     // either the output type or the subexpr is.
10133     return IntRange(SubRange.Width,
10134                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10135   }
10136 
10137   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10138     // If we can fold the condition, just take that operand.
10139     bool CondResult;
10140     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10141       return GetExprRange(C,
10142                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10143                           MaxWidth, InConstantContext);
10144 
10145     // Otherwise, conservatively merge.
10146     IntRange L =
10147         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10148     IntRange R =
10149         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10150     return IntRange::join(L, R);
10151   }
10152 
10153   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10154     switch (BO->getOpcode()) {
10155     case BO_Cmp:
10156       llvm_unreachable("builtin <=> should have class type");
10157 
10158     // Boolean-valued operations are single-bit and positive.
10159     case BO_LAnd:
10160     case BO_LOr:
10161     case BO_LT:
10162     case BO_GT:
10163     case BO_LE:
10164     case BO_GE:
10165     case BO_EQ:
10166     case BO_NE:
10167       return IntRange::forBoolType();
10168 
10169     // The type of the assignments is the type of the LHS, so the RHS
10170     // is not necessarily the same type.
10171     case BO_MulAssign:
10172     case BO_DivAssign:
10173     case BO_RemAssign:
10174     case BO_AddAssign:
10175     case BO_SubAssign:
10176     case BO_XorAssign:
10177     case BO_OrAssign:
10178       // TODO: bitfields?
10179       return IntRange::forValueOfType(C, GetExprType(E));
10180 
10181     // Simple assignments just pass through the RHS, which will have
10182     // been coerced to the LHS type.
10183     case BO_Assign:
10184       // TODO: bitfields?
10185       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10186 
10187     // Operations with opaque sources are black-listed.
10188     case BO_PtrMemD:
10189     case BO_PtrMemI:
10190       return IntRange::forValueOfType(C, GetExprType(E));
10191 
10192     // Bitwise-and uses the *infinum* of the two source ranges.
10193     case BO_And:
10194     case BO_AndAssign:
10195       return IntRange::meet(
10196           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10197           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10198 
10199     // Left shift gets black-listed based on a judgement call.
10200     case BO_Shl:
10201       // ...except that we want to treat '1 << (blah)' as logically
10202       // positive.  It's an important idiom.
10203       if (IntegerLiteral *I
10204             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10205         if (I->getValue() == 1) {
10206           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10207           return IntRange(R.Width, /*NonNegative*/ true);
10208         }
10209       }
10210       LLVM_FALLTHROUGH;
10211 
10212     case BO_ShlAssign:
10213       return IntRange::forValueOfType(C, GetExprType(E));
10214 
10215     // Right shift by a constant can narrow its left argument.
10216     case BO_Shr:
10217     case BO_ShrAssign: {
10218       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10219 
10220       // If the shift amount is a positive constant, drop the width by
10221       // that much.
10222       llvm::APSInt shift;
10223       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10224           shift.isNonNegative()) {
10225         unsigned zext = shift.getZExtValue();
10226         if (zext >= L.Width)
10227           L.Width = (L.NonNegative ? 0 : 1);
10228         else
10229           L.Width -= zext;
10230       }
10231 
10232       return L;
10233     }
10234 
10235     // Comma acts as its right operand.
10236     case BO_Comma:
10237       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10238 
10239     // Black-list pointer subtractions.
10240     case BO_Sub:
10241       if (BO->getLHS()->getType()->isPointerType())
10242         return IntRange::forValueOfType(C, GetExprType(E));
10243       break;
10244 
10245     // The width of a division result is mostly determined by the size
10246     // of the LHS.
10247     case BO_Div: {
10248       // Don't 'pre-truncate' the operands.
10249       unsigned opWidth = C.getIntWidth(GetExprType(E));
10250       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10251 
10252       // If the divisor is constant, use that.
10253       llvm::APSInt divisor;
10254       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10255         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10256         if (log2 >= L.Width)
10257           L.Width = (L.NonNegative ? 0 : 1);
10258         else
10259           L.Width = std::min(L.Width - log2, MaxWidth);
10260         return L;
10261       }
10262 
10263       // Otherwise, just use the LHS's width.
10264       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10265       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10266     }
10267 
10268     // The result of a remainder can't be larger than the result of
10269     // either side.
10270     case BO_Rem: {
10271       // Don't 'pre-truncate' the operands.
10272       unsigned opWidth = C.getIntWidth(GetExprType(E));
10273       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10274       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10275 
10276       IntRange meet = IntRange::meet(L, R);
10277       meet.Width = std::min(meet.Width, MaxWidth);
10278       return meet;
10279     }
10280 
10281     // The default behavior is okay for these.
10282     case BO_Mul:
10283     case BO_Add:
10284     case BO_Xor:
10285     case BO_Or:
10286       break;
10287     }
10288 
10289     // The default case is to treat the operation as if it were closed
10290     // on the narrowest type that encompasses both operands.
10291     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10292     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10293     return IntRange::join(L, R);
10294   }
10295 
10296   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10297     switch (UO->getOpcode()) {
10298     // Boolean-valued operations are white-listed.
10299     case UO_LNot:
10300       return IntRange::forBoolType();
10301 
10302     // Operations with opaque sources are black-listed.
10303     case UO_Deref:
10304     case UO_AddrOf: // should be impossible
10305       return IntRange::forValueOfType(C, GetExprType(E));
10306 
10307     default:
10308       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10309     }
10310   }
10311 
10312   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10313     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10314 
10315   if (const auto *BitField = E->getSourceBitField())
10316     return IntRange(BitField->getBitWidthValue(C),
10317                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10318 
10319   return IntRange::forValueOfType(C, GetExprType(E));
10320 }
10321 
10322 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10323                              bool InConstantContext) {
10324   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10325 }
10326 
10327 /// Checks whether the given value, which currently has the given
10328 /// source semantics, has the same value when coerced through the
10329 /// target semantics.
10330 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10331                                  const llvm::fltSemantics &Src,
10332                                  const llvm::fltSemantics &Tgt) {
10333   llvm::APFloat truncated = value;
10334 
10335   bool ignored;
10336   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10337   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10338 
10339   return truncated.bitwiseIsEqual(value);
10340 }
10341 
10342 /// Checks whether the given value, which currently has the given
10343 /// source semantics, has the same value when coerced through the
10344 /// target semantics.
10345 ///
10346 /// The value might be a vector of floats (or a complex number).
10347 static bool IsSameFloatAfterCast(const APValue &value,
10348                                  const llvm::fltSemantics &Src,
10349                                  const llvm::fltSemantics &Tgt) {
10350   if (value.isFloat())
10351     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10352 
10353   if (value.isVector()) {
10354     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10355       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10356         return false;
10357     return true;
10358   }
10359 
10360   assert(value.isComplexFloat());
10361   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10362           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10363 }
10364 
10365 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10366                                        bool IsListInit = false);
10367 
10368 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10369   // Suppress cases where we are comparing against an enum constant.
10370   if (const DeclRefExpr *DR =
10371       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10372     if (isa<EnumConstantDecl>(DR->getDecl()))
10373       return true;
10374 
10375   // Suppress cases where the value is expanded from a macro, unless that macro
10376   // is how a language represents a boolean literal. This is the case in both C
10377   // and Objective-C.
10378   SourceLocation BeginLoc = E->getBeginLoc();
10379   if (BeginLoc.isMacroID()) {
10380     StringRef MacroName = Lexer::getImmediateMacroName(
10381         BeginLoc, S.getSourceManager(), S.getLangOpts());
10382     return MacroName != "YES" && MacroName != "NO" &&
10383            MacroName != "true" && MacroName != "false";
10384   }
10385 
10386   return false;
10387 }
10388 
10389 static bool isKnownToHaveUnsignedValue(Expr *E) {
10390   return E->getType()->isIntegerType() &&
10391          (!E->getType()->isSignedIntegerType() ||
10392           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10393 }
10394 
10395 namespace {
10396 /// The promoted range of values of a type. In general this has the
10397 /// following structure:
10398 ///
10399 ///     |-----------| . . . |-----------|
10400 ///     ^           ^       ^           ^
10401 ///    Min       HoleMin  HoleMax      Max
10402 ///
10403 /// ... where there is only a hole if a signed type is promoted to unsigned
10404 /// (in which case Min and Max are the smallest and largest representable
10405 /// values).
10406 struct PromotedRange {
10407   // Min, or HoleMax if there is a hole.
10408   llvm::APSInt PromotedMin;
10409   // Max, or HoleMin if there is a hole.
10410   llvm::APSInt PromotedMax;
10411 
10412   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10413     if (R.Width == 0)
10414       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10415     else if (R.Width >= BitWidth && !Unsigned) {
10416       // Promotion made the type *narrower*. This happens when promoting
10417       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10418       // Treat all values of 'signed int' as being in range for now.
10419       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10420       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10421     } else {
10422       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10423                         .extOrTrunc(BitWidth);
10424       PromotedMin.setIsUnsigned(Unsigned);
10425 
10426       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10427                         .extOrTrunc(BitWidth);
10428       PromotedMax.setIsUnsigned(Unsigned);
10429     }
10430   }
10431 
10432   // Determine whether this range is contiguous (has no hole).
10433   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10434 
10435   // Where a constant value is within the range.
10436   enum ComparisonResult {
10437     LT = 0x1,
10438     LE = 0x2,
10439     GT = 0x4,
10440     GE = 0x8,
10441     EQ = 0x10,
10442     NE = 0x20,
10443     InRangeFlag = 0x40,
10444 
10445     Less = LE | LT | NE,
10446     Min = LE | InRangeFlag,
10447     InRange = InRangeFlag,
10448     Max = GE | InRangeFlag,
10449     Greater = GE | GT | NE,
10450 
10451     OnlyValue = LE | GE | EQ | InRangeFlag,
10452     InHole = NE
10453   };
10454 
10455   ComparisonResult compare(const llvm::APSInt &Value) const {
10456     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10457            Value.isUnsigned() == PromotedMin.isUnsigned());
10458     if (!isContiguous()) {
10459       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10460       if (Value.isMinValue()) return Min;
10461       if (Value.isMaxValue()) return Max;
10462       if (Value >= PromotedMin) return InRange;
10463       if (Value <= PromotedMax) return InRange;
10464       return InHole;
10465     }
10466 
10467     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10468     case -1: return Less;
10469     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10470     case 1:
10471       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10472       case -1: return InRange;
10473       case 0: return Max;
10474       case 1: return Greater;
10475       }
10476     }
10477 
10478     llvm_unreachable("impossible compare result");
10479   }
10480 
10481   static llvm::Optional<StringRef>
10482   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10483     if (Op == BO_Cmp) {
10484       ComparisonResult LTFlag = LT, GTFlag = GT;
10485       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10486 
10487       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10488       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10489       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10490       return llvm::None;
10491     }
10492 
10493     ComparisonResult TrueFlag, FalseFlag;
10494     if (Op == BO_EQ) {
10495       TrueFlag = EQ;
10496       FalseFlag = NE;
10497     } else if (Op == BO_NE) {
10498       TrueFlag = NE;
10499       FalseFlag = EQ;
10500     } else {
10501       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10502         TrueFlag = LT;
10503         FalseFlag = GE;
10504       } else {
10505         TrueFlag = GT;
10506         FalseFlag = LE;
10507       }
10508       if (Op == BO_GE || Op == BO_LE)
10509         std::swap(TrueFlag, FalseFlag);
10510     }
10511     if (R & TrueFlag)
10512       return StringRef("true");
10513     if (R & FalseFlag)
10514       return StringRef("false");
10515     return llvm::None;
10516   }
10517 };
10518 }
10519 
10520 static bool HasEnumType(Expr *E) {
10521   // Strip off implicit integral promotions.
10522   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10523     if (ICE->getCastKind() != CK_IntegralCast &&
10524         ICE->getCastKind() != CK_NoOp)
10525       break;
10526     E = ICE->getSubExpr();
10527   }
10528 
10529   return E->getType()->isEnumeralType();
10530 }
10531 
10532 static int classifyConstantValue(Expr *Constant) {
10533   // The values of this enumeration are used in the diagnostics
10534   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10535   enum ConstantValueKind {
10536     Miscellaneous = 0,
10537     LiteralTrue,
10538     LiteralFalse
10539   };
10540   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10541     return BL->getValue() ? ConstantValueKind::LiteralTrue
10542                           : ConstantValueKind::LiteralFalse;
10543   return ConstantValueKind::Miscellaneous;
10544 }
10545 
10546 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10547                                         Expr *Constant, Expr *Other,
10548                                         const llvm::APSInt &Value,
10549                                         bool RhsConstant) {
10550   if (S.inTemplateInstantiation())
10551     return false;
10552 
10553   Expr *OriginalOther = Other;
10554 
10555   Constant = Constant->IgnoreParenImpCasts();
10556   Other = Other->IgnoreParenImpCasts();
10557 
10558   // Suppress warnings on tautological comparisons between values of the same
10559   // enumeration type. There are only two ways we could warn on this:
10560   //  - If the constant is outside the range of representable values of
10561   //    the enumeration. In such a case, we should warn about the cast
10562   //    to enumeration type, not about the comparison.
10563   //  - If the constant is the maximum / minimum in-range value. For an
10564   //    enumeratin type, such comparisons can be meaningful and useful.
10565   if (Constant->getType()->isEnumeralType() &&
10566       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10567     return false;
10568 
10569   // TODO: Investigate using GetExprRange() to get tighter bounds
10570   // on the bit ranges.
10571   QualType OtherT = Other->getType();
10572   if (const auto *AT = OtherT->getAs<AtomicType>())
10573     OtherT = AT->getValueType();
10574   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10575 
10576   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10577   // (Namely, macOS).
10578   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10579                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10580                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10581 
10582   // Whether we're treating Other as being a bool because of the form of
10583   // expression despite it having another type (typically 'int' in C).
10584   bool OtherIsBooleanDespiteType =
10585       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10586   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10587     OtherRange = IntRange::forBoolType();
10588 
10589   // Determine the promoted range of the other type and see if a comparison of
10590   // the constant against that range is tautological.
10591   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10592                                    Value.isUnsigned());
10593   auto Cmp = OtherPromotedRange.compare(Value);
10594   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10595   if (!Result)
10596     return false;
10597 
10598   // Suppress the diagnostic for an in-range comparison if the constant comes
10599   // from a macro or enumerator. We don't want to diagnose
10600   //
10601   //   some_long_value <= INT_MAX
10602   //
10603   // when sizeof(int) == sizeof(long).
10604   bool InRange = Cmp & PromotedRange::InRangeFlag;
10605   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10606     return false;
10607 
10608   // If this is a comparison to an enum constant, include that
10609   // constant in the diagnostic.
10610   const EnumConstantDecl *ED = nullptr;
10611   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10612     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10613 
10614   // Should be enough for uint128 (39 decimal digits)
10615   SmallString<64> PrettySourceValue;
10616   llvm::raw_svector_ostream OS(PrettySourceValue);
10617   if (ED) {
10618     OS << '\'' << *ED << "' (" << Value << ")";
10619   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10620                Constant->IgnoreParenImpCasts())) {
10621     OS << (BL->getValue() ? "YES" : "NO");
10622   } else {
10623     OS << Value;
10624   }
10625 
10626   if (IsObjCSignedCharBool) {
10627     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10628                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10629                               << OS.str() << *Result);
10630     return true;
10631   }
10632 
10633   // FIXME: We use a somewhat different formatting for the in-range cases and
10634   // cases involving boolean values for historical reasons. We should pick a
10635   // consistent way of presenting these diagnostics.
10636   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10637 
10638     S.DiagRuntimeBehavior(
10639         E->getOperatorLoc(), E,
10640         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10641                          : diag::warn_tautological_bool_compare)
10642             << OS.str() << classifyConstantValue(Constant) << OtherT
10643             << OtherIsBooleanDespiteType << *Result
10644             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10645   } else {
10646     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10647                         ? (HasEnumType(OriginalOther)
10648                                ? diag::warn_unsigned_enum_always_true_comparison
10649                                : diag::warn_unsigned_always_true_comparison)
10650                         : diag::warn_tautological_constant_compare;
10651 
10652     S.Diag(E->getOperatorLoc(), Diag)
10653         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10654         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10655   }
10656 
10657   return true;
10658 }
10659 
10660 /// Analyze the operands of the given comparison.  Implements the
10661 /// fallback case from AnalyzeComparison.
10662 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10663   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10664   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10665 }
10666 
10667 /// Implements -Wsign-compare.
10668 ///
10669 /// \param E the binary operator to check for warnings
10670 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10671   // The type the comparison is being performed in.
10672   QualType T = E->getLHS()->getType();
10673 
10674   // Only analyze comparison operators where both sides have been converted to
10675   // the same type.
10676   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10677     return AnalyzeImpConvsInComparison(S, E);
10678 
10679   // Don't analyze value-dependent comparisons directly.
10680   if (E->isValueDependent())
10681     return AnalyzeImpConvsInComparison(S, E);
10682 
10683   Expr *LHS = E->getLHS();
10684   Expr *RHS = E->getRHS();
10685 
10686   if (T->isIntegralType(S.Context)) {
10687     llvm::APSInt RHSValue;
10688     llvm::APSInt LHSValue;
10689 
10690     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10691     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10692 
10693     // We don't care about expressions whose result is a constant.
10694     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10695       return AnalyzeImpConvsInComparison(S, E);
10696 
10697     // We only care about expressions where just one side is literal
10698     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10699       // Is the constant on the RHS or LHS?
10700       const bool RhsConstant = IsRHSIntegralLiteral;
10701       Expr *Const = RhsConstant ? RHS : LHS;
10702       Expr *Other = RhsConstant ? LHS : RHS;
10703       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10704 
10705       // Check whether an integer constant comparison results in a value
10706       // of 'true' or 'false'.
10707       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10708         return AnalyzeImpConvsInComparison(S, E);
10709     }
10710   }
10711 
10712   if (!T->hasUnsignedIntegerRepresentation()) {
10713     // We don't do anything special if this isn't an unsigned integral
10714     // comparison:  we're only interested in integral comparisons, and
10715     // signed comparisons only happen in cases we don't care to warn about.
10716     return AnalyzeImpConvsInComparison(S, E);
10717   }
10718 
10719   LHS = LHS->IgnoreParenImpCasts();
10720   RHS = RHS->IgnoreParenImpCasts();
10721 
10722   if (!S.getLangOpts().CPlusPlus) {
10723     // Avoid warning about comparison of integers with different signs when
10724     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10725     // the type of `E`.
10726     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10727       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10728     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10729       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10730   }
10731 
10732   // Check to see if one of the (unmodified) operands is of different
10733   // signedness.
10734   Expr *signedOperand, *unsignedOperand;
10735   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10736     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10737            "unsigned comparison between two signed integer expressions?");
10738     signedOperand = LHS;
10739     unsignedOperand = RHS;
10740   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10741     signedOperand = RHS;
10742     unsignedOperand = LHS;
10743   } else {
10744     return AnalyzeImpConvsInComparison(S, E);
10745   }
10746 
10747   // Otherwise, calculate the effective range of the signed operand.
10748   IntRange signedRange =
10749       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10750 
10751   // Go ahead and analyze implicit conversions in the operands.  Note
10752   // that we skip the implicit conversions on both sides.
10753   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10754   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10755 
10756   // If the signed range is non-negative, -Wsign-compare won't fire.
10757   if (signedRange.NonNegative)
10758     return;
10759 
10760   // For (in)equality comparisons, if the unsigned operand is a
10761   // constant which cannot collide with a overflowed signed operand,
10762   // then reinterpreting the signed operand as unsigned will not
10763   // change the result of the comparison.
10764   if (E->isEqualityOp()) {
10765     unsigned comparisonWidth = S.Context.getIntWidth(T);
10766     IntRange unsignedRange =
10767         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10768 
10769     // We should never be unable to prove that the unsigned operand is
10770     // non-negative.
10771     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10772 
10773     if (unsignedRange.Width < comparisonWidth)
10774       return;
10775   }
10776 
10777   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10778                         S.PDiag(diag::warn_mixed_sign_comparison)
10779                             << LHS->getType() << RHS->getType()
10780                             << LHS->getSourceRange() << RHS->getSourceRange());
10781 }
10782 
10783 /// Analyzes an attempt to assign the given value to a bitfield.
10784 ///
10785 /// Returns true if there was something fishy about the attempt.
10786 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10787                                       SourceLocation InitLoc) {
10788   assert(Bitfield->isBitField());
10789   if (Bitfield->isInvalidDecl())
10790     return false;
10791 
10792   // White-list bool bitfields.
10793   QualType BitfieldType = Bitfield->getType();
10794   if (BitfieldType->isBooleanType())
10795      return false;
10796 
10797   if (BitfieldType->isEnumeralType()) {
10798     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10799     // If the underlying enum type was not explicitly specified as an unsigned
10800     // type and the enum contain only positive values, MSVC++ will cause an
10801     // inconsistency by storing this as a signed type.
10802     if (S.getLangOpts().CPlusPlus11 &&
10803         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10804         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10805         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10806       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10807         << BitfieldEnumDecl->getNameAsString();
10808     }
10809   }
10810 
10811   if (Bitfield->getType()->isBooleanType())
10812     return false;
10813 
10814   // Ignore value- or type-dependent expressions.
10815   if (Bitfield->getBitWidth()->isValueDependent() ||
10816       Bitfield->getBitWidth()->isTypeDependent() ||
10817       Init->isValueDependent() ||
10818       Init->isTypeDependent())
10819     return false;
10820 
10821   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10822   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10823 
10824   Expr::EvalResult Result;
10825   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10826                                    Expr::SE_AllowSideEffects)) {
10827     // The RHS is not constant.  If the RHS has an enum type, make sure the
10828     // bitfield is wide enough to hold all the values of the enum without
10829     // truncation.
10830     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10831       EnumDecl *ED = EnumTy->getDecl();
10832       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10833 
10834       // Enum types are implicitly signed on Windows, so check if there are any
10835       // negative enumerators to see if the enum was intended to be signed or
10836       // not.
10837       bool SignedEnum = ED->getNumNegativeBits() > 0;
10838 
10839       // Check for surprising sign changes when assigning enum values to a
10840       // bitfield of different signedness.  If the bitfield is signed and we
10841       // have exactly the right number of bits to store this unsigned enum,
10842       // suggest changing the enum to an unsigned type. This typically happens
10843       // on Windows where unfixed enums always use an underlying type of 'int'.
10844       unsigned DiagID = 0;
10845       if (SignedEnum && !SignedBitfield) {
10846         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10847       } else if (SignedBitfield && !SignedEnum &&
10848                  ED->getNumPositiveBits() == FieldWidth) {
10849         DiagID = diag::warn_signed_bitfield_enum_conversion;
10850       }
10851 
10852       if (DiagID) {
10853         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10854         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10855         SourceRange TypeRange =
10856             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10857         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10858             << SignedEnum << TypeRange;
10859       }
10860 
10861       // Compute the required bitwidth. If the enum has negative values, we need
10862       // one more bit than the normal number of positive bits to represent the
10863       // sign bit.
10864       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10865                                                   ED->getNumNegativeBits())
10866                                        : ED->getNumPositiveBits();
10867 
10868       // Check the bitwidth.
10869       if (BitsNeeded > FieldWidth) {
10870         Expr *WidthExpr = Bitfield->getBitWidth();
10871         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10872             << Bitfield << ED;
10873         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10874             << BitsNeeded << ED << WidthExpr->getSourceRange();
10875       }
10876     }
10877 
10878     return false;
10879   }
10880 
10881   llvm::APSInt Value = Result.Val.getInt();
10882 
10883   unsigned OriginalWidth = Value.getBitWidth();
10884 
10885   if (!Value.isSigned() || Value.isNegative())
10886     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10887       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10888         OriginalWidth = Value.getMinSignedBits();
10889 
10890   if (OriginalWidth <= FieldWidth)
10891     return false;
10892 
10893   // Compute the value which the bitfield will contain.
10894   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10895   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10896 
10897   // Check whether the stored value is equal to the original value.
10898   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10899   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10900     return false;
10901 
10902   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10903   // therefore don't strictly fit into a signed bitfield of width 1.
10904   if (FieldWidth == 1 && Value == 1)
10905     return false;
10906 
10907   std::string PrettyValue = Value.toString(10);
10908   std::string PrettyTrunc = TruncatedValue.toString(10);
10909 
10910   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10911     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10912     << Init->getSourceRange();
10913 
10914   return true;
10915 }
10916 
10917 /// Analyze the given simple or compound assignment for warning-worthy
10918 /// operations.
10919 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10920   // Just recurse on the LHS.
10921   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10922 
10923   // We want to recurse on the RHS as normal unless we're assigning to
10924   // a bitfield.
10925   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10926     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10927                                   E->getOperatorLoc())) {
10928       // Recurse, ignoring any implicit conversions on the RHS.
10929       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10930                                         E->getOperatorLoc());
10931     }
10932   }
10933 
10934   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10935 
10936   // Diagnose implicitly sequentially-consistent atomic assignment.
10937   if (E->getLHS()->getType()->isAtomicType())
10938     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10939 }
10940 
10941 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10942 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10943                             SourceLocation CContext, unsigned diag,
10944                             bool pruneControlFlow = false) {
10945   if (pruneControlFlow) {
10946     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10947                           S.PDiag(diag)
10948                               << SourceType << T << E->getSourceRange()
10949                               << SourceRange(CContext));
10950     return;
10951   }
10952   S.Diag(E->getExprLoc(), diag)
10953     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10954 }
10955 
10956 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10957 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10958                             SourceLocation CContext,
10959                             unsigned diag, bool pruneControlFlow = false) {
10960   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10961 }
10962 
10963 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10964   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10965       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10966 }
10967 
10968 static void adornObjCBoolConversionDiagWithTernaryFixit(
10969     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10970   Expr *Ignored = SourceExpr->IgnoreImplicit();
10971   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10972     Ignored = OVE->getSourceExpr();
10973   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10974                      isa<BinaryOperator>(Ignored) ||
10975                      isa<CXXOperatorCallExpr>(Ignored);
10976   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10977   if (NeedsParens)
10978     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10979             << FixItHint::CreateInsertion(EndLoc, ")");
10980   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10981 }
10982 
10983 /// Diagnose an implicit cast from a floating point value to an integer value.
10984 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10985                                     SourceLocation CContext) {
10986   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10987   const bool PruneWarnings = S.inTemplateInstantiation();
10988 
10989   Expr *InnerE = E->IgnoreParenImpCasts();
10990   // We also want to warn on, e.g., "int i = -1.234"
10991   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10992     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10993       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10994 
10995   const bool IsLiteral =
10996       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10997 
10998   llvm::APFloat Value(0.0);
10999   bool IsConstant =
11000     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11001   if (!IsConstant) {
11002     if (isObjCSignedCharBool(S, T)) {
11003       return adornObjCBoolConversionDiagWithTernaryFixit(
11004           S, E,
11005           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11006               << E->getType());
11007     }
11008 
11009     return DiagnoseImpCast(S, E, T, CContext,
11010                            diag::warn_impcast_float_integer, PruneWarnings);
11011   }
11012 
11013   bool isExact = false;
11014 
11015   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11016                             T->hasUnsignedIntegerRepresentation());
11017   llvm::APFloat::opStatus Result = Value.convertToInteger(
11018       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11019 
11020   // FIXME: Force the precision of the source value down so we don't print
11021   // digits which are usually useless (we don't really care here if we
11022   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11023   // would automatically print the shortest representation, but it's a bit
11024   // tricky to implement.
11025   SmallString<16> PrettySourceValue;
11026   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11027   precision = (precision * 59 + 195) / 196;
11028   Value.toString(PrettySourceValue, precision);
11029 
11030   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11031     return adornObjCBoolConversionDiagWithTernaryFixit(
11032         S, E,
11033         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11034             << PrettySourceValue);
11035   }
11036 
11037   if (Result == llvm::APFloat::opOK && isExact) {
11038     if (IsLiteral) return;
11039     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11040                            PruneWarnings);
11041   }
11042 
11043   // Conversion of a floating-point value to a non-bool integer where the
11044   // integral part cannot be represented by the integer type is undefined.
11045   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11046     return DiagnoseImpCast(
11047         S, E, T, CContext,
11048         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11049                   : diag::warn_impcast_float_to_integer_out_of_range,
11050         PruneWarnings);
11051 
11052   unsigned DiagID = 0;
11053   if (IsLiteral) {
11054     // Warn on floating point literal to integer.
11055     DiagID = diag::warn_impcast_literal_float_to_integer;
11056   } else if (IntegerValue == 0) {
11057     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11058       return DiagnoseImpCast(S, E, T, CContext,
11059                              diag::warn_impcast_float_integer, PruneWarnings);
11060     }
11061     // Warn on non-zero to zero conversion.
11062     DiagID = diag::warn_impcast_float_to_integer_zero;
11063   } else {
11064     if (IntegerValue.isUnsigned()) {
11065       if (!IntegerValue.isMaxValue()) {
11066         return DiagnoseImpCast(S, E, T, CContext,
11067                                diag::warn_impcast_float_integer, PruneWarnings);
11068       }
11069     } else {  // IntegerValue.isSigned()
11070       if (!IntegerValue.isMaxSignedValue() &&
11071           !IntegerValue.isMinSignedValue()) {
11072         return DiagnoseImpCast(S, E, T, CContext,
11073                                diag::warn_impcast_float_integer, PruneWarnings);
11074       }
11075     }
11076     // Warn on evaluatable floating point expression to integer conversion.
11077     DiagID = diag::warn_impcast_float_to_integer;
11078   }
11079 
11080   SmallString<16> PrettyTargetValue;
11081   if (IsBool)
11082     PrettyTargetValue = Value.isZero() ? "false" : "true";
11083   else
11084     IntegerValue.toString(PrettyTargetValue);
11085 
11086   if (PruneWarnings) {
11087     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11088                           S.PDiag(DiagID)
11089                               << E->getType() << T.getUnqualifiedType()
11090                               << PrettySourceValue << PrettyTargetValue
11091                               << E->getSourceRange() << SourceRange(CContext));
11092   } else {
11093     S.Diag(E->getExprLoc(), DiagID)
11094         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11095         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11096   }
11097 }
11098 
11099 /// Analyze the given compound assignment for the possible losing of
11100 /// floating-point precision.
11101 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11102   assert(isa<CompoundAssignOperator>(E) &&
11103          "Must be compound assignment operation");
11104   // Recurse on the LHS and RHS in here
11105   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11106   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11107 
11108   if (E->getLHS()->getType()->isAtomicType())
11109     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11110 
11111   // Now check the outermost expression
11112   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11113   const auto *RBT = cast<CompoundAssignOperator>(E)
11114                         ->getComputationResultType()
11115                         ->getAs<BuiltinType>();
11116 
11117   // The below checks assume source is floating point.
11118   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11119 
11120   // If source is floating point but target is an integer.
11121   if (ResultBT->isInteger())
11122     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11123                            E->getExprLoc(), diag::warn_impcast_float_integer);
11124 
11125   if (!ResultBT->isFloatingPoint())
11126     return;
11127 
11128   // If both source and target are floating points, warn about losing precision.
11129   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11130       QualType(ResultBT, 0), QualType(RBT, 0));
11131   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11132     // warn about dropping FP rank.
11133     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11134                     diag::warn_impcast_float_result_precision);
11135 }
11136 
11137 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11138                                       IntRange Range) {
11139   if (!Range.Width) return "0";
11140 
11141   llvm::APSInt ValueInRange = Value;
11142   ValueInRange.setIsSigned(!Range.NonNegative);
11143   ValueInRange = ValueInRange.trunc(Range.Width);
11144   return ValueInRange.toString(10);
11145 }
11146 
11147 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11148   if (!isa<ImplicitCastExpr>(Ex))
11149     return false;
11150 
11151   Expr *InnerE = Ex->IgnoreParenImpCasts();
11152   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11153   const Type *Source =
11154     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11155   if (Target->isDependentType())
11156     return false;
11157 
11158   const BuiltinType *FloatCandidateBT =
11159     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11160   const Type *BoolCandidateType = ToBool ? Target : Source;
11161 
11162   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11163           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11164 }
11165 
11166 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11167                                              SourceLocation CC) {
11168   unsigned NumArgs = TheCall->getNumArgs();
11169   for (unsigned i = 0; i < NumArgs; ++i) {
11170     Expr *CurrA = TheCall->getArg(i);
11171     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11172       continue;
11173 
11174     bool IsSwapped = ((i > 0) &&
11175         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11176     IsSwapped |= ((i < (NumArgs - 1)) &&
11177         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11178     if (IsSwapped) {
11179       // Warn on this floating-point to bool conversion.
11180       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11181                       CurrA->getType(), CC,
11182                       diag::warn_impcast_floating_point_to_bool);
11183     }
11184   }
11185 }
11186 
11187 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11188                                    SourceLocation CC) {
11189   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11190                         E->getExprLoc()))
11191     return;
11192 
11193   // Don't warn on functions which have return type nullptr_t.
11194   if (isa<CallExpr>(E))
11195     return;
11196 
11197   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11198   const Expr::NullPointerConstantKind NullKind =
11199       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11200   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11201     return;
11202 
11203   // Return if target type is a safe conversion.
11204   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11205       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11206     return;
11207 
11208   SourceLocation Loc = E->getSourceRange().getBegin();
11209 
11210   // Venture through the macro stacks to get to the source of macro arguments.
11211   // The new location is a better location than the complete location that was
11212   // passed in.
11213   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11214   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11215 
11216   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11217   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11218     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11219         Loc, S.SourceMgr, S.getLangOpts());
11220     if (MacroName == "NULL")
11221       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11222   }
11223 
11224   // Only warn if the null and context location are in the same macro expansion.
11225   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11226     return;
11227 
11228   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11229       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11230       << FixItHint::CreateReplacement(Loc,
11231                                       S.getFixItZeroLiteralForType(T, Loc));
11232 }
11233 
11234 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11235                                   ObjCArrayLiteral *ArrayLiteral);
11236 
11237 static void
11238 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11239                            ObjCDictionaryLiteral *DictionaryLiteral);
11240 
11241 /// Check a single element within a collection literal against the
11242 /// target element type.
11243 static void checkObjCCollectionLiteralElement(Sema &S,
11244                                               QualType TargetElementType,
11245                                               Expr *Element,
11246                                               unsigned ElementKind) {
11247   // Skip a bitcast to 'id' or qualified 'id'.
11248   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11249     if (ICE->getCastKind() == CK_BitCast &&
11250         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11251       Element = ICE->getSubExpr();
11252   }
11253 
11254   QualType ElementType = Element->getType();
11255   ExprResult ElementResult(Element);
11256   if (ElementType->getAs<ObjCObjectPointerType>() &&
11257       S.CheckSingleAssignmentConstraints(TargetElementType,
11258                                          ElementResult,
11259                                          false, false)
11260         != Sema::Compatible) {
11261     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11262         << ElementType << ElementKind << TargetElementType
11263         << Element->getSourceRange();
11264   }
11265 
11266   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11267     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11268   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11269     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11270 }
11271 
11272 /// Check an Objective-C array literal being converted to the given
11273 /// target type.
11274 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11275                                   ObjCArrayLiteral *ArrayLiteral) {
11276   if (!S.NSArrayDecl)
11277     return;
11278 
11279   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11280   if (!TargetObjCPtr)
11281     return;
11282 
11283   if (TargetObjCPtr->isUnspecialized() ||
11284       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11285         != S.NSArrayDecl->getCanonicalDecl())
11286     return;
11287 
11288   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11289   if (TypeArgs.size() != 1)
11290     return;
11291 
11292   QualType TargetElementType = TypeArgs[0];
11293   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11294     checkObjCCollectionLiteralElement(S, TargetElementType,
11295                                       ArrayLiteral->getElement(I),
11296                                       0);
11297   }
11298 }
11299 
11300 /// Check an Objective-C dictionary literal being converted to the given
11301 /// target type.
11302 static void
11303 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11304                            ObjCDictionaryLiteral *DictionaryLiteral) {
11305   if (!S.NSDictionaryDecl)
11306     return;
11307 
11308   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11309   if (!TargetObjCPtr)
11310     return;
11311 
11312   if (TargetObjCPtr->isUnspecialized() ||
11313       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11314         != S.NSDictionaryDecl->getCanonicalDecl())
11315     return;
11316 
11317   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11318   if (TypeArgs.size() != 2)
11319     return;
11320 
11321   QualType TargetKeyType = TypeArgs[0];
11322   QualType TargetObjectType = TypeArgs[1];
11323   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11324     auto Element = DictionaryLiteral->getKeyValueElement(I);
11325     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11326     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11327   }
11328 }
11329 
11330 // Helper function to filter out cases for constant width constant conversion.
11331 // Don't warn on char array initialization or for non-decimal values.
11332 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11333                                           SourceLocation CC) {
11334   // If initializing from a constant, and the constant starts with '0',
11335   // then it is a binary, octal, or hexadecimal.  Allow these constants
11336   // to fill all the bits, even if there is a sign change.
11337   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11338     const char FirstLiteralCharacter =
11339         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11340     if (FirstLiteralCharacter == '0')
11341       return false;
11342   }
11343 
11344   // If the CC location points to a '{', and the type is char, then assume
11345   // assume it is an array initialization.
11346   if (CC.isValid() && T->isCharType()) {
11347     const char FirstContextCharacter =
11348         S.getSourceManager().getCharacterData(CC)[0];
11349     if (FirstContextCharacter == '{')
11350       return false;
11351   }
11352 
11353   return true;
11354 }
11355 
11356 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11357   const auto *IL = dyn_cast<IntegerLiteral>(E);
11358   if (!IL) {
11359     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11360       if (UO->getOpcode() == UO_Minus)
11361         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11362     }
11363   }
11364 
11365   return IL;
11366 }
11367 
11368 static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
11369                                           Expr *LHS, Expr *RHS) {
11370   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
11371   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
11372 
11373   const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
11374   if (!LHSEnumType)
11375     return;
11376   const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
11377   if (!RHSEnumType)
11378     return;
11379 
11380   // Ignore anonymous enums.
11381   if (!LHSEnumType->getDecl()->hasNameForLinkage())
11382     return;
11383   if (!RHSEnumType->getDecl()->hasNameForLinkage())
11384     return;
11385 
11386   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
11387     return;
11388 
11389   S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
11390       << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
11391       << RHS->getSourceRange();
11392 }
11393 
11394 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11395   E = E->IgnoreParenImpCasts();
11396   SourceLocation ExprLoc = E->getExprLoc();
11397 
11398   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11399     BinaryOperator::Opcode Opc = BO->getOpcode();
11400     Expr::EvalResult Result;
11401     // Do not diagnose unsigned shifts.
11402     if (Opc == BO_Shl) {
11403       const auto *LHS = getIntegerLiteral(BO->getLHS());
11404       const auto *RHS = getIntegerLiteral(BO->getRHS());
11405       if (LHS && LHS->getValue() == 0)
11406         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11407       else if (!E->isValueDependent() && LHS && RHS &&
11408                RHS->getValue().isNonNegative() &&
11409                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11410         S.Diag(ExprLoc, diag::warn_left_shift_always)
11411             << (Result.Val.getInt() != 0);
11412       else if (E->getType()->isSignedIntegerType())
11413         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11414     }
11415   }
11416 
11417   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11418     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11419     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11420     if (!LHS || !RHS)
11421       return;
11422     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11423         (RHS->getValue() == 0 || RHS->getValue() == 1))
11424       // Do not diagnose common idioms.
11425       return;
11426     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11427       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11428   }
11429 }
11430 
11431 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11432                                     SourceLocation CC,
11433                                     bool *ICContext = nullptr,
11434                                     bool IsListInit = false) {
11435   if (E->isTypeDependent() || E->isValueDependent()) return;
11436 
11437   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11438   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11439   if (Source == Target) return;
11440   if (Target->isDependentType()) return;
11441 
11442   // If the conversion context location is invalid don't complain. We also
11443   // don't want to emit a warning if the issue occurs from the expansion of
11444   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11445   // delay this check as long as possible. Once we detect we are in that
11446   // scenario, we just return.
11447   if (CC.isInvalid())
11448     return;
11449 
11450   if (Source->isAtomicType())
11451     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11452 
11453   // Diagnose implicit casts to bool.
11454   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11455     if (isa<StringLiteral>(E))
11456       // Warn on string literal to bool.  Checks for string literals in logical
11457       // and expressions, for instance, assert(0 && "error here"), are
11458       // prevented by a check in AnalyzeImplicitConversions().
11459       return DiagnoseImpCast(S, E, T, CC,
11460                              diag::warn_impcast_string_literal_to_bool);
11461     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11462         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11463       // This covers the literal expressions that evaluate to Objective-C
11464       // objects.
11465       return DiagnoseImpCast(S, E, T, CC,
11466                              diag::warn_impcast_objective_c_literal_to_bool);
11467     }
11468     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11469       // Warn on pointer to bool conversion that is always true.
11470       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11471                                      SourceRange(CC));
11472     }
11473   }
11474 
11475   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11476   // is a typedef for signed char (macOS), then that constant value has to be 1
11477   // or 0.
11478   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11479     Expr::EvalResult Result;
11480     if (E->EvaluateAsInt(Result, S.getASTContext(),
11481                          Expr::SE_AllowSideEffects)) {
11482       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11483         adornObjCBoolConversionDiagWithTernaryFixit(
11484             S, E,
11485             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11486                 << Result.Val.getInt().toString(10));
11487       }
11488       return;
11489     }
11490   }
11491 
11492   // Check implicit casts from Objective-C collection literals to specialized
11493   // collection types, e.g., NSArray<NSString *> *.
11494   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11495     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11496   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11497     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11498 
11499   // Strip vector types.
11500   if (isa<VectorType>(Source)) {
11501     if (!isa<VectorType>(Target)) {
11502       if (S.SourceMgr.isInSystemMacro(CC))
11503         return;
11504       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11505     }
11506 
11507     // If the vector cast is cast between two vectors of the same size, it is
11508     // a bitcast, not a conversion.
11509     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11510       return;
11511 
11512     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11513     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11514   }
11515   if (auto VecTy = dyn_cast<VectorType>(Target))
11516     Target = VecTy->getElementType().getTypePtr();
11517 
11518   // Strip complex types.
11519   if (isa<ComplexType>(Source)) {
11520     if (!isa<ComplexType>(Target)) {
11521       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11522         return;
11523 
11524       return DiagnoseImpCast(S, E, T, CC,
11525                              S.getLangOpts().CPlusPlus
11526                                  ? diag::err_impcast_complex_scalar
11527                                  : diag::warn_impcast_complex_scalar);
11528     }
11529 
11530     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11531     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11532   }
11533 
11534   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11535   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11536 
11537   // If the source is floating point...
11538   if (SourceBT && SourceBT->isFloatingPoint()) {
11539     // ...and the target is floating point...
11540     if (TargetBT && TargetBT->isFloatingPoint()) {
11541       // ...then warn if we're dropping FP rank.
11542 
11543       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11544           QualType(SourceBT, 0), QualType(TargetBT, 0));
11545       if (Order > 0) {
11546         // Don't warn about float constants that are precisely
11547         // representable in the target type.
11548         Expr::EvalResult result;
11549         if (E->EvaluateAsRValue(result, S.Context)) {
11550           // Value might be a float, a float vector, or a float complex.
11551           if (IsSameFloatAfterCast(result.Val,
11552                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11553                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11554             return;
11555         }
11556 
11557         if (S.SourceMgr.isInSystemMacro(CC))
11558           return;
11559 
11560         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11561       }
11562       // ... or possibly if we're increasing rank, too
11563       else if (Order < 0) {
11564         if (S.SourceMgr.isInSystemMacro(CC))
11565           return;
11566 
11567         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11568       }
11569       return;
11570     }
11571 
11572     // If the target is integral, always warn.
11573     if (TargetBT && TargetBT->isInteger()) {
11574       if (S.SourceMgr.isInSystemMacro(CC))
11575         return;
11576 
11577       DiagnoseFloatingImpCast(S, E, T, CC);
11578     }
11579 
11580     // Detect the case where a call result is converted from floating-point to
11581     // to bool, and the final argument to the call is converted from bool, to
11582     // discover this typo:
11583     //
11584     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11585     //
11586     // FIXME: This is an incredibly special case; is there some more general
11587     // way to detect this class of misplaced-parentheses bug?
11588     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11589       // Check last argument of function call to see if it is an
11590       // implicit cast from a type matching the type the result
11591       // is being cast to.
11592       CallExpr *CEx = cast<CallExpr>(E);
11593       if (unsigned NumArgs = CEx->getNumArgs()) {
11594         Expr *LastA = CEx->getArg(NumArgs - 1);
11595         Expr *InnerE = LastA->IgnoreParenImpCasts();
11596         if (isa<ImplicitCastExpr>(LastA) &&
11597             InnerE->getType()->isBooleanType()) {
11598           // Warn on this floating-point to bool conversion
11599           DiagnoseImpCast(S, E, T, CC,
11600                           diag::warn_impcast_floating_point_to_bool);
11601         }
11602       }
11603     }
11604     return;
11605   }
11606 
11607   // Valid casts involving fixed point types should be accounted for here.
11608   if (Source->isFixedPointType()) {
11609     if (Target->isUnsaturatedFixedPointType()) {
11610       Expr::EvalResult Result;
11611       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11612                                   S.isConstantEvaluated())) {
11613         APFixedPoint Value = Result.Val.getFixedPoint();
11614         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11615         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11616         if (Value > MaxVal || Value < MinVal) {
11617           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11618                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11619                                     << Value.toString() << T
11620                                     << E->getSourceRange()
11621                                     << clang::SourceRange(CC));
11622           return;
11623         }
11624       }
11625     } else if (Target->isIntegerType()) {
11626       Expr::EvalResult Result;
11627       if (!S.isConstantEvaluated() &&
11628           E->EvaluateAsFixedPoint(Result, S.Context,
11629                                   Expr::SE_AllowSideEffects)) {
11630         APFixedPoint FXResult = Result.Val.getFixedPoint();
11631 
11632         bool Overflowed;
11633         llvm::APSInt IntResult = FXResult.convertToInt(
11634             S.Context.getIntWidth(T),
11635             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11636 
11637         if (Overflowed) {
11638           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11639                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11640                                     << FXResult.toString() << T
11641                                     << E->getSourceRange()
11642                                     << clang::SourceRange(CC));
11643           return;
11644         }
11645       }
11646     }
11647   } else if (Target->isUnsaturatedFixedPointType()) {
11648     if (Source->isIntegerType()) {
11649       Expr::EvalResult Result;
11650       if (!S.isConstantEvaluated() &&
11651           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11652         llvm::APSInt Value = Result.Val.getInt();
11653 
11654         bool Overflowed;
11655         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11656             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11657 
11658         if (Overflowed) {
11659           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11660                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11661                                     << Value.toString(/*Radix=*/10) << T
11662                                     << E->getSourceRange()
11663                                     << clang::SourceRange(CC));
11664           return;
11665         }
11666       }
11667     }
11668   }
11669 
11670   // If we are casting an integer type to a floating point type without
11671   // initialization-list syntax, we might lose accuracy if the floating
11672   // point type has a narrower significand than the integer type.
11673   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11674       TargetBT->isFloatingType() && !IsListInit) {
11675     // Determine the number of precision bits in the source integer type.
11676     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11677     unsigned int SourcePrecision = SourceRange.Width;
11678 
11679     // Determine the number of precision bits in the
11680     // target floating point type.
11681     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11682         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11683 
11684     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11685         SourcePrecision > TargetPrecision) {
11686 
11687       llvm::APSInt SourceInt;
11688       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11689         // If the source integer is a constant, convert it to the target
11690         // floating point type. Issue a warning if the value changes
11691         // during the whole conversion.
11692         llvm::APFloat TargetFloatValue(
11693             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11694         llvm::APFloat::opStatus ConversionStatus =
11695             TargetFloatValue.convertFromAPInt(
11696                 SourceInt, SourceBT->isSignedInteger(),
11697                 llvm::APFloat::rmNearestTiesToEven);
11698 
11699         if (ConversionStatus != llvm::APFloat::opOK) {
11700           std::string PrettySourceValue = SourceInt.toString(10);
11701           SmallString<32> PrettyTargetValue;
11702           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11703 
11704           S.DiagRuntimeBehavior(
11705               E->getExprLoc(), E,
11706               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11707                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11708                   << E->getSourceRange() << clang::SourceRange(CC));
11709         }
11710       } else {
11711         // Otherwise, the implicit conversion may lose precision.
11712         DiagnoseImpCast(S, E, T, CC,
11713                         diag::warn_impcast_integer_float_precision);
11714       }
11715     }
11716   }
11717 
11718   DiagnoseNullConversion(S, E, T, CC);
11719 
11720   S.DiscardMisalignedMemberAddress(Target, E);
11721 
11722   if (Target->isBooleanType())
11723     DiagnoseIntInBoolContext(S, E);
11724 
11725   if (!Source->isIntegerType() || !Target->isIntegerType())
11726     return;
11727 
11728   // TODO: remove this early return once the false positives for constant->bool
11729   // in templates, macros, etc, are reduced or removed.
11730   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11731     return;
11732 
11733   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11734       !E->isKnownToHaveBooleanValue()) {
11735     return adornObjCBoolConversionDiagWithTernaryFixit(
11736         S, E,
11737         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11738             << E->getType());
11739   }
11740 
11741   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11742   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11743 
11744   if (SourceRange.Width > TargetRange.Width) {
11745     // If the source is a constant, use a default-on diagnostic.
11746     // TODO: this should happen for bitfield stores, too.
11747     Expr::EvalResult Result;
11748     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11749                          S.isConstantEvaluated())) {
11750       llvm::APSInt Value(32);
11751       Value = Result.Val.getInt();
11752 
11753       if (S.SourceMgr.isInSystemMacro(CC))
11754         return;
11755 
11756       std::string PrettySourceValue = Value.toString(10);
11757       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11758 
11759       S.DiagRuntimeBehavior(
11760           E->getExprLoc(), E,
11761           S.PDiag(diag::warn_impcast_integer_precision_constant)
11762               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11763               << E->getSourceRange() << clang::SourceRange(CC));
11764       return;
11765     }
11766 
11767     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11768     if (S.SourceMgr.isInSystemMacro(CC))
11769       return;
11770 
11771     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11772       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11773                              /* pruneControlFlow */ true);
11774     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11775   }
11776 
11777   if (TargetRange.Width > SourceRange.Width) {
11778     if (auto *UO = dyn_cast<UnaryOperator>(E))
11779       if (UO->getOpcode() == UO_Minus)
11780         if (Source->isUnsignedIntegerType()) {
11781           if (Target->isUnsignedIntegerType())
11782             return DiagnoseImpCast(S, E, T, CC,
11783                                    diag::warn_impcast_high_order_zero_bits);
11784           if (Target->isSignedIntegerType())
11785             return DiagnoseImpCast(S, E, T, CC,
11786                                    diag::warn_impcast_nonnegative_result);
11787         }
11788   }
11789 
11790   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11791       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11792     // Warn when doing a signed to signed conversion, warn if the positive
11793     // source value is exactly the width of the target type, which will
11794     // cause a negative value to be stored.
11795 
11796     Expr::EvalResult Result;
11797     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11798         !S.SourceMgr.isInSystemMacro(CC)) {
11799       llvm::APSInt Value = Result.Val.getInt();
11800       if (isSameWidthConstantConversion(S, E, T, CC)) {
11801         std::string PrettySourceValue = Value.toString(10);
11802         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11803 
11804         S.DiagRuntimeBehavior(
11805             E->getExprLoc(), E,
11806             S.PDiag(diag::warn_impcast_integer_precision_constant)
11807                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11808                 << E->getSourceRange() << clang::SourceRange(CC));
11809         return;
11810       }
11811     }
11812 
11813     // Fall through for non-constants to give a sign conversion warning.
11814   }
11815 
11816   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11817       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11818        SourceRange.Width == TargetRange.Width)) {
11819     if (S.SourceMgr.isInSystemMacro(CC))
11820       return;
11821 
11822     unsigned DiagID = diag::warn_impcast_integer_sign;
11823 
11824     // Traditionally, gcc has warned about this under -Wsign-compare.
11825     // We also want to warn about it in -Wconversion.
11826     // So if -Wconversion is off, use a completely identical diagnostic
11827     // in the sign-compare group.
11828     // The conditional-checking code will
11829     if (ICContext) {
11830       DiagID = diag::warn_impcast_integer_sign_conditional;
11831       *ICContext = true;
11832     }
11833 
11834     return DiagnoseImpCast(S, E, T, CC, DiagID);
11835   }
11836 
11837   // Diagnose conversions between different enumeration types.
11838   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11839   // type, to give us better diagnostics.
11840   QualType SourceType = E->getType();
11841   if (!S.getLangOpts().CPlusPlus) {
11842     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11843       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11844         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11845         SourceType = S.Context.getTypeDeclType(Enum);
11846         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11847       }
11848   }
11849 
11850   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11851     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11852       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11853           TargetEnum->getDecl()->hasNameForLinkage() &&
11854           SourceEnum != TargetEnum) {
11855         if (S.SourceMgr.isInSystemMacro(CC))
11856           return;
11857 
11858         return DiagnoseImpCast(S, E, SourceType, T, CC,
11859                                diag::warn_impcast_different_enum_types);
11860       }
11861 }
11862 
11863 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11864                                      SourceLocation CC, QualType T);
11865 
11866 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11867                                     SourceLocation CC, bool &ICContext) {
11868   E = E->IgnoreParenImpCasts();
11869 
11870   if (isa<ConditionalOperator>(E))
11871     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11872 
11873   AnalyzeImplicitConversions(S, E, CC);
11874   if (E->getType() != T)
11875     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11876 }
11877 
11878 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11879                                      SourceLocation CC, QualType T) {
11880   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11881 
11882   bool Suspicious = false;
11883   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11884   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11885   CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
11886                                 E->getFalseExpr());
11887 
11888   if (T->isBooleanType())
11889     DiagnoseIntInBoolContext(S, E);
11890 
11891   // If -Wconversion would have warned about either of the candidates
11892   // for a signedness conversion to the context type...
11893   if (!Suspicious) return;
11894 
11895   // ...but it's currently ignored...
11896   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11897     return;
11898 
11899   // ...then check whether it would have warned about either of the
11900   // candidates for a signedness conversion to the condition type.
11901   if (E->getType() == T) return;
11902 
11903   Suspicious = false;
11904   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11905                           E->getType(), CC, &Suspicious);
11906   if (!Suspicious)
11907     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11908                             E->getType(), CC, &Suspicious);
11909 }
11910 
11911 /// Check conversion of given expression to boolean.
11912 /// Input argument E is a logical expression.
11913 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11914   if (S.getLangOpts().Bool)
11915     return;
11916   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11917     return;
11918   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11919 }
11920 
11921 /// AnalyzeImplicitConversions - Find and report any interesting
11922 /// implicit conversions in the given expression.  There are a couple
11923 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11924 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11925                                        bool IsListInit/*= false*/) {
11926   QualType T = OrigE->getType();
11927   Expr *E = OrigE->IgnoreParenImpCasts();
11928 
11929   // Propagate whether we are in a C++ list initialization expression.
11930   // If so, we do not issue warnings for implicit int-float conversion
11931   // precision loss, because C++11 narrowing already handles it.
11932   IsListInit =
11933       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11934 
11935   if (E->isTypeDependent() || E->isValueDependent())
11936     return;
11937 
11938   if (const auto *UO = dyn_cast<UnaryOperator>(E))
11939     if (UO->getOpcode() == UO_Not &&
11940         UO->getSubExpr()->isKnownToHaveBooleanValue())
11941       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11942           << OrigE->getSourceRange() << T->isBooleanType()
11943           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11944 
11945   // For conditional operators, we analyze the arguments as if they
11946   // were being fed directly into the output.
11947   if (isa<ConditionalOperator>(E)) {
11948     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11949     CheckConditionalOperator(S, CO, CC, T);
11950     return;
11951   }
11952 
11953   // Check implicit argument conversions for function calls.
11954   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11955     CheckImplicitArgumentConversions(S, Call, CC);
11956 
11957   // Go ahead and check any implicit conversions we might have skipped.
11958   // The non-canonical typecheck is just an optimization;
11959   // CheckImplicitConversion will filter out dead implicit conversions.
11960   if (E->getType() != T)
11961     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
11962 
11963   // Now continue drilling into this expression.
11964 
11965   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11966     // The bound subexpressions in a PseudoObjectExpr are not reachable
11967     // as transitive children.
11968     // FIXME: Use a more uniform representation for this.
11969     for (auto *SE : POE->semantics())
11970       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11971         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
11972   }
11973 
11974   // Skip past explicit casts.
11975   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11976     E = CE->getSubExpr()->IgnoreParenImpCasts();
11977     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11978       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11979     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
11980   }
11981 
11982   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11983     // Do a somewhat different check with comparison operators.
11984     if (BO->isComparisonOp())
11985       return AnalyzeComparison(S, BO);
11986 
11987     // And with simple assignments.
11988     if (BO->getOpcode() == BO_Assign)
11989       return AnalyzeAssignment(S, BO);
11990     // And with compound assignments.
11991     if (BO->isAssignmentOp())
11992       return AnalyzeCompoundAssignment(S, BO);
11993   }
11994 
11995   // These break the otherwise-useful invariant below.  Fortunately,
11996   // we don't really need to recurse into them, because any internal
11997   // expressions should have been analyzed already when they were
11998   // built into statements.
11999   if (isa<StmtExpr>(E)) return;
12000 
12001   // Don't descend into unevaluated contexts.
12002   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12003 
12004   // Now just recurse over the expression's children.
12005   CC = E->getExprLoc();
12006   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12007   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12008   for (Stmt *SubStmt : E->children()) {
12009     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12010     if (!ChildExpr)
12011       continue;
12012 
12013     if (IsLogicalAndOperator &&
12014         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12015       // Ignore checking string literals that are in logical and operators.
12016       // This is a common pattern for asserts.
12017       continue;
12018     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
12019   }
12020 
12021   if (BO && BO->isLogicalOp()) {
12022     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12023     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12024       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12025 
12026     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12027     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12028       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12029   }
12030 
12031   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12032     if (U->getOpcode() == UO_LNot) {
12033       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12034     } else if (U->getOpcode() != UO_AddrOf) {
12035       if (U->getSubExpr()->getType()->isAtomicType())
12036         S.Diag(U->getSubExpr()->getBeginLoc(),
12037                diag::warn_atomic_implicit_seq_cst);
12038     }
12039   }
12040 }
12041 
12042 /// Diagnose integer type and any valid implicit conversion to it.
12043 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12044   // Taking into account implicit conversions,
12045   // allow any integer.
12046   if (!E->getType()->isIntegerType()) {
12047     S.Diag(E->getBeginLoc(),
12048            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12049     return true;
12050   }
12051   // Potentially emit standard warnings for implicit conversions if enabled
12052   // using -Wconversion.
12053   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12054   return false;
12055 }
12056 
12057 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12058 // Returns true when emitting a warning about taking the address of a reference.
12059 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12060                               const PartialDiagnostic &PD) {
12061   E = E->IgnoreParenImpCasts();
12062 
12063   const FunctionDecl *FD = nullptr;
12064 
12065   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12066     if (!DRE->getDecl()->getType()->isReferenceType())
12067       return false;
12068   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12069     if (!M->getMemberDecl()->getType()->isReferenceType())
12070       return false;
12071   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12072     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12073       return false;
12074     FD = Call->getDirectCallee();
12075   } else {
12076     return false;
12077   }
12078 
12079   SemaRef.Diag(E->getExprLoc(), PD);
12080 
12081   // If possible, point to location of function.
12082   if (FD) {
12083     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12084   }
12085 
12086   return true;
12087 }
12088 
12089 // Returns true if the SourceLocation is expanded from any macro body.
12090 // Returns false if the SourceLocation is invalid, is from not in a macro
12091 // expansion, or is from expanded from a top-level macro argument.
12092 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12093   if (Loc.isInvalid())
12094     return false;
12095 
12096   while (Loc.isMacroID()) {
12097     if (SM.isMacroBodyExpansion(Loc))
12098       return true;
12099     Loc = SM.getImmediateMacroCallerLoc(Loc);
12100   }
12101 
12102   return false;
12103 }
12104 
12105 /// Diagnose pointers that are always non-null.
12106 /// \param E the expression containing the pointer
12107 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12108 /// compared to a null pointer
12109 /// \param IsEqual True when the comparison is equal to a null pointer
12110 /// \param Range Extra SourceRange to highlight in the diagnostic
12111 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12112                                         Expr::NullPointerConstantKind NullKind,
12113                                         bool IsEqual, SourceRange Range) {
12114   if (!E)
12115     return;
12116 
12117   // Don't warn inside macros.
12118   if (E->getExprLoc().isMacroID()) {
12119     const SourceManager &SM = getSourceManager();
12120     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12121         IsInAnyMacroBody(SM, Range.getBegin()))
12122       return;
12123   }
12124   E = E->IgnoreImpCasts();
12125 
12126   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12127 
12128   if (isa<CXXThisExpr>(E)) {
12129     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12130                                 : diag::warn_this_bool_conversion;
12131     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12132     return;
12133   }
12134 
12135   bool IsAddressOf = false;
12136 
12137   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12138     if (UO->getOpcode() != UO_AddrOf)
12139       return;
12140     IsAddressOf = true;
12141     E = UO->getSubExpr();
12142   }
12143 
12144   if (IsAddressOf) {
12145     unsigned DiagID = IsCompare
12146                           ? diag::warn_address_of_reference_null_compare
12147                           : diag::warn_address_of_reference_bool_conversion;
12148     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12149                                          << IsEqual;
12150     if (CheckForReference(*this, E, PD)) {
12151       return;
12152     }
12153   }
12154 
12155   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12156     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12157     std::string Str;
12158     llvm::raw_string_ostream S(Str);
12159     E->printPretty(S, nullptr, getPrintingPolicy());
12160     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12161                                 : diag::warn_cast_nonnull_to_bool;
12162     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12163       << E->getSourceRange() << Range << IsEqual;
12164     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12165   };
12166 
12167   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12168   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12169     if (auto *Callee = Call->getDirectCallee()) {
12170       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12171         ComplainAboutNonnullParamOrCall(A);
12172         return;
12173       }
12174     }
12175   }
12176 
12177   // Expect to find a single Decl.  Skip anything more complicated.
12178   ValueDecl *D = nullptr;
12179   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12180     D = R->getDecl();
12181   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12182     D = M->getMemberDecl();
12183   }
12184 
12185   // Weak Decls can be null.
12186   if (!D || D->isWeak())
12187     return;
12188 
12189   // Check for parameter decl with nonnull attribute
12190   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12191     if (getCurFunction() &&
12192         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12193       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12194         ComplainAboutNonnullParamOrCall(A);
12195         return;
12196       }
12197 
12198       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12199         // Skip function template not specialized yet.
12200         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12201           return;
12202         auto ParamIter = llvm::find(FD->parameters(), PV);
12203         assert(ParamIter != FD->param_end());
12204         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12205 
12206         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12207           if (!NonNull->args_size()) {
12208               ComplainAboutNonnullParamOrCall(NonNull);
12209               return;
12210           }
12211 
12212           for (const ParamIdx &ArgNo : NonNull->args()) {
12213             if (ArgNo.getASTIndex() == ParamNo) {
12214               ComplainAboutNonnullParamOrCall(NonNull);
12215               return;
12216             }
12217           }
12218         }
12219       }
12220     }
12221   }
12222 
12223   QualType T = D->getType();
12224   const bool IsArray = T->isArrayType();
12225   const bool IsFunction = T->isFunctionType();
12226 
12227   // Address of function is used to silence the function warning.
12228   if (IsAddressOf && IsFunction) {
12229     return;
12230   }
12231 
12232   // Found nothing.
12233   if (!IsAddressOf && !IsFunction && !IsArray)
12234     return;
12235 
12236   // Pretty print the expression for the diagnostic.
12237   std::string Str;
12238   llvm::raw_string_ostream S(Str);
12239   E->printPretty(S, nullptr, getPrintingPolicy());
12240 
12241   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12242                               : diag::warn_impcast_pointer_to_bool;
12243   enum {
12244     AddressOf,
12245     FunctionPointer,
12246     ArrayPointer
12247   } DiagType;
12248   if (IsAddressOf)
12249     DiagType = AddressOf;
12250   else if (IsFunction)
12251     DiagType = FunctionPointer;
12252   else if (IsArray)
12253     DiagType = ArrayPointer;
12254   else
12255     llvm_unreachable("Could not determine diagnostic.");
12256   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12257                                 << Range << IsEqual;
12258 
12259   if (!IsFunction)
12260     return;
12261 
12262   // Suggest '&' to silence the function warning.
12263   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12264       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12265 
12266   // Check to see if '()' fixit should be emitted.
12267   QualType ReturnType;
12268   UnresolvedSet<4> NonTemplateOverloads;
12269   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12270   if (ReturnType.isNull())
12271     return;
12272 
12273   if (IsCompare) {
12274     // There are two cases here.  If there is null constant, the only suggest
12275     // for a pointer return type.  If the null is 0, then suggest if the return
12276     // type is a pointer or an integer type.
12277     if (!ReturnType->isPointerType()) {
12278       if (NullKind == Expr::NPCK_ZeroExpression ||
12279           NullKind == Expr::NPCK_ZeroLiteral) {
12280         if (!ReturnType->isIntegerType())
12281           return;
12282       } else {
12283         return;
12284       }
12285     }
12286   } else { // !IsCompare
12287     // For function to bool, only suggest if the function pointer has bool
12288     // return type.
12289     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12290       return;
12291   }
12292   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12293       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12294 }
12295 
12296 /// Diagnoses "dangerous" implicit conversions within the given
12297 /// expression (which is a full expression).  Implements -Wconversion
12298 /// and -Wsign-compare.
12299 ///
12300 /// \param CC the "context" location of the implicit conversion, i.e.
12301 ///   the most location of the syntactic entity requiring the implicit
12302 ///   conversion
12303 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12304   // Don't diagnose in unevaluated contexts.
12305   if (isUnevaluatedContext())
12306     return;
12307 
12308   // Don't diagnose for value- or type-dependent expressions.
12309   if (E->isTypeDependent() || E->isValueDependent())
12310     return;
12311 
12312   // Check for array bounds violations in cases where the check isn't triggered
12313   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12314   // ArraySubscriptExpr is on the RHS of a variable initialization.
12315   CheckArrayAccess(E);
12316 
12317   // This is not the right CC for (e.g.) a variable initialization.
12318   AnalyzeImplicitConversions(*this, E, CC);
12319 }
12320 
12321 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12322 /// Input argument E is a logical expression.
12323 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12324   ::CheckBoolLikeConversion(*this, E, CC);
12325 }
12326 
12327 /// Diagnose when expression is an integer constant expression and its evaluation
12328 /// results in integer overflow
12329 void Sema::CheckForIntOverflow (Expr *E) {
12330   // Use a work list to deal with nested struct initializers.
12331   SmallVector<Expr *, 2> Exprs(1, E);
12332 
12333   do {
12334     Expr *OriginalE = Exprs.pop_back_val();
12335     Expr *E = OriginalE->IgnoreParenCasts();
12336 
12337     if (isa<BinaryOperator>(E)) {
12338       E->EvaluateForOverflow(Context);
12339       continue;
12340     }
12341 
12342     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12343       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12344     else if (isa<ObjCBoxedExpr>(OriginalE))
12345       E->EvaluateForOverflow(Context);
12346     else if (auto Call = dyn_cast<CallExpr>(E))
12347       Exprs.append(Call->arg_begin(), Call->arg_end());
12348     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12349       Exprs.append(Message->arg_begin(), Message->arg_end());
12350   } while (!Exprs.empty());
12351 }
12352 
12353 namespace {
12354 
12355 /// Visitor for expressions which looks for unsequenced operations on the
12356 /// same object.
12357 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
12358   using Base = EvaluatedExprVisitor<SequenceChecker>;
12359 
12360   /// A tree of sequenced regions within an expression. Two regions are
12361   /// unsequenced if one is an ancestor or a descendent of the other. When we
12362   /// finish processing an expression with sequencing, such as a comma
12363   /// expression, we fold its tree nodes into its parent, since they are
12364   /// unsequenced with respect to nodes we will visit later.
12365   class SequenceTree {
12366     struct Value {
12367       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12368       unsigned Parent : 31;
12369       unsigned Merged : 1;
12370     };
12371     SmallVector<Value, 8> Values;
12372 
12373   public:
12374     /// A region within an expression which may be sequenced with respect
12375     /// to some other region.
12376     class Seq {
12377       friend class SequenceTree;
12378 
12379       unsigned Index;
12380 
12381       explicit Seq(unsigned N) : Index(N) {}
12382 
12383     public:
12384       Seq() : Index(0) {}
12385     };
12386 
12387     SequenceTree() { Values.push_back(Value(0)); }
12388     Seq root() const { return Seq(0); }
12389 
12390     /// Create a new sequence of operations, which is an unsequenced
12391     /// subset of \p Parent. This sequence of operations is sequenced with
12392     /// respect to other children of \p Parent.
12393     Seq allocate(Seq Parent) {
12394       Values.push_back(Value(Parent.Index));
12395       return Seq(Values.size() - 1);
12396     }
12397 
12398     /// Merge a sequence of operations into its parent.
12399     void merge(Seq S) {
12400       Values[S.Index].Merged = true;
12401     }
12402 
12403     /// Determine whether two operations are unsequenced. This operation
12404     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12405     /// should have been merged into its parent as appropriate.
12406     bool isUnsequenced(Seq Cur, Seq Old) {
12407       unsigned C = representative(Cur.Index);
12408       unsigned Target = representative(Old.Index);
12409       while (C >= Target) {
12410         if (C == Target)
12411           return true;
12412         C = Values[C].Parent;
12413       }
12414       return false;
12415     }
12416 
12417   private:
12418     /// Pick a representative for a sequence.
12419     unsigned representative(unsigned K) {
12420       if (Values[K].Merged)
12421         // Perform path compression as we go.
12422         return Values[K].Parent = representative(Values[K].Parent);
12423       return K;
12424     }
12425   };
12426 
12427   /// An object for which we can track unsequenced uses.
12428   using Object = NamedDecl *;
12429 
12430   /// Different flavors of object usage which we track. We only track the
12431   /// least-sequenced usage of each kind.
12432   enum UsageKind {
12433     /// A read of an object. Multiple unsequenced reads are OK.
12434     UK_Use,
12435 
12436     /// A modification of an object which is sequenced before the value
12437     /// computation of the expression, such as ++n in C++.
12438     UK_ModAsValue,
12439 
12440     /// A modification of an object which is not sequenced before the value
12441     /// computation of the expression, such as n++.
12442     UK_ModAsSideEffect,
12443 
12444     UK_Count = UK_ModAsSideEffect + 1
12445   };
12446 
12447   struct Usage {
12448     Expr *Use;
12449     SequenceTree::Seq Seq;
12450 
12451     Usage() : Use(nullptr), Seq() {}
12452   };
12453 
12454   struct UsageInfo {
12455     Usage Uses[UK_Count];
12456 
12457     /// Have we issued a diagnostic for this variable already?
12458     bool Diagnosed;
12459 
12460     UsageInfo() : Uses(), Diagnosed(false) {}
12461   };
12462   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12463 
12464   Sema &SemaRef;
12465 
12466   /// Sequenced regions within the expression.
12467   SequenceTree Tree;
12468 
12469   /// Declaration modifications and references which we have seen.
12470   UsageInfoMap UsageMap;
12471 
12472   /// The region we are currently within.
12473   SequenceTree::Seq Region;
12474 
12475   /// Filled in with declarations which were modified as a side-effect
12476   /// (that is, post-increment operations).
12477   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12478 
12479   /// Expressions to check later. We defer checking these to reduce
12480   /// stack usage.
12481   SmallVectorImpl<Expr *> &WorkList;
12482 
12483   /// RAII object wrapping the visitation of a sequenced subexpression of an
12484   /// expression. At the end of this process, the side-effects of the evaluation
12485   /// become sequenced with respect to the value computation of the result, so
12486   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12487   /// UK_ModAsValue.
12488   struct SequencedSubexpression {
12489     SequencedSubexpression(SequenceChecker &Self)
12490       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12491       Self.ModAsSideEffect = &ModAsSideEffect;
12492     }
12493 
12494     ~SequencedSubexpression() {
12495       for (auto &M : llvm::reverse(ModAsSideEffect)) {
12496         UsageInfo &U = Self.UsageMap[M.first];
12497         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12498         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12499         SideEffectUsage = M.second;
12500       }
12501       Self.ModAsSideEffect = OldModAsSideEffect;
12502     }
12503 
12504     SequenceChecker &Self;
12505     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12506     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12507   };
12508 
12509   /// RAII object wrapping the visitation of a subexpression which we might
12510   /// choose to evaluate as a constant. If any subexpression is evaluated and
12511   /// found to be non-constant, this allows us to suppress the evaluation of
12512   /// the outer expression.
12513   class EvaluationTracker {
12514   public:
12515     EvaluationTracker(SequenceChecker &Self)
12516         : Self(Self), Prev(Self.EvalTracker) {
12517       Self.EvalTracker = this;
12518     }
12519 
12520     ~EvaluationTracker() {
12521       Self.EvalTracker = Prev;
12522       if (Prev)
12523         Prev->EvalOK &= EvalOK;
12524     }
12525 
12526     bool evaluate(const Expr *E, bool &Result) {
12527       if (!EvalOK || E->isValueDependent())
12528         return false;
12529       EvalOK = E->EvaluateAsBooleanCondition(
12530           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12531       return EvalOK;
12532     }
12533 
12534   private:
12535     SequenceChecker &Self;
12536     EvaluationTracker *Prev;
12537     bool EvalOK = true;
12538   } *EvalTracker = nullptr;
12539 
12540   /// Find the object which is produced by the specified expression,
12541   /// if any.
12542   Object getObject(Expr *E, bool Mod) const {
12543     E = E->IgnoreParenCasts();
12544     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12545       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12546         return getObject(UO->getSubExpr(), Mod);
12547     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12548       if (BO->getOpcode() == BO_Comma)
12549         return getObject(BO->getRHS(), Mod);
12550       if (Mod && BO->isAssignmentOp())
12551         return getObject(BO->getLHS(), Mod);
12552     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12553       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12554       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12555         return ME->getMemberDecl();
12556     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12557       // FIXME: If this is a reference, map through to its value.
12558       return DRE->getDecl();
12559     return nullptr;
12560   }
12561 
12562   /// Note that an object was modified or used by an expression.
12563   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12564     Usage &U = UI.Uses[UK];
12565     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12566       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12567         ModAsSideEffect->push_back(std::make_pair(O, U));
12568       U.Use = Ref;
12569       U.Seq = Region;
12570     }
12571   }
12572 
12573   /// Check whether a modification or use conflicts with a prior usage.
12574   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12575                   bool IsModMod) {
12576     if (UI.Diagnosed)
12577       return;
12578 
12579     const Usage &U = UI.Uses[OtherKind];
12580     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12581       return;
12582 
12583     Expr *Mod = U.Use;
12584     Expr *ModOrUse = Ref;
12585     if (OtherKind == UK_Use)
12586       std::swap(Mod, ModOrUse);
12587 
12588     SemaRef.DiagRuntimeBehavior(
12589         Mod->getExprLoc(), {Mod, ModOrUse},
12590         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12591                                : diag::warn_unsequenced_mod_use)
12592             << O << SourceRange(ModOrUse->getExprLoc()));
12593     UI.Diagnosed = true;
12594   }
12595 
12596   void notePreUse(Object O, Expr *Use) {
12597     UsageInfo &U = UsageMap[O];
12598     // Uses conflict with other modifications.
12599     checkUsage(O, U, Use, UK_ModAsValue, false);
12600   }
12601 
12602   void notePostUse(Object O, Expr *Use) {
12603     UsageInfo &U = UsageMap[O];
12604     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12605     addUsage(U, O, Use, UK_Use);
12606   }
12607 
12608   void notePreMod(Object O, Expr *Mod) {
12609     UsageInfo &U = UsageMap[O];
12610     // Modifications conflict with other modifications and with uses.
12611     checkUsage(O, U, Mod, UK_ModAsValue, true);
12612     checkUsage(O, U, Mod, UK_Use, false);
12613   }
12614 
12615   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12616     UsageInfo &U = UsageMap[O];
12617     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12618     addUsage(U, O, Use, UK);
12619   }
12620 
12621 public:
12622   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12623       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12624     Visit(E);
12625   }
12626 
12627   void VisitStmt(Stmt *S) {
12628     // Skip all statements which aren't expressions for now.
12629   }
12630 
12631   void VisitExpr(Expr *E) {
12632     // By default, just recurse to evaluated subexpressions.
12633     Base::VisitStmt(E);
12634   }
12635 
12636   void VisitCastExpr(CastExpr *E) {
12637     Object O = Object();
12638     if (E->getCastKind() == CK_LValueToRValue)
12639       O = getObject(E->getSubExpr(), false);
12640 
12641     if (O)
12642       notePreUse(O, E);
12643     VisitExpr(E);
12644     if (O)
12645       notePostUse(O, E);
12646   }
12647 
12648   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12649     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12650     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12651     SequenceTree::Seq OldRegion = Region;
12652 
12653     {
12654       SequencedSubexpression SeqBefore(*this);
12655       Region = BeforeRegion;
12656       Visit(SequencedBefore);
12657     }
12658 
12659     Region = AfterRegion;
12660     Visit(SequencedAfter);
12661 
12662     Region = OldRegion;
12663 
12664     Tree.merge(BeforeRegion);
12665     Tree.merge(AfterRegion);
12666   }
12667 
12668   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12669     // C++17 [expr.sub]p1:
12670     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12671     //   expression E1 is sequenced before the expression E2.
12672     if (SemaRef.getLangOpts().CPlusPlus17)
12673       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12674     else
12675       Base::VisitStmt(ASE);
12676   }
12677 
12678   void VisitBinComma(BinaryOperator *BO) {
12679     // C++11 [expr.comma]p1:
12680     //   Every value computation and side effect associated with the left
12681     //   expression is sequenced before every value computation and side
12682     //   effect associated with the right expression.
12683     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12684   }
12685 
12686   void VisitBinAssign(BinaryOperator *BO) {
12687     // The modification is sequenced after the value computation of the LHS
12688     // and RHS, so check it before inspecting the operands and update the
12689     // map afterwards.
12690     Object O = getObject(BO->getLHS(), true);
12691     if (!O)
12692       return VisitExpr(BO);
12693 
12694     notePreMod(O, BO);
12695 
12696     // C++11 [expr.ass]p7:
12697     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12698     //   only once.
12699     //
12700     // Therefore, for a compound assignment operator, O is considered used
12701     // everywhere except within the evaluation of E1 itself.
12702     if (isa<CompoundAssignOperator>(BO))
12703       notePreUse(O, BO);
12704 
12705     Visit(BO->getLHS());
12706 
12707     if (isa<CompoundAssignOperator>(BO))
12708       notePostUse(O, BO);
12709 
12710     Visit(BO->getRHS());
12711 
12712     // C++11 [expr.ass]p1:
12713     //   the assignment is sequenced [...] before the value computation of the
12714     //   assignment expression.
12715     // C11 6.5.16/3 has no such rule.
12716     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12717                                                        : UK_ModAsSideEffect);
12718   }
12719 
12720   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12721     VisitBinAssign(CAO);
12722   }
12723 
12724   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12725   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12726   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12727     Object O = getObject(UO->getSubExpr(), true);
12728     if (!O)
12729       return VisitExpr(UO);
12730 
12731     notePreMod(O, UO);
12732     Visit(UO->getSubExpr());
12733     // C++11 [expr.pre.incr]p1:
12734     //   the expression ++x is equivalent to x+=1
12735     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12736                                                        : UK_ModAsSideEffect);
12737   }
12738 
12739   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12740   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12741   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12742     Object O = getObject(UO->getSubExpr(), true);
12743     if (!O)
12744       return VisitExpr(UO);
12745 
12746     notePreMod(O, UO);
12747     Visit(UO->getSubExpr());
12748     notePostMod(O, UO, UK_ModAsSideEffect);
12749   }
12750 
12751   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12752   void VisitBinLOr(BinaryOperator *BO) {
12753     // The side-effects of the LHS of an '&&' are sequenced before the
12754     // value computation of the RHS, and hence before the value computation
12755     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12756     // as if they were unconditionally sequenced.
12757     EvaluationTracker Eval(*this);
12758     {
12759       SequencedSubexpression Sequenced(*this);
12760       Visit(BO->getLHS());
12761     }
12762 
12763     bool Result;
12764     if (Eval.evaluate(BO->getLHS(), Result)) {
12765       if (!Result)
12766         Visit(BO->getRHS());
12767     } else {
12768       // Check for unsequenced operations in the RHS, treating it as an
12769       // entirely separate evaluation.
12770       //
12771       // FIXME: If there are operations in the RHS which are unsequenced
12772       // with respect to operations outside the RHS, and those operations
12773       // are unconditionally evaluated, diagnose them.
12774       WorkList.push_back(BO->getRHS());
12775     }
12776   }
12777   void VisitBinLAnd(BinaryOperator *BO) {
12778     EvaluationTracker Eval(*this);
12779     {
12780       SequencedSubexpression Sequenced(*this);
12781       Visit(BO->getLHS());
12782     }
12783 
12784     bool Result;
12785     if (Eval.evaluate(BO->getLHS(), Result)) {
12786       if (Result)
12787         Visit(BO->getRHS());
12788     } else {
12789       WorkList.push_back(BO->getRHS());
12790     }
12791   }
12792 
12793   // Only visit the condition, unless we can be sure which subexpression will
12794   // be chosen.
12795   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12796     EvaluationTracker Eval(*this);
12797     {
12798       SequencedSubexpression Sequenced(*this);
12799       Visit(CO->getCond());
12800     }
12801 
12802     bool Result;
12803     if (Eval.evaluate(CO->getCond(), Result))
12804       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12805     else {
12806       WorkList.push_back(CO->getTrueExpr());
12807       WorkList.push_back(CO->getFalseExpr());
12808     }
12809   }
12810 
12811   void VisitCallExpr(CallExpr *CE) {
12812     // C++11 [intro.execution]p15:
12813     //   When calling a function [...], every value computation and side effect
12814     //   associated with any argument expression, or with the postfix expression
12815     //   designating the called function, is sequenced before execution of every
12816     //   expression or statement in the body of the function [and thus before
12817     //   the value computation of its result].
12818     SequencedSubexpression Sequenced(*this);
12819     Base::VisitCallExpr(CE);
12820 
12821     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12822   }
12823 
12824   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12825     // This is a call, so all subexpressions are sequenced before the result.
12826     SequencedSubexpression Sequenced(*this);
12827 
12828     if (!CCE->isListInitialization())
12829       return VisitExpr(CCE);
12830 
12831     // In C++11, list initializations are sequenced.
12832     SmallVector<SequenceTree::Seq, 32> Elts;
12833     SequenceTree::Seq Parent = Region;
12834     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12835                                         E = CCE->arg_end();
12836          I != E; ++I) {
12837       Region = Tree.allocate(Parent);
12838       Elts.push_back(Region);
12839       Visit(*I);
12840     }
12841 
12842     // Forget that the initializers are sequenced.
12843     Region = Parent;
12844     for (unsigned I = 0; I < Elts.size(); ++I)
12845       Tree.merge(Elts[I]);
12846   }
12847 
12848   void VisitInitListExpr(InitListExpr *ILE) {
12849     if (!SemaRef.getLangOpts().CPlusPlus11)
12850       return VisitExpr(ILE);
12851 
12852     // In C++11, list initializations are sequenced.
12853     SmallVector<SequenceTree::Seq, 32> Elts;
12854     SequenceTree::Seq Parent = Region;
12855     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12856       Expr *E = ILE->getInit(I);
12857       if (!E) continue;
12858       Region = Tree.allocate(Parent);
12859       Elts.push_back(Region);
12860       Visit(E);
12861     }
12862 
12863     // Forget that the initializers are sequenced.
12864     Region = Parent;
12865     for (unsigned I = 0; I < Elts.size(); ++I)
12866       Tree.merge(Elts[I]);
12867   }
12868 };
12869 
12870 } // namespace
12871 
12872 void Sema::CheckUnsequencedOperations(Expr *E) {
12873   SmallVector<Expr *, 8> WorkList;
12874   WorkList.push_back(E);
12875   while (!WorkList.empty()) {
12876     Expr *Item = WorkList.pop_back_val();
12877     SequenceChecker(*this, Item, WorkList);
12878   }
12879 }
12880 
12881 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12882                               bool IsConstexpr) {
12883   llvm::SaveAndRestore<bool> ConstantContext(
12884       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12885   CheckImplicitConversions(E, CheckLoc);
12886   if (!E->isInstantiationDependent())
12887     CheckUnsequencedOperations(E);
12888   if (!IsConstexpr && !E->isValueDependent())
12889     CheckForIntOverflow(E);
12890   DiagnoseMisalignedMembers();
12891 }
12892 
12893 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12894                                        FieldDecl *BitField,
12895                                        Expr *Init) {
12896   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12897 }
12898 
12899 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12900                                          SourceLocation Loc) {
12901   if (!PType->isVariablyModifiedType())
12902     return;
12903   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12904     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12905     return;
12906   }
12907   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12908     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12909     return;
12910   }
12911   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12912     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12913     return;
12914   }
12915 
12916   const ArrayType *AT = S.Context.getAsArrayType(PType);
12917   if (!AT)
12918     return;
12919 
12920   if (AT->getSizeModifier() != ArrayType::Star) {
12921     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12922     return;
12923   }
12924 
12925   S.Diag(Loc, diag::err_array_star_in_function_definition);
12926 }
12927 
12928 /// CheckParmsForFunctionDef - Check that the parameters of the given
12929 /// function are appropriate for the definition of a function. This
12930 /// takes care of any checks that cannot be performed on the
12931 /// declaration itself, e.g., that the types of each of the function
12932 /// parameters are complete.
12933 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12934                                     bool CheckParameterNames) {
12935   bool HasInvalidParm = false;
12936   for (ParmVarDecl *Param : Parameters) {
12937     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12938     // function declarator that is part of a function definition of
12939     // that function shall not have incomplete type.
12940     //
12941     // This is also C++ [dcl.fct]p6.
12942     if (!Param->isInvalidDecl() &&
12943         RequireCompleteType(Param->getLocation(), Param->getType(),
12944                             diag::err_typecheck_decl_incomplete_type)) {
12945       Param->setInvalidDecl();
12946       HasInvalidParm = true;
12947     }
12948 
12949     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12950     // declaration of each parameter shall include an identifier.
12951     if (CheckParameterNames &&
12952         Param->getIdentifier() == nullptr &&
12953         !Param->isImplicit() &&
12954         !getLangOpts().CPlusPlus)
12955       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12956 
12957     // C99 6.7.5.3p12:
12958     //   If the function declarator is not part of a definition of that
12959     //   function, parameters may have incomplete type and may use the [*]
12960     //   notation in their sequences of declarator specifiers to specify
12961     //   variable length array types.
12962     QualType PType = Param->getOriginalType();
12963     // FIXME: This diagnostic should point the '[*]' if source-location
12964     // information is added for it.
12965     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12966 
12967     // If the parameter is a c++ class type and it has to be destructed in the
12968     // callee function, declare the destructor so that it can be called by the
12969     // callee function. Do not perform any direct access check on the dtor here.
12970     if (!Param->isInvalidDecl()) {
12971       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12972         if (!ClassDecl->isInvalidDecl() &&
12973             !ClassDecl->hasIrrelevantDestructor() &&
12974             !ClassDecl->isDependentContext() &&
12975             ClassDecl->isParamDestroyedInCallee()) {
12976           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12977           MarkFunctionReferenced(Param->getLocation(), Destructor);
12978           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12979         }
12980       }
12981     }
12982 
12983     // Parameters with the pass_object_size attribute only need to be marked
12984     // constant at function definitions. Because we lack information about
12985     // whether we're on a declaration or definition when we're instantiating the
12986     // attribute, we need to check for constness here.
12987     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12988       if (!Param->getType().isConstQualified())
12989         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12990             << Attr->getSpelling() << 1;
12991 
12992     // Check for parameter names shadowing fields from the class.
12993     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12994       // The owning context for the parameter should be the function, but we
12995       // want to see if this function's declaration context is a record.
12996       DeclContext *DC = Param->getDeclContext();
12997       if (DC && DC->isFunctionOrMethod()) {
12998         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12999           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13000                                      RD, /*DeclIsField*/ false);
13001       }
13002     }
13003   }
13004 
13005   return HasInvalidParm;
13006 }
13007 
13008 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13009 /// or MemberExpr.
13010 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13011                               ASTContext &Context) {
13012   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13013     return Context.getDeclAlign(DRE->getDecl());
13014 
13015   if (const auto *ME = dyn_cast<MemberExpr>(E))
13016     return Context.getDeclAlign(ME->getMemberDecl());
13017 
13018   return TypeAlign;
13019 }
13020 
13021 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13022 /// pointer cast increases the alignment requirements.
13023 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13024   // This is actually a lot of work to potentially be doing on every
13025   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13026   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13027     return;
13028 
13029   // Ignore dependent types.
13030   if (T->isDependentType() || Op->getType()->isDependentType())
13031     return;
13032 
13033   // Require that the destination be a pointer type.
13034   const PointerType *DestPtr = T->getAs<PointerType>();
13035   if (!DestPtr) return;
13036 
13037   // If the destination has alignment 1, we're done.
13038   QualType DestPointee = DestPtr->getPointeeType();
13039   if (DestPointee->isIncompleteType()) return;
13040   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13041   if (DestAlign.isOne()) return;
13042 
13043   // Require that the source be a pointer type.
13044   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13045   if (!SrcPtr) return;
13046   QualType SrcPointee = SrcPtr->getPointeeType();
13047 
13048   // Whitelist casts from cv void*.  We already implicitly
13049   // whitelisted casts to cv void*, since they have alignment 1.
13050   // Also whitelist casts involving incomplete types, which implicitly
13051   // includes 'void'.
13052   if (SrcPointee->isIncompleteType()) return;
13053 
13054   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13055 
13056   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13057     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13058       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13059   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13060     if (UO->getOpcode() == UO_AddrOf)
13061       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13062   }
13063 
13064   if (SrcAlign >= DestAlign) return;
13065 
13066   Diag(TRange.getBegin(), diag::warn_cast_align)
13067     << Op->getType() << T
13068     << static_cast<unsigned>(SrcAlign.getQuantity())
13069     << static_cast<unsigned>(DestAlign.getQuantity())
13070     << TRange << Op->getSourceRange();
13071 }
13072 
13073 /// Check whether this array fits the idiom of a size-one tail padded
13074 /// array member of a struct.
13075 ///
13076 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13077 /// commonly used to emulate flexible arrays in C89 code.
13078 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13079                                     const NamedDecl *ND) {
13080   if (Size != 1 || !ND) return false;
13081 
13082   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13083   if (!FD) return false;
13084 
13085   // Don't consider sizes resulting from macro expansions or template argument
13086   // substitution to form C89 tail-padded arrays.
13087 
13088   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13089   while (TInfo) {
13090     TypeLoc TL = TInfo->getTypeLoc();
13091     // Look through typedefs.
13092     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13093       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13094       TInfo = TDL->getTypeSourceInfo();
13095       continue;
13096     }
13097     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13098       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13099       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13100         return false;
13101     }
13102     break;
13103   }
13104 
13105   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13106   if (!RD) return false;
13107   if (RD->isUnion()) return false;
13108   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13109     if (!CRD->isStandardLayout()) return false;
13110   }
13111 
13112   // See if this is the last field decl in the record.
13113   const Decl *D = FD;
13114   while ((D = D->getNextDeclInContext()))
13115     if (isa<FieldDecl>(D))
13116       return false;
13117   return true;
13118 }
13119 
13120 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13121                             const ArraySubscriptExpr *ASE,
13122                             bool AllowOnePastEnd, bool IndexNegated) {
13123   // Already diagnosed by the constant evaluator.
13124   if (isConstantEvaluated())
13125     return;
13126 
13127   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13128   if (IndexExpr->isValueDependent())
13129     return;
13130 
13131   const Type *EffectiveType =
13132       BaseExpr->getType()->getPointeeOrArrayElementType();
13133   BaseExpr = BaseExpr->IgnoreParenCasts();
13134   const ConstantArrayType *ArrayTy =
13135       Context.getAsConstantArrayType(BaseExpr->getType());
13136 
13137   if (!ArrayTy)
13138     return;
13139 
13140   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13141   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13142     return;
13143 
13144   Expr::EvalResult Result;
13145   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13146     return;
13147 
13148   llvm::APSInt index = Result.Val.getInt();
13149   if (IndexNegated)
13150     index = -index;
13151 
13152   const NamedDecl *ND = nullptr;
13153   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13154     ND = DRE->getDecl();
13155   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13156     ND = ME->getMemberDecl();
13157 
13158   if (index.isUnsigned() || !index.isNegative()) {
13159     // It is possible that the type of the base expression after
13160     // IgnoreParenCasts is incomplete, even though the type of the base
13161     // expression before IgnoreParenCasts is complete (see PR39746 for an
13162     // example). In this case we have no information about whether the array
13163     // access exceeds the array bounds. However we can still diagnose an array
13164     // access which precedes the array bounds.
13165     if (BaseType->isIncompleteType())
13166       return;
13167 
13168     llvm::APInt size = ArrayTy->getSize();
13169     if (!size.isStrictlyPositive())
13170       return;
13171 
13172     if (BaseType != EffectiveType) {
13173       // Make sure we're comparing apples to apples when comparing index to size
13174       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13175       uint64_t array_typesize = Context.getTypeSize(BaseType);
13176       // Handle ptrarith_typesize being zero, such as when casting to void*
13177       if (!ptrarith_typesize) ptrarith_typesize = 1;
13178       if (ptrarith_typesize != array_typesize) {
13179         // There's a cast to a different size type involved
13180         uint64_t ratio = array_typesize / ptrarith_typesize;
13181         // TODO: Be smarter about handling cases where array_typesize is not a
13182         // multiple of ptrarith_typesize
13183         if (ptrarith_typesize * ratio == array_typesize)
13184           size *= llvm::APInt(size.getBitWidth(), ratio);
13185       }
13186     }
13187 
13188     if (size.getBitWidth() > index.getBitWidth())
13189       index = index.zext(size.getBitWidth());
13190     else if (size.getBitWidth() < index.getBitWidth())
13191       size = size.zext(index.getBitWidth());
13192 
13193     // For array subscripting the index must be less than size, but for pointer
13194     // arithmetic also allow the index (offset) to be equal to size since
13195     // computing the next address after the end of the array is legal and
13196     // commonly done e.g. in C++ iterators and range-based for loops.
13197     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13198       return;
13199 
13200     // Also don't warn for arrays of size 1 which are members of some
13201     // structure. These are often used to approximate flexible arrays in C89
13202     // code.
13203     if (IsTailPaddedMemberArray(*this, size, ND))
13204       return;
13205 
13206     // Suppress the warning if the subscript expression (as identified by the
13207     // ']' location) and the index expression are both from macro expansions
13208     // within a system header.
13209     if (ASE) {
13210       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13211           ASE->getRBracketLoc());
13212       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13213         SourceLocation IndexLoc =
13214             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13215         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13216           return;
13217       }
13218     }
13219 
13220     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13221     if (ASE)
13222       DiagID = diag::warn_array_index_exceeds_bounds;
13223 
13224     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13225                         PDiag(DiagID) << index.toString(10, true)
13226                                       << size.toString(10, true)
13227                                       << (unsigned)size.getLimitedValue(~0U)
13228                                       << IndexExpr->getSourceRange());
13229   } else {
13230     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13231     if (!ASE) {
13232       DiagID = diag::warn_ptr_arith_precedes_bounds;
13233       if (index.isNegative()) index = -index;
13234     }
13235 
13236     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13237                         PDiag(DiagID) << index.toString(10, true)
13238                                       << IndexExpr->getSourceRange());
13239   }
13240 
13241   if (!ND) {
13242     // Try harder to find a NamedDecl to point at in the note.
13243     while (const ArraySubscriptExpr *ASE =
13244            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13245       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13246     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13247       ND = DRE->getDecl();
13248     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13249       ND = ME->getMemberDecl();
13250   }
13251 
13252   if (ND)
13253     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13254                         PDiag(diag::note_array_declared_here)
13255                             << ND->getDeclName());
13256 }
13257 
13258 void Sema::CheckArrayAccess(const Expr *expr) {
13259   int AllowOnePastEnd = 0;
13260   while (expr) {
13261     expr = expr->IgnoreParenImpCasts();
13262     switch (expr->getStmtClass()) {
13263       case Stmt::ArraySubscriptExprClass: {
13264         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13265         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13266                          AllowOnePastEnd > 0);
13267         expr = ASE->getBase();
13268         break;
13269       }
13270       case Stmt::MemberExprClass: {
13271         expr = cast<MemberExpr>(expr)->getBase();
13272         break;
13273       }
13274       case Stmt::OMPArraySectionExprClass: {
13275         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13276         if (ASE->getLowerBound())
13277           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13278                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13279         return;
13280       }
13281       case Stmt::UnaryOperatorClass: {
13282         // Only unwrap the * and & unary operators
13283         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13284         expr = UO->getSubExpr();
13285         switch (UO->getOpcode()) {
13286           case UO_AddrOf:
13287             AllowOnePastEnd++;
13288             break;
13289           case UO_Deref:
13290             AllowOnePastEnd--;
13291             break;
13292           default:
13293             return;
13294         }
13295         break;
13296       }
13297       case Stmt::ConditionalOperatorClass: {
13298         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13299         if (const Expr *lhs = cond->getLHS())
13300           CheckArrayAccess(lhs);
13301         if (const Expr *rhs = cond->getRHS())
13302           CheckArrayAccess(rhs);
13303         return;
13304       }
13305       case Stmt::CXXOperatorCallExprClass: {
13306         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13307         for (const auto *Arg : OCE->arguments())
13308           CheckArrayAccess(Arg);
13309         return;
13310       }
13311       default:
13312         return;
13313     }
13314   }
13315 }
13316 
13317 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13318 
13319 namespace {
13320 
13321 struct RetainCycleOwner {
13322   VarDecl *Variable = nullptr;
13323   SourceRange Range;
13324   SourceLocation Loc;
13325   bool Indirect = false;
13326 
13327   RetainCycleOwner() = default;
13328 
13329   void setLocsFrom(Expr *e) {
13330     Loc = e->getExprLoc();
13331     Range = e->getSourceRange();
13332   }
13333 };
13334 
13335 } // namespace
13336 
13337 /// Consider whether capturing the given variable can possibly lead to
13338 /// a retain cycle.
13339 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13340   // In ARC, it's captured strongly iff the variable has __strong
13341   // lifetime.  In MRR, it's captured strongly if the variable is
13342   // __block and has an appropriate type.
13343   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13344     return false;
13345 
13346   owner.Variable = var;
13347   if (ref)
13348     owner.setLocsFrom(ref);
13349   return true;
13350 }
13351 
13352 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13353   while (true) {
13354     e = e->IgnoreParens();
13355     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13356       switch (cast->getCastKind()) {
13357       case CK_BitCast:
13358       case CK_LValueBitCast:
13359       case CK_LValueToRValue:
13360       case CK_ARCReclaimReturnedObject:
13361         e = cast->getSubExpr();
13362         continue;
13363 
13364       default:
13365         return false;
13366       }
13367     }
13368 
13369     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13370       ObjCIvarDecl *ivar = ref->getDecl();
13371       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13372         return false;
13373 
13374       // Try to find a retain cycle in the base.
13375       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13376         return false;
13377 
13378       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13379       owner.Indirect = true;
13380       return true;
13381     }
13382 
13383     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13384       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13385       if (!var) return false;
13386       return considerVariable(var, ref, owner);
13387     }
13388 
13389     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13390       if (member->isArrow()) return false;
13391 
13392       // Don't count this as an indirect ownership.
13393       e = member->getBase();
13394       continue;
13395     }
13396 
13397     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13398       // Only pay attention to pseudo-objects on property references.
13399       ObjCPropertyRefExpr *pre
13400         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13401                                               ->IgnoreParens());
13402       if (!pre) return false;
13403       if (pre->isImplicitProperty()) return false;
13404       ObjCPropertyDecl *property = pre->getExplicitProperty();
13405       if (!property->isRetaining() &&
13406           !(property->getPropertyIvarDecl() &&
13407             property->getPropertyIvarDecl()->getType()
13408               .getObjCLifetime() == Qualifiers::OCL_Strong))
13409           return false;
13410 
13411       owner.Indirect = true;
13412       if (pre->isSuperReceiver()) {
13413         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13414         if (!owner.Variable)
13415           return false;
13416         owner.Loc = pre->getLocation();
13417         owner.Range = pre->getSourceRange();
13418         return true;
13419       }
13420       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13421                               ->getSourceExpr());
13422       continue;
13423     }
13424 
13425     // Array ivars?
13426 
13427     return false;
13428   }
13429 }
13430 
13431 namespace {
13432 
13433   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13434     ASTContext &Context;
13435     VarDecl *Variable;
13436     Expr *Capturer = nullptr;
13437     bool VarWillBeReased = false;
13438 
13439     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13440         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13441           Context(Context), Variable(variable) {}
13442 
13443     void VisitDeclRefExpr(DeclRefExpr *ref) {
13444       if (ref->getDecl() == Variable && !Capturer)
13445         Capturer = ref;
13446     }
13447 
13448     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13449       if (Capturer) return;
13450       Visit(ref->getBase());
13451       if (Capturer && ref->isFreeIvar())
13452         Capturer = ref;
13453     }
13454 
13455     void VisitBlockExpr(BlockExpr *block) {
13456       // Look inside nested blocks
13457       if (block->getBlockDecl()->capturesVariable(Variable))
13458         Visit(block->getBlockDecl()->getBody());
13459     }
13460 
13461     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13462       if (Capturer) return;
13463       if (OVE->getSourceExpr())
13464         Visit(OVE->getSourceExpr());
13465     }
13466 
13467     void VisitBinaryOperator(BinaryOperator *BinOp) {
13468       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13469         return;
13470       Expr *LHS = BinOp->getLHS();
13471       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13472         if (DRE->getDecl() != Variable)
13473           return;
13474         if (Expr *RHS = BinOp->getRHS()) {
13475           RHS = RHS->IgnoreParenCasts();
13476           llvm::APSInt Value;
13477           VarWillBeReased =
13478             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13479         }
13480       }
13481     }
13482   };
13483 
13484 } // namespace
13485 
13486 /// Check whether the given argument is a block which captures a
13487 /// variable.
13488 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13489   assert(owner.Variable && owner.Loc.isValid());
13490 
13491   e = e->IgnoreParenCasts();
13492 
13493   // Look through [^{...} copy] and Block_copy(^{...}).
13494   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13495     Selector Cmd = ME->getSelector();
13496     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13497       e = ME->getInstanceReceiver();
13498       if (!e)
13499         return nullptr;
13500       e = e->IgnoreParenCasts();
13501     }
13502   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13503     if (CE->getNumArgs() == 1) {
13504       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13505       if (Fn) {
13506         const IdentifierInfo *FnI = Fn->getIdentifier();
13507         if (FnI && FnI->isStr("_Block_copy")) {
13508           e = CE->getArg(0)->IgnoreParenCasts();
13509         }
13510       }
13511     }
13512   }
13513 
13514   BlockExpr *block = dyn_cast<BlockExpr>(e);
13515   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13516     return nullptr;
13517 
13518   FindCaptureVisitor visitor(S.Context, owner.Variable);
13519   visitor.Visit(block->getBlockDecl()->getBody());
13520   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13521 }
13522 
13523 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13524                                 RetainCycleOwner &owner) {
13525   assert(capturer);
13526   assert(owner.Variable && owner.Loc.isValid());
13527 
13528   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13529     << owner.Variable << capturer->getSourceRange();
13530   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13531     << owner.Indirect << owner.Range;
13532 }
13533 
13534 /// Check for a keyword selector that starts with the word 'add' or
13535 /// 'set'.
13536 static bool isSetterLikeSelector(Selector sel) {
13537   if (sel.isUnarySelector()) return false;
13538 
13539   StringRef str = sel.getNameForSlot(0);
13540   while (!str.empty() && str.front() == '_') str = str.substr(1);
13541   if (str.startswith("set"))
13542     str = str.substr(3);
13543   else if (str.startswith("add")) {
13544     // Specially whitelist 'addOperationWithBlock:'.
13545     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13546       return false;
13547     str = str.substr(3);
13548   }
13549   else
13550     return false;
13551 
13552   if (str.empty()) return true;
13553   return !isLowercase(str.front());
13554 }
13555 
13556 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13557                                                     ObjCMessageExpr *Message) {
13558   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13559                                                 Message->getReceiverInterface(),
13560                                                 NSAPI::ClassId_NSMutableArray);
13561   if (!IsMutableArray) {
13562     return None;
13563   }
13564 
13565   Selector Sel = Message->getSelector();
13566 
13567   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13568     S.NSAPIObj->getNSArrayMethodKind(Sel);
13569   if (!MKOpt) {
13570     return None;
13571   }
13572 
13573   NSAPI::NSArrayMethodKind MK = *MKOpt;
13574 
13575   switch (MK) {
13576     case NSAPI::NSMutableArr_addObject:
13577     case NSAPI::NSMutableArr_insertObjectAtIndex:
13578     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13579       return 0;
13580     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13581       return 1;
13582 
13583     default:
13584       return None;
13585   }
13586 
13587   return None;
13588 }
13589 
13590 static
13591 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13592                                                   ObjCMessageExpr *Message) {
13593   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13594                                             Message->getReceiverInterface(),
13595                                             NSAPI::ClassId_NSMutableDictionary);
13596   if (!IsMutableDictionary) {
13597     return None;
13598   }
13599 
13600   Selector Sel = Message->getSelector();
13601 
13602   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13603     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13604   if (!MKOpt) {
13605     return None;
13606   }
13607 
13608   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13609 
13610   switch (MK) {
13611     case NSAPI::NSMutableDict_setObjectForKey:
13612     case NSAPI::NSMutableDict_setValueForKey:
13613     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13614       return 0;
13615 
13616     default:
13617       return None;
13618   }
13619 
13620   return None;
13621 }
13622 
13623 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13624   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13625                                                 Message->getReceiverInterface(),
13626                                                 NSAPI::ClassId_NSMutableSet);
13627 
13628   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13629                                             Message->getReceiverInterface(),
13630                                             NSAPI::ClassId_NSMutableOrderedSet);
13631   if (!IsMutableSet && !IsMutableOrderedSet) {
13632     return None;
13633   }
13634 
13635   Selector Sel = Message->getSelector();
13636 
13637   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13638   if (!MKOpt) {
13639     return None;
13640   }
13641 
13642   NSAPI::NSSetMethodKind MK = *MKOpt;
13643 
13644   switch (MK) {
13645     case NSAPI::NSMutableSet_addObject:
13646     case NSAPI::NSOrderedSet_setObjectAtIndex:
13647     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13648     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13649       return 0;
13650     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13651       return 1;
13652   }
13653 
13654   return None;
13655 }
13656 
13657 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13658   if (!Message->isInstanceMessage()) {
13659     return;
13660   }
13661 
13662   Optional<int> ArgOpt;
13663 
13664   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13665       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13666       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13667     return;
13668   }
13669 
13670   int ArgIndex = *ArgOpt;
13671 
13672   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13673   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13674     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13675   }
13676 
13677   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13678     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13679       if (ArgRE->isObjCSelfExpr()) {
13680         Diag(Message->getSourceRange().getBegin(),
13681              diag::warn_objc_circular_container)
13682           << ArgRE->getDecl() << StringRef("'super'");
13683       }
13684     }
13685   } else {
13686     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13687 
13688     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13689       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13690     }
13691 
13692     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13693       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13694         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13695           ValueDecl *Decl = ReceiverRE->getDecl();
13696           Diag(Message->getSourceRange().getBegin(),
13697                diag::warn_objc_circular_container)
13698             << Decl << Decl;
13699           if (!ArgRE->isObjCSelfExpr()) {
13700             Diag(Decl->getLocation(),
13701                  diag::note_objc_circular_container_declared_here)
13702               << Decl;
13703           }
13704         }
13705       }
13706     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13707       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13708         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13709           ObjCIvarDecl *Decl = IvarRE->getDecl();
13710           Diag(Message->getSourceRange().getBegin(),
13711                diag::warn_objc_circular_container)
13712             << Decl << Decl;
13713           Diag(Decl->getLocation(),
13714                diag::note_objc_circular_container_declared_here)
13715             << Decl;
13716         }
13717       }
13718     }
13719   }
13720 }
13721 
13722 /// Check a message send to see if it's likely to cause a retain cycle.
13723 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13724   // Only check instance methods whose selector looks like a setter.
13725   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13726     return;
13727 
13728   // Try to find a variable that the receiver is strongly owned by.
13729   RetainCycleOwner owner;
13730   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13731     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13732       return;
13733   } else {
13734     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13735     owner.Variable = getCurMethodDecl()->getSelfDecl();
13736     owner.Loc = msg->getSuperLoc();
13737     owner.Range = msg->getSuperLoc();
13738   }
13739 
13740   // Check whether the receiver is captured by any of the arguments.
13741   const ObjCMethodDecl *MD = msg->getMethodDecl();
13742   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13743     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13744       // noescape blocks should not be retained by the method.
13745       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13746         continue;
13747       return diagnoseRetainCycle(*this, capturer, owner);
13748     }
13749   }
13750 }
13751 
13752 /// Check a property assign to see if it's likely to cause a retain cycle.
13753 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13754   RetainCycleOwner owner;
13755   if (!findRetainCycleOwner(*this, receiver, owner))
13756     return;
13757 
13758   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13759     diagnoseRetainCycle(*this, capturer, owner);
13760 }
13761 
13762 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13763   RetainCycleOwner Owner;
13764   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13765     return;
13766 
13767   // Because we don't have an expression for the variable, we have to set the
13768   // location explicitly here.
13769   Owner.Loc = Var->getLocation();
13770   Owner.Range = Var->getSourceRange();
13771 
13772   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13773     diagnoseRetainCycle(*this, Capturer, Owner);
13774 }
13775 
13776 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13777                                      Expr *RHS, bool isProperty) {
13778   // Check if RHS is an Objective-C object literal, which also can get
13779   // immediately zapped in a weak reference.  Note that we explicitly
13780   // allow ObjCStringLiterals, since those are designed to never really die.
13781   RHS = RHS->IgnoreParenImpCasts();
13782 
13783   // This enum needs to match with the 'select' in
13784   // warn_objc_arc_literal_assign (off-by-1).
13785   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13786   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13787     return false;
13788 
13789   S.Diag(Loc, diag::warn_arc_literal_assign)
13790     << (unsigned) Kind
13791     << (isProperty ? 0 : 1)
13792     << RHS->getSourceRange();
13793 
13794   return true;
13795 }
13796 
13797 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13798                                     Qualifiers::ObjCLifetime LT,
13799                                     Expr *RHS, bool isProperty) {
13800   // Strip off any implicit cast added to get to the one ARC-specific.
13801   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13802     if (cast->getCastKind() == CK_ARCConsumeObject) {
13803       S.Diag(Loc, diag::warn_arc_retained_assign)
13804         << (LT == Qualifiers::OCL_ExplicitNone)
13805         << (isProperty ? 0 : 1)
13806         << RHS->getSourceRange();
13807       return true;
13808     }
13809     RHS = cast->getSubExpr();
13810   }
13811 
13812   if (LT == Qualifiers::OCL_Weak &&
13813       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13814     return true;
13815 
13816   return false;
13817 }
13818 
13819 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13820                               QualType LHS, Expr *RHS) {
13821   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13822 
13823   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13824     return false;
13825 
13826   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13827     return true;
13828 
13829   return false;
13830 }
13831 
13832 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13833                               Expr *LHS, Expr *RHS) {
13834   QualType LHSType;
13835   // PropertyRef on LHS type need be directly obtained from
13836   // its declaration as it has a PseudoType.
13837   ObjCPropertyRefExpr *PRE
13838     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13839   if (PRE && !PRE->isImplicitProperty()) {
13840     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13841     if (PD)
13842       LHSType = PD->getType();
13843   }
13844 
13845   if (LHSType.isNull())
13846     LHSType = LHS->getType();
13847 
13848   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13849 
13850   if (LT == Qualifiers::OCL_Weak) {
13851     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13852       getCurFunction()->markSafeWeakUse(LHS);
13853   }
13854 
13855   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13856     return;
13857 
13858   // FIXME. Check for other life times.
13859   if (LT != Qualifiers::OCL_None)
13860     return;
13861 
13862   if (PRE) {
13863     if (PRE->isImplicitProperty())
13864       return;
13865     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13866     if (!PD)
13867       return;
13868 
13869     unsigned Attributes = PD->getPropertyAttributes();
13870     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13871       // when 'assign' attribute was not explicitly specified
13872       // by user, ignore it and rely on property type itself
13873       // for lifetime info.
13874       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13875       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13876           LHSType->isObjCRetainableType())
13877         return;
13878 
13879       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13880         if (cast->getCastKind() == CK_ARCConsumeObject) {
13881           Diag(Loc, diag::warn_arc_retained_property_assign)
13882           << RHS->getSourceRange();
13883           return;
13884         }
13885         RHS = cast->getSubExpr();
13886       }
13887     }
13888     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13889       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13890         return;
13891     }
13892   }
13893 }
13894 
13895 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13896 
13897 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13898                                         SourceLocation StmtLoc,
13899                                         const NullStmt *Body) {
13900   // Do not warn if the body is a macro that expands to nothing, e.g:
13901   //
13902   // #define CALL(x)
13903   // if (condition)
13904   //   CALL(0);
13905   if (Body->hasLeadingEmptyMacro())
13906     return false;
13907 
13908   // Get line numbers of statement and body.
13909   bool StmtLineInvalid;
13910   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13911                                                       &StmtLineInvalid);
13912   if (StmtLineInvalid)
13913     return false;
13914 
13915   bool BodyLineInvalid;
13916   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13917                                                       &BodyLineInvalid);
13918   if (BodyLineInvalid)
13919     return false;
13920 
13921   // Warn if null statement and body are on the same line.
13922   if (StmtLine != BodyLine)
13923     return false;
13924 
13925   return true;
13926 }
13927 
13928 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13929                                  const Stmt *Body,
13930                                  unsigned DiagID) {
13931   // Since this is a syntactic check, don't emit diagnostic for template
13932   // instantiations, this just adds noise.
13933   if (CurrentInstantiationScope)
13934     return;
13935 
13936   // The body should be a null statement.
13937   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13938   if (!NBody)
13939     return;
13940 
13941   // Do the usual checks.
13942   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13943     return;
13944 
13945   Diag(NBody->getSemiLoc(), DiagID);
13946   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13947 }
13948 
13949 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13950                                  const Stmt *PossibleBody) {
13951   assert(!CurrentInstantiationScope); // Ensured by caller
13952 
13953   SourceLocation StmtLoc;
13954   const Stmt *Body;
13955   unsigned DiagID;
13956   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13957     StmtLoc = FS->getRParenLoc();
13958     Body = FS->getBody();
13959     DiagID = diag::warn_empty_for_body;
13960   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13961     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13962     Body = WS->getBody();
13963     DiagID = diag::warn_empty_while_body;
13964   } else
13965     return; // Neither `for' nor `while'.
13966 
13967   // The body should be a null statement.
13968   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13969   if (!NBody)
13970     return;
13971 
13972   // Skip expensive checks if diagnostic is disabled.
13973   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13974     return;
13975 
13976   // Do the usual checks.
13977   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13978     return;
13979 
13980   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13981   // noise level low, emit diagnostics only if for/while is followed by a
13982   // CompoundStmt, e.g.:
13983   //    for (int i = 0; i < n; i++);
13984   //    {
13985   //      a(i);
13986   //    }
13987   // or if for/while is followed by a statement with more indentation
13988   // than for/while itself:
13989   //    for (int i = 0; i < n; i++);
13990   //      a(i);
13991   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13992   if (!ProbableTypo) {
13993     bool BodyColInvalid;
13994     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13995         PossibleBody->getBeginLoc(), &BodyColInvalid);
13996     if (BodyColInvalid)
13997       return;
13998 
13999     bool StmtColInvalid;
14000     unsigned StmtCol =
14001         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14002     if (StmtColInvalid)
14003       return;
14004 
14005     if (BodyCol > StmtCol)
14006       ProbableTypo = true;
14007   }
14008 
14009   if (ProbableTypo) {
14010     Diag(NBody->getSemiLoc(), DiagID);
14011     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14012   }
14013 }
14014 
14015 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14016 
14017 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14018 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14019                              SourceLocation OpLoc) {
14020   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14021     return;
14022 
14023   if (inTemplateInstantiation())
14024     return;
14025 
14026   // Strip parens and casts away.
14027   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14028   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14029 
14030   // Check for a call expression
14031   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14032   if (!CE || CE->getNumArgs() != 1)
14033     return;
14034 
14035   // Check for a call to std::move
14036   if (!CE->isCallToStdMove())
14037     return;
14038 
14039   // Get argument from std::move
14040   RHSExpr = CE->getArg(0);
14041 
14042   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14043   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14044 
14045   // Two DeclRefExpr's, check that the decls are the same.
14046   if (LHSDeclRef && RHSDeclRef) {
14047     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14048       return;
14049     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14050         RHSDeclRef->getDecl()->getCanonicalDecl())
14051       return;
14052 
14053     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14054                                         << LHSExpr->getSourceRange()
14055                                         << RHSExpr->getSourceRange();
14056     return;
14057   }
14058 
14059   // Member variables require a different approach to check for self moves.
14060   // MemberExpr's are the same if every nested MemberExpr refers to the same
14061   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14062   // the base Expr's are CXXThisExpr's.
14063   const Expr *LHSBase = LHSExpr;
14064   const Expr *RHSBase = RHSExpr;
14065   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14066   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14067   if (!LHSME || !RHSME)
14068     return;
14069 
14070   while (LHSME && RHSME) {
14071     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14072         RHSME->getMemberDecl()->getCanonicalDecl())
14073       return;
14074 
14075     LHSBase = LHSME->getBase();
14076     RHSBase = RHSME->getBase();
14077     LHSME = dyn_cast<MemberExpr>(LHSBase);
14078     RHSME = dyn_cast<MemberExpr>(RHSBase);
14079   }
14080 
14081   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14082   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14083   if (LHSDeclRef && RHSDeclRef) {
14084     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14085       return;
14086     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14087         RHSDeclRef->getDecl()->getCanonicalDecl())
14088       return;
14089 
14090     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14091                                         << LHSExpr->getSourceRange()
14092                                         << RHSExpr->getSourceRange();
14093     return;
14094   }
14095 
14096   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14097     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14098                                         << LHSExpr->getSourceRange()
14099                                         << RHSExpr->getSourceRange();
14100 }
14101 
14102 //===--- Layout compatibility ----------------------------------------------//
14103 
14104 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14105 
14106 /// Check if two enumeration types are layout-compatible.
14107 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14108   // C++11 [dcl.enum] p8:
14109   // Two enumeration types are layout-compatible if they have the same
14110   // underlying type.
14111   return ED1->isComplete() && ED2->isComplete() &&
14112          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14113 }
14114 
14115 /// Check if two fields are layout-compatible.
14116 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14117                                FieldDecl *Field2) {
14118   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14119     return false;
14120 
14121   if (Field1->isBitField() != Field2->isBitField())
14122     return false;
14123 
14124   if (Field1->isBitField()) {
14125     // Make sure that the bit-fields are the same length.
14126     unsigned Bits1 = Field1->getBitWidthValue(C);
14127     unsigned Bits2 = Field2->getBitWidthValue(C);
14128 
14129     if (Bits1 != Bits2)
14130       return false;
14131   }
14132 
14133   return true;
14134 }
14135 
14136 /// Check if two standard-layout structs are layout-compatible.
14137 /// (C++11 [class.mem] p17)
14138 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14139                                      RecordDecl *RD2) {
14140   // If both records are C++ classes, check that base classes match.
14141   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14142     // If one of records is a CXXRecordDecl we are in C++ mode,
14143     // thus the other one is a CXXRecordDecl, too.
14144     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14145     // Check number of base classes.
14146     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14147       return false;
14148 
14149     // Check the base classes.
14150     for (CXXRecordDecl::base_class_const_iterator
14151                Base1 = D1CXX->bases_begin(),
14152            BaseEnd1 = D1CXX->bases_end(),
14153               Base2 = D2CXX->bases_begin();
14154          Base1 != BaseEnd1;
14155          ++Base1, ++Base2) {
14156       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14157         return false;
14158     }
14159   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14160     // If only RD2 is a C++ class, it should have zero base classes.
14161     if (D2CXX->getNumBases() > 0)
14162       return false;
14163   }
14164 
14165   // Check the fields.
14166   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14167                              Field2End = RD2->field_end(),
14168                              Field1 = RD1->field_begin(),
14169                              Field1End = RD1->field_end();
14170   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14171     if (!isLayoutCompatible(C, *Field1, *Field2))
14172       return false;
14173   }
14174   if (Field1 != Field1End || Field2 != Field2End)
14175     return false;
14176 
14177   return true;
14178 }
14179 
14180 /// Check if two standard-layout unions are layout-compatible.
14181 /// (C++11 [class.mem] p18)
14182 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14183                                     RecordDecl *RD2) {
14184   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14185   for (auto *Field2 : RD2->fields())
14186     UnmatchedFields.insert(Field2);
14187 
14188   for (auto *Field1 : RD1->fields()) {
14189     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14190         I = UnmatchedFields.begin(),
14191         E = UnmatchedFields.end();
14192 
14193     for ( ; I != E; ++I) {
14194       if (isLayoutCompatible(C, Field1, *I)) {
14195         bool Result = UnmatchedFields.erase(*I);
14196         (void) Result;
14197         assert(Result);
14198         break;
14199       }
14200     }
14201     if (I == E)
14202       return false;
14203   }
14204 
14205   return UnmatchedFields.empty();
14206 }
14207 
14208 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14209                                RecordDecl *RD2) {
14210   if (RD1->isUnion() != RD2->isUnion())
14211     return false;
14212 
14213   if (RD1->isUnion())
14214     return isLayoutCompatibleUnion(C, RD1, RD2);
14215   else
14216     return isLayoutCompatibleStruct(C, RD1, RD2);
14217 }
14218 
14219 /// Check if two types are layout-compatible in C++11 sense.
14220 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14221   if (T1.isNull() || T2.isNull())
14222     return false;
14223 
14224   // C++11 [basic.types] p11:
14225   // If two types T1 and T2 are the same type, then T1 and T2 are
14226   // layout-compatible types.
14227   if (C.hasSameType(T1, T2))
14228     return true;
14229 
14230   T1 = T1.getCanonicalType().getUnqualifiedType();
14231   T2 = T2.getCanonicalType().getUnqualifiedType();
14232 
14233   const Type::TypeClass TC1 = T1->getTypeClass();
14234   const Type::TypeClass TC2 = T2->getTypeClass();
14235 
14236   if (TC1 != TC2)
14237     return false;
14238 
14239   if (TC1 == Type::Enum) {
14240     return isLayoutCompatible(C,
14241                               cast<EnumType>(T1)->getDecl(),
14242                               cast<EnumType>(T2)->getDecl());
14243   } else if (TC1 == Type::Record) {
14244     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14245       return false;
14246 
14247     return isLayoutCompatible(C,
14248                               cast<RecordType>(T1)->getDecl(),
14249                               cast<RecordType>(T2)->getDecl());
14250   }
14251 
14252   return false;
14253 }
14254 
14255 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14256 
14257 /// Given a type tag expression find the type tag itself.
14258 ///
14259 /// \param TypeExpr Type tag expression, as it appears in user's code.
14260 ///
14261 /// \param VD Declaration of an identifier that appears in a type tag.
14262 ///
14263 /// \param MagicValue Type tag magic value.
14264 ///
14265 /// \param isConstantEvaluated wether the evalaution should be performed in
14266 
14267 /// constant context.
14268 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14269                             const ValueDecl **VD, uint64_t *MagicValue,
14270                             bool isConstantEvaluated) {
14271   while(true) {
14272     if (!TypeExpr)
14273       return false;
14274 
14275     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14276 
14277     switch (TypeExpr->getStmtClass()) {
14278     case Stmt::UnaryOperatorClass: {
14279       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14280       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14281         TypeExpr = UO->getSubExpr();
14282         continue;
14283       }
14284       return false;
14285     }
14286 
14287     case Stmt::DeclRefExprClass: {
14288       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14289       *VD = DRE->getDecl();
14290       return true;
14291     }
14292 
14293     case Stmt::IntegerLiteralClass: {
14294       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14295       llvm::APInt MagicValueAPInt = IL->getValue();
14296       if (MagicValueAPInt.getActiveBits() <= 64) {
14297         *MagicValue = MagicValueAPInt.getZExtValue();
14298         return true;
14299       } else
14300         return false;
14301     }
14302 
14303     case Stmt::BinaryConditionalOperatorClass:
14304     case Stmt::ConditionalOperatorClass: {
14305       const AbstractConditionalOperator *ACO =
14306           cast<AbstractConditionalOperator>(TypeExpr);
14307       bool Result;
14308       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14309                                                      isConstantEvaluated)) {
14310         if (Result)
14311           TypeExpr = ACO->getTrueExpr();
14312         else
14313           TypeExpr = ACO->getFalseExpr();
14314         continue;
14315       }
14316       return false;
14317     }
14318 
14319     case Stmt::BinaryOperatorClass: {
14320       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14321       if (BO->getOpcode() == BO_Comma) {
14322         TypeExpr = BO->getRHS();
14323         continue;
14324       }
14325       return false;
14326     }
14327 
14328     default:
14329       return false;
14330     }
14331   }
14332 }
14333 
14334 /// Retrieve the C type corresponding to type tag TypeExpr.
14335 ///
14336 /// \param TypeExpr Expression that specifies a type tag.
14337 ///
14338 /// \param MagicValues Registered magic values.
14339 ///
14340 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14341 ///        kind.
14342 ///
14343 /// \param TypeInfo Information about the corresponding C type.
14344 ///
14345 /// \param isConstantEvaluated wether the evalaution should be performed in
14346 /// constant context.
14347 ///
14348 /// \returns true if the corresponding C type was found.
14349 static bool GetMatchingCType(
14350     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14351     const ASTContext &Ctx,
14352     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14353         *MagicValues,
14354     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14355     bool isConstantEvaluated) {
14356   FoundWrongKind = false;
14357 
14358   // Variable declaration that has type_tag_for_datatype attribute.
14359   const ValueDecl *VD = nullptr;
14360 
14361   uint64_t MagicValue;
14362 
14363   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14364     return false;
14365 
14366   if (VD) {
14367     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14368       if (I->getArgumentKind() != ArgumentKind) {
14369         FoundWrongKind = true;
14370         return false;
14371       }
14372       TypeInfo.Type = I->getMatchingCType();
14373       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14374       TypeInfo.MustBeNull = I->getMustBeNull();
14375       return true;
14376     }
14377     return false;
14378   }
14379 
14380   if (!MagicValues)
14381     return false;
14382 
14383   llvm::DenseMap<Sema::TypeTagMagicValue,
14384                  Sema::TypeTagData>::const_iterator I =
14385       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14386   if (I == MagicValues->end())
14387     return false;
14388 
14389   TypeInfo = I->second;
14390   return true;
14391 }
14392 
14393 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14394                                       uint64_t MagicValue, QualType Type,
14395                                       bool LayoutCompatible,
14396                                       bool MustBeNull) {
14397   if (!TypeTagForDatatypeMagicValues)
14398     TypeTagForDatatypeMagicValues.reset(
14399         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14400 
14401   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14402   (*TypeTagForDatatypeMagicValues)[Magic] =
14403       TypeTagData(Type, LayoutCompatible, MustBeNull);
14404 }
14405 
14406 static bool IsSameCharType(QualType T1, QualType T2) {
14407   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14408   if (!BT1)
14409     return false;
14410 
14411   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14412   if (!BT2)
14413     return false;
14414 
14415   BuiltinType::Kind T1Kind = BT1->getKind();
14416   BuiltinType::Kind T2Kind = BT2->getKind();
14417 
14418   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14419          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14420          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14421          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14422 }
14423 
14424 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14425                                     const ArrayRef<const Expr *> ExprArgs,
14426                                     SourceLocation CallSiteLoc) {
14427   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14428   bool IsPointerAttr = Attr->getIsPointer();
14429 
14430   // Retrieve the argument representing the 'type_tag'.
14431   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14432   if (TypeTagIdxAST >= ExprArgs.size()) {
14433     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14434         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14435     return;
14436   }
14437   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14438   bool FoundWrongKind;
14439   TypeTagData TypeInfo;
14440   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14441                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14442                         TypeInfo, isConstantEvaluated())) {
14443     if (FoundWrongKind)
14444       Diag(TypeTagExpr->getExprLoc(),
14445            diag::warn_type_tag_for_datatype_wrong_kind)
14446         << TypeTagExpr->getSourceRange();
14447     return;
14448   }
14449 
14450   // Retrieve the argument representing the 'arg_idx'.
14451   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14452   if (ArgumentIdxAST >= ExprArgs.size()) {
14453     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14454         << 1 << Attr->getArgumentIdx().getSourceIndex();
14455     return;
14456   }
14457   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14458   if (IsPointerAttr) {
14459     // Skip implicit cast of pointer to `void *' (as a function argument).
14460     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14461       if (ICE->getType()->isVoidPointerType() &&
14462           ICE->getCastKind() == CK_BitCast)
14463         ArgumentExpr = ICE->getSubExpr();
14464   }
14465   QualType ArgumentType = ArgumentExpr->getType();
14466 
14467   // Passing a `void*' pointer shouldn't trigger a warning.
14468   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14469     return;
14470 
14471   if (TypeInfo.MustBeNull) {
14472     // Type tag with matching void type requires a null pointer.
14473     if (!ArgumentExpr->isNullPointerConstant(Context,
14474                                              Expr::NPC_ValueDependentIsNotNull)) {
14475       Diag(ArgumentExpr->getExprLoc(),
14476            diag::warn_type_safety_null_pointer_required)
14477           << ArgumentKind->getName()
14478           << ArgumentExpr->getSourceRange()
14479           << TypeTagExpr->getSourceRange();
14480     }
14481     return;
14482   }
14483 
14484   QualType RequiredType = TypeInfo.Type;
14485   if (IsPointerAttr)
14486     RequiredType = Context.getPointerType(RequiredType);
14487 
14488   bool mismatch = false;
14489   if (!TypeInfo.LayoutCompatible) {
14490     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14491 
14492     // C++11 [basic.fundamental] p1:
14493     // Plain char, signed char, and unsigned char are three distinct types.
14494     //
14495     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14496     // char' depending on the current char signedness mode.
14497     if (mismatch)
14498       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14499                                            RequiredType->getPointeeType())) ||
14500           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14501         mismatch = false;
14502   } else
14503     if (IsPointerAttr)
14504       mismatch = !isLayoutCompatible(Context,
14505                                      ArgumentType->getPointeeType(),
14506                                      RequiredType->getPointeeType());
14507     else
14508       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14509 
14510   if (mismatch)
14511     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14512         << ArgumentType << ArgumentKind
14513         << TypeInfo.LayoutCompatible << RequiredType
14514         << ArgumentExpr->getSourceRange()
14515         << TypeTagExpr->getSourceRange();
14516 }
14517 
14518 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14519                                          CharUnits Alignment) {
14520   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14521 }
14522 
14523 void Sema::DiagnoseMisalignedMembers() {
14524   for (MisalignedMember &m : MisalignedMembers) {
14525     const NamedDecl *ND = m.RD;
14526     if (ND->getName().empty()) {
14527       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14528         ND = TD;
14529     }
14530     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14531         << m.MD << ND << m.E->getSourceRange();
14532   }
14533   MisalignedMembers.clear();
14534 }
14535 
14536 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14537   E = E->IgnoreParens();
14538   if (!T->isPointerType() && !T->isIntegerType())
14539     return;
14540   if (isa<UnaryOperator>(E) &&
14541       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14542     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14543     if (isa<MemberExpr>(Op)) {
14544       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14545       if (MA != MisalignedMembers.end() &&
14546           (T->isIntegerType() ||
14547            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14548                                    Context.getTypeAlignInChars(
14549                                        T->getPointeeType()) <= MA->Alignment))))
14550         MisalignedMembers.erase(MA);
14551     }
14552   }
14553 }
14554 
14555 void Sema::RefersToMemberWithReducedAlignment(
14556     Expr *E,
14557     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14558         Action) {
14559   const auto *ME = dyn_cast<MemberExpr>(E);
14560   if (!ME)
14561     return;
14562 
14563   // No need to check expressions with an __unaligned-qualified type.
14564   if (E->getType().getQualifiers().hasUnaligned())
14565     return;
14566 
14567   // For a chain of MemberExpr like "a.b.c.d" this list
14568   // will keep FieldDecl's like [d, c, b].
14569   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14570   const MemberExpr *TopME = nullptr;
14571   bool AnyIsPacked = false;
14572   do {
14573     QualType BaseType = ME->getBase()->getType();
14574     if (ME->isArrow())
14575       BaseType = BaseType->getPointeeType();
14576     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14577     if (RD->isInvalidDecl())
14578       return;
14579 
14580     ValueDecl *MD = ME->getMemberDecl();
14581     auto *FD = dyn_cast<FieldDecl>(MD);
14582     // We do not care about non-data members.
14583     if (!FD || FD->isInvalidDecl())
14584       return;
14585 
14586     AnyIsPacked =
14587         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14588     ReverseMemberChain.push_back(FD);
14589 
14590     TopME = ME;
14591     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14592   } while (ME);
14593   assert(TopME && "We did not compute a topmost MemberExpr!");
14594 
14595   // Not the scope of this diagnostic.
14596   if (!AnyIsPacked)
14597     return;
14598 
14599   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14600   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14601   // TODO: The innermost base of the member expression may be too complicated.
14602   // For now, just disregard these cases. This is left for future
14603   // improvement.
14604   if (!DRE && !isa<CXXThisExpr>(TopBase))
14605       return;
14606 
14607   // Alignment expected by the whole expression.
14608   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14609 
14610   // No need to do anything else with this case.
14611   if (ExpectedAlignment.isOne())
14612     return;
14613 
14614   // Synthesize offset of the whole access.
14615   CharUnits Offset;
14616   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14617        I++) {
14618     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14619   }
14620 
14621   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14622   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14623       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14624 
14625   // The base expression of the innermost MemberExpr may give
14626   // stronger guarantees than the class containing the member.
14627   if (DRE && !TopME->isArrow()) {
14628     const ValueDecl *VD = DRE->getDecl();
14629     if (!VD->getType()->isReferenceType())
14630       CompleteObjectAlignment =
14631           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14632   }
14633 
14634   // Check if the synthesized offset fulfills the alignment.
14635   if (Offset % ExpectedAlignment != 0 ||
14636       // It may fulfill the offset it but the effective alignment may still be
14637       // lower than the expected expression alignment.
14638       CompleteObjectAlignment < ExpectedAlignment) {
14639     // If this happens, we want to determine a sensible culprit of this.
14640     // Intuitively, watching the chain of member expressions from right to
14641     // left, we start with the required alignment (as required by the field
14642     // type) but some packed attribute in that chain has reduced the alignment.
14643     // It may happen that another packed structure increases it again. But if
14644     // we are here such increase has not been enough. So pointing the first
14645     // FieldDecl that either is packed or else its RecordDecl is,
14646     // seems reasonable.
14647     FieldDecl *FD = nullptr;
14648     CharUnits Alignment;
14649     for (FieldDecl *FDI : ReverseMemberChain) {
14650       if (FDI->hasAttr<PackedAttr>() ||
14651           FDI->getParent()->hasAttr<PackedAttr>()) {
14652         FD = FDI;
14653         Alignment = std::min(
14654             Context.getTypeAlignInChars(FD->getType()),
14655             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14656         break;
14657       }
14658     }
14659     assert(FD && "We did not find a packed FieldDecl!");
14660     Action(E, FD->getParent(), FD, Alignment);
14661   }
14662 }
14663 
14664 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14665   using namespace std::placeholders;
14666 
14667   RefersToMemberWithReducedAlignment(
14668       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14669                      _2, _3, _4));
14670 }
14671