1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197   if (checkArgCount(S, TheCall, 1))
198     return true;
199 
200   TheCall->setType(TheCall->getArg(0)->getType());
201   return false;
202 }
203 
204 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
205   if (checkArgCount(S, TheCall, 3))
206     return true;
207 
208   // First two arguments should be integers.
209   for (unsigned I = 0; I < 2; ++I) {
210     ExprResult Arg = TheCall->getArg(I);
211     QualType Ty = Arg.get()->getType();
212     if (!Ty->isIntegerType()) {
213       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
214           << Ty << Arg.get()->getSourceRange();
215       return true;
216     }
217     InitializedEntity Entity = InitializedEntity::InitializeParameter(
218         S.getASTContext(), Ty, /*consume*/ false);
219     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
220     if (Arg.isInvalid())
221       return true;
222     TheCall->setArg(I, Arg.get());
223   }
224 
225   // Third argument should be a pointer to a non-const integer.
226   // IRGen correctly handles volatile, restrict, and address spaces, and
227   // the other qualifiers aren't possible.
228   {
229     ExprResult Arg = TheCall->getArg(2);
230     QualType Ty = Arg.get()->getType();
231     const auto *PtrTy = Ty->getAs<PointerType>();
232     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
233           !PtrTy->getPointeeType().isConstQualified())) {
234       S.Diag(Arg.get()->getBeginLoc(),
235              diag::err_overflow_builtin_must_be_ptr_int)
236           << Ty << Arg.get()->getSourceRange();
237       return true;
238     }
239     InitializedEntity Entity = InitializedEntity::InitializeParameter(
240         S.getASTContext(), Ty, /*consume*/ false);
241     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
242     if (Arg.isInvalid())
243       return true;
244     TheCall->setArg(2, Arg.get());
245   }
246   return false;
247 }
248 
249 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
250   if (checkArgCount(S, BuiltinCall, 2))
251     return true;
252 
253   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
254   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
255   Expr *Call = BuiltinCall->getArg(0);
256   Expr *Chain = BuiltinCall->getArg(1);
257 
258   if (Call->getStmtClass() != Stmt::CallExprClass) {
259     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
260         << Call->getSourceRange();
261     return true;
262   }
263 
264   auto CE = cast<CallExpr>(Call);
265   if (CE->getCallee()->getType()->isBlockPointerType()) {
266     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
267         << Call->getSourceRange();
268     return true;
269   }
270 
271   const Decl *TargetDecl = CE->getCalleeDecl();
272   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
273     if (FD->getBuiltinID()) {
274       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
275           << Call->getSourceRange();
276       return true;
277     }
278 
279   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
280     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
281         << Call->getSourceRange();
282     return true;
283   }
284 
285   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
286   if (ChainResult.isInvalid())
287     return true;
288   if (!ChainResult.get()->getType()->isPointerType()) {
289     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
290         << Chain->getSourceRange();
291     return true;
292   }
293 
294   QualType ReturnTy = CE->getCallReturnType(S.Context);
295   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
296   QualType BuiltinTy = S.Context.getFunctionType(
297       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
298   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
299 
300   Builtin =
301       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
302 
303   BuiltinCall->setType(CE->getType());
304   BuiltinCall->setValueKind(CE->getValueKind());
305   BuiltinCall->setObjectKind(CE->getObjectKind());
306   BuiltinCall->setCallee(Builtin);
307   BuiltinCall->setArg(1, ChainResult.get());
308 
309   return false;
310 }
311 
312 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
313 /// __builtin_*_chk function, then use the object size argument specified in the
314 /// source. Otherwise, infer the object size using __builtin_object_size.
315 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
316                                                CallExpr *TheCall) {
317   // FIXME: There are some more useful checks we could be doing here:
318   //  - Analyze the format string of sprintf to see how much of buffer is used.
319   //  - Evaluate strlen of strcpy arguments, use as object size.
320 
321   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
322       isConstantEvaluated())
323     return;
324 
325   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
326   if (!BuiltinID)
327     return;
328 
329   unsigned DiagID = 0;
330   bool IsChkVariant = false;
331   unsigned SizeIndex, ObjectIndex;
332   switch (BuiltinID) {
333   default:
334     return;
335   case Builtin::BI__builtin___memcpy_chk:
336   case Builtin::BI__builtin___memmove_chk:
337   case Builtin::BI__builtin___memset_chk:
338   case Builtin::BI__builtin___strlcat_chk:
339   case Builtin::BI__builtin___strlcpy_chk:
340   case Builtin::BI__builtin___strncat_chk:
341   case Builtin::BI__builtin___strncpy_chk:
342   case Builtin::BI__builtin___stpncpy_chk:
343   case Builtin::BI__builtin___memccpy_chk: {
344     DiagID = diag::warn_builtin_chk_overflow;
345     IsChkVariant = true;
346     SizeIndex = TheCall->getNumArgs() - 2;
347     ObjectIndex = TheCall->getNumArgs() - 1;
348     break;
349   }
350 
351   case Builtin::BI__builtin___snprintf_chk:
352   case Builtin::BI__builtin___vsnprintf_chk: {
353     DiagID = diag::warn_builtin_chk_overflow;
354     IsChkVariant = true;
355     SizeIndex = 1;
356     ObjectIndex = 3;
357     break;
358   }
359 
360   case Builtin::BIstrncat:
361   case Builtin::BI__builtin_strncat:
362   case Builtin::BIstrncpy:
363   case Builtin::BI__builtin_strncpy:
364   case Builtin::BIstpncpy:
365   case Builtin::BI__builtin_stpncpy: {
366     // Whether these functions overflow depends on the runtime strlen of the
367     // string, not just the buffer size, so emitting the "always overflow"
368     // diagnostic isn't quite right. We should still diagnose passing a buffer
369     // size larger than the destination buffer though; this is a runtime abort
370     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
371     DiagID = diag::warn_fortify_source_size_mismatch;
372     SizeIndex = TheCall->getNumArgs() - 1;
373     ObjectIndex = 0;
374     break;
375   }
376 
377   case Builtin::BImemcpy:
378   case Builtin::BI__builtin_memcpy:
379   case Builtin::BImemmove:
380   case Builtin::BI__builtin_memmove:
381   case Builtin::BImemset:
382   case Builtin::BI__builtin_memset: {
383     DiagID = diag::warn_fortify_source_overflow;
384     SizeIndex = TheCall->getNumArgs() - 1;
385     ObjectIndex = 0;
386     break;
387   }
388   case Builtin::BIsnprintf:
389   case Builtin::BI__builtin_snprintf:
390   case Builtin::BIvsnprintf:
391   case Builtin::BI__builtin_vsnprintf: {
392     DiagID = diag::warn_fortify_source_size_mismatch;
393     SizeIndex = 1;
394     ObjectIndex = 0;
395     break;
396   }
397   }
398 
399   llvm::APSInt ObjectSize;
400   // For __builtin___*_chk, the object size is explicitly provided by the caller
401   // (usually using __builtin_object_size). Use that value to check this call.
402   if (IsChkVariant) {
403     Expr::EvalResult Result;
404     Expr *SizeArg = TheCall->getArg(ObjectIndex);
405     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
406       return;
407     ObjectSize = Result.Val.getInt();
408 
409   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
410   } else {
411     // If the parameter has a pass_object_size attribute, then we should use its
412     // (potentially) more strict checking mode. Otherwise, conservatively assume
413     // type 0.
414     int BOSType = 0;
415     if (const auto *POS =
416             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
417       BOSType = POS->getType();
418 
419     Expr *ObjArg = TheCall->getArg(ObjectIndex);
420     uint64_t Result;
421     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
422       return;
423     // Get the object size in the target's size_t width.
424     const TargetInfo &TI = getASTContext().getTargetInfo();
425     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
426     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
427   }
428 
429   // Evaluate the number of bytes of the object that this call will use.
430   Expr::EvalResult Result;
431   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
432   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
433     return;
434   llvm::APSInt UsedSize = Result.Val.getInt();
435 
436   if (UsedSize.ule(ObjectSize))
437     return;
438 
439   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
440   // Skim off the details of whichever builtin was called to produce a better
441   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
442   if (IsChkVariant) {
443     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
444     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
445   } else if (FunctionName.startswith("__builtin_")) {
446     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
447   }
448 
449   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
450                       PDiag(DiagID)
451                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
452                           << UsedSize.toString(/*Radix=*/10));
453 }
454 
455 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
456                                      Scope::ScopeFlags NeededScopeFlags,
457                                      unsigned DiagID) {
458   // Scopes aren't available during instantiation. Fortunately, builtin
459   // functions cannot be template args so they cannot be formed through template
460   // instantiation. Therefore checking once during the parse is sufficient.
461   if (SemaRef.inTemplateInstantiation())
462     return false;
463 
464   Scope *S = SemaRef.getCurScope();
465   while (S && !S->isSEHExceptScope())
466     S = S->getParent();
467   if (!S || !(S->getFlags() & NeededScopeFlags)) {
468     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
469     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
470         << DRE->getDecl()->getIdentifier();
471     return true;
472   }
473 
474   return false;
475 }
476 
477 static inline bool isBlockPointer(Expr *Arg) {
478   return Arg->getType()->isBlockPointerType();
479 }
480 
481 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
482 /// void*, which is a requirement of device side enqueue.
483 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
484   const BlockPointerType *BPT =
485       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
486   ArrayRef<QualType> Params =
487       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
488   unsigned ArgCounter = 0;
489   bool IllegalParams = false;
490   // Iterate through the block parameters until either one is found that is not
491   // a local void*, or the block is valid.
492   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
493        I != E; ++I, ++ArgCounter) {
494     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
495         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
496             LangAS::opencl_local) {
497       // Get the location of the error. If a block literal has been passed
498       // (BlockExpr) then we can point straight to the offending argument,
499       // else we just point to the variable reference.
500       SourceLocation ErrorLoc;
501       if (isa<BlockExpr>(BlockArg)) {
502         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
503         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
504       } else if (isa<DeclRefExpr>(BlockArg)) {
505         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
506       }
507       S.Diag(ErrorLoc,
508              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
509       IllegalParams = true;
510     }
511   }
512 
513   return IllegalParams;
514 }
515 
516 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
517   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
518     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
519         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
520     return true;
521   }
522   return false;
523 }
524 
525 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
526   if (checkArgCount(S, TheCall, 2))
527     return true;
528 
529   if (checkOpenCLSubgroupExt(S, TheCall))
530     return true;
531 
532   // First argument is an ndrange_t type.
533   Expr *NDRangeArg = TheCall->getArg(0);
534   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
535     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
536         << TheCall->getDirectCallee() << "'ndrange_t'";
537     return true;
538   }
539 
540   Expr *BlockArg = TheCall->getArg(1);
541   if (!isBlockPointer(BlockArg)) {
542     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
543         << TheCall->getDirectCallee() << "block";
544     return true;
545   }
546   return checkOpenCLBlockArgs(S, BlockArg);
547 }
548 
549 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
550 /// get_kernel_work_group_size
551 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
552 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
553   if (checkArgCount(S, TheCall, 1))
554     return true;
555 
556   Expr *BlockArg = TheCall->getArg(0);
557   if (!isBlockPointer(BlockArg)) {
558     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
559         << TheCall->getDirectCallee() << "block";
560     return true;
561   }
562   return checkOpenCLBlockArgs(S, BlockArg);
563 }
564 
565 /// Diagnose integer type and any valid implicit conversion to it.
566 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
567                                       const QualType &IntType);
568 
569 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
570                                             unsigned Start, unsigned End) {
571   bool IllegalParams = false;
572   for (unsigned I = Start; I <= End; ++I)
573     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
574                                               S.Context.getSizeType());
575   return IllegalParams;
576 }
577 
578 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
579 /// 'local void*' parameter of passed block.
580 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
581                                            Expr *BlockArg,
582                                            unsigned NumNonVarArgs) {
583   const BlockPointerType *BPT =
584       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
585   unsigned NumBlockParams =
586       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
587   unsigned TotalNumArgs = TheCall->getNumArgs();
588 
589   // For each argument passed to the block, a corresponding uint needs to
590   // be passed to describe the size of the local memory.
591   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
592     S.Diag(TheCall->getBeginLoc(),
593            diag::err_opencl_enqueue_kernel_local_size_args);
594     return true;
595   }
596 
597   // Check that the sizes of the local memory are specified by integers.
598   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
599                                          TotalNumArgs - 1);
600 }
601 
602 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
603 /// overload formats specified in Table 6.13.17.1.
604 /// int enqueue_kernel(queue_t queue,
605 ///                    kernel_enqueue_flags_t flags,
606 ///                    const ndrange_t ndrange,
607 ///                    void (^block)(void))
608 /// int enqueue_kernel(queue_t queue,
609 ///                    kernel_enqueue_flags_t flags,
610 ///                    const ndrange_t ndrange,
611 ///                    uint num_events_in_wait_list,
612 ///                    clk_event_t *event_wait_list,
613 ///                    clk_event_t *event_ret,
614 ///                    void (^block)(void))
615 /// int enqueue_kernel(queue_t queue,
616 ///                    kernel_enqueue_flags_t flags,
617 ///                    const ndrange_t ndrange,
618 ///                    void (^block)(local void*, ...),
619 ///                    uint size0, ...)
620 /// int enqueue_kernel(queue_t queue,
621 ///                    kernel_enqueue_flags_t flags,
622 ///                    const ndrange_t ndrange,
623 ///                    uint num_events_in_wait_list,
624 ///                    clk_event_t *event_wait_list,
625 ///                    clk_event_t *event_ret,
626 ///                    void (^block)(local void*, ...),
627 ///                    uint size0, ...)
628 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
629   unsigned NumArgs = TheCall->getNumArgs();
630 
631   if (NumArgs < 4) {
632     S.Diag(TheCall->getBeginLoc(),
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()->getAs<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::hexagon:
1544         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1545           return ExprError();
1546         break;
1547       case llvm::Triple::mips:
1548       case llvm::Triple::mipsel:
1549       case llvm::Triple::mips64:
1550       case llvm::Triple::mips64el:
1551         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1552           return ExprError();
1553         break;
1554       case llvm::Triple::systemz:
1555         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1556           return ExprError();
1557         break;
1558       case llvm::Triple::x86:
1559       case llvm::Triple::x86_64:
1560         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1561           return ExprError();
1562         break;
1563       case llvm::Triple::ppc:
1564       case llvm::Triple::ppc64:
1565       case llvm::Triple::ppc64le:
1566         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1567           return ExprError();
1568         break;
1569       default:
1570         break;
1571     }
1572   }
1573 
1574   return TheCallResult;
1575 }
1576 
1577 // Get the valid immediate range for the specified NEON type code.
1578 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1579   NeonTypeFlags Type(t);
1580   int IsQuad = ForceQuad ? true : Type.isQuad();
1581   switch (Type.getEltType()) {
1582   case NeonTypeFlags::Int8:
1583   case NeonTypeFlags::Poly8:
1584     return shift ? 7 : (8 << IsQuad) - 1;
1585   case NeonTypeFlags::Int16:
1586   case NeonTypeFlags::Poly16:
1587     return shift ? 15 : (4 << IsQuad) - 1;
1588   case NeonTypeFlags::Int32:
1589     return shift ? 31 : (2 << IsQuad) - 1;
1590   case NeonTypeFlags::Int64:
1591   case NeonTypeFlags::Poly64:
1592     return shift ? 63 : (1 << IsQuad) - 1;
1593   case NeonTypeFlags::Poly128:
1594     return shift ? 127 : (1 << IsQuad) - 1;
1595   case NeonTypeFlags::Float16:
1596     assert(!shift && "cannot shift float types!");
1597     return (4 << IsQuad) - 1;
1598   case NeonTypeFlags::Float32:
1599     assert(!shift && "cannot shift float types!");
1600     return (2 << IsQuad) - 1;
1601   case NeonTypeFlags::Float64:
1602     assert(!shift && "cannot shift float types!");
1603     return (1 << IsQuad) - 1;
1604   }
1605   llvm_unreachable("Invalid NeonTypeFlag!");
1606 }
1607 
1608 /// getNeonEltType - Return the QualType corresponding to the elements of
1609 /// the vector type specified by the NeonTypeFlags.  This is used to check
1610 /// the pointer arguments for Neon load/store intrinsics.
1611 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1612                                bool IsPolyUnsigned, bool IsInt64Long) {
1613   switch (Flags.getEltType()) {
1614   case NeonTypeFlags::Int8:
1615     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1616   case NeonTypeFlags::Int16:
1617     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1618   case NeonTypeFlags::Int32:
1619     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1620   case NeonTypeFlags::Int64:
1621     if (IsInt64Long)
1622       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1623     else
1624       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1625                                 : Context.LongLongTy;
1626   case NeonTypeFlags::Poly8:
1627     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1628   case NeonTypeFlags::Poly16:
1629     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1630   case NeonTypeFlags::Poly64:
1631     if (IsInt64Long)
1632       return Context.UnsignedLongTy;
1633     else
1634       return Context.UnsignedLongLongTy;
1635   case NeonTypeFlags::Poly128:
1636     break;
1637   case NeonTypeFlags::Float16:
1638     return Context.HalfTy;
1639   case NeonTypeFlags::Float32:
1640     return Context.FloatTy;
1641   case NeonTypeFlags::Float64:
1642     return Context.DoubleTy;
1643   }
1644   llvm_unreachable("Invalid NeonTypeFlag!");
1645 }
1646 
1647 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1648   llvm::APSInt Result;
1649   uint64_t mask = 0;
1650   unsigned TV = 0;
1651   int PtrArgNum = -1;
1652   bool HasConstPtr = false;
1653   switch (BuiltinID) {
1654 #define GET_NEON_OVERLOAD_CHECK
1655 #include "clang/Basic/arm_neon.inc"
1656 #include "clang/Basic/arm_fp16.inc"
1657 #undef GET_NEON_OVERLOAD_CHECK
1658   }
1659 
1660   // For NEON intrinsics which are overloaded on vector element type, validate
1661   // the immediate which specifies which variant to emit.
1662   unsigned ImmArg = TheCall->getNumArgs()-1;
1663   if (mask) {
1664     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1665       return true;
1666 
1667     TV = Result.getLimitedValue(64);
1668     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1669       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1670              << TheCall->getArg(ImmArg)->getSourceRange();
1671   }
1672 
1673   if (PtrArgNum >= 0) {
1674     // Check that pointer arguments have the specified type.
1675     Expr *Arg = TheCall->getArg(PtrArgNum);
1676     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1677       Arg = ICE->getSubExpr();
1678     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1679     QualType RHSTy = RHS.get()->getType();
1680 
1681     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1682     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1683                           Arch == llvm::Triple::aarch64_be;
1684     bool IsInt64Long =
1685         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1686     QualType EltTy =
1687         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1688     if (HasConstPtr)
1689       EltTy = EltTy.withConst();
1690     QualType LHSTy = Context.getPointerType(EltTy);
1691     AssignConvertType ConvTy;
1692     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1693     if (RHS.isInvalid())
1694       return true;
1695     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1696                                  RHS.get(), AA_Assigning))
1697       return true;
1698   }
1699 
1700   // For NEON intrinsics which take an immediate value as part of the
1701   // instruction, range check them here.
1702   unsigned i = 0, l = 0, u = 0;
1703   switch (BuiltinID) {
1704   default:
1705     return false;
1706   #define GET_NEON_IMMEDIATE_CHECK
1707   #include "clang/Basic/arm_neon.inc"
1708   #include "clang/Basic/arm_fp16.inc"
1709   #undef GET_NEON_IMMEDIATE_CHECK
1710   }
1711 
1712   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1713 }
1714 
1715 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1716                                         unsigned MaxWidth) {
1717   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1718           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1719           BuiltinID == ARM::BI__builtin_arm_strex ||
1720           BuiltinID == ARM::BI__builtin_arm_stlex ||
1721           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1722           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1723           BuiltinID == AArch64::BI__builtin_arm_strex ||
1724           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1725          "unexpected ARM builtin");
1726   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1727                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1728                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1729                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1730 
1731   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1732 
1733   // Ensure that we have the proper number of arguments.
1734   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1735     return true;
1736 
1737   // Inspect the pointer argument of the atomic builtin.  This should always be
1738   // a pointer type, whose element is an integral scalar or pointer type.
1739   // Because it is a pointer type, we don't have to worry about any implicit
1740   // casts here.
1741   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1742   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1743   if (PointerArgRes.isInvalid())
1744     return true;
1745   PointerArg = PointerArgRes.get();
1746 
1747   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1748   if (!pointerType) {
1749     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1750         << PointerArg->getType() << PointerArg->getSourceRange();
1751     return true;
1752   }
1753 
1754   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1755   // task is to insert the appropriate casts into the AST. First work out just
1756   // what the appropriate type is.
1757   QualType ValType = pointerType->getPointeeType();
1758   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1759   if (IsLdrex)
1760     AddrType.addConst();
1761 
1762   // Issue a warning if the cast is dodgy.
1763   CastKind CastNeeded = CK_NoOp;
1764   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1765     CastNeeded = CK_BitCast;
1766     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1767         << PointerArg->getType() << Context.getPointerType(AddrType)
1768         << AA_Passing << PointerArg->getSourceRange();
1769   }
1770 
1771   // Finally, do the cast and replace the argument with the corrected version.
1772   AddrType = Context.getPointerType(AddrType);
1773   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1774   if (PointerArgRes.isInvalid())
1775     return true;
1776   PointerArg = PointerArgRes.get();
1777 
1778   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1779 
1780   // In general, we allow ints, floats and pointers to be loaded and stored.
1781   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1782       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1783     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1784         << PointerArg->getType() << PointerArg->getSourceRange();
1785     return true;
1786   }
1787 
1788   // But ARM doesn't have instructions to deal with 128-bit versions.
1789   if (Context.getTypeSize(ValType) > MaxWidth) {
1790     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1791     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1792         << PointerArg->getType() << PointerArg->getSourceRange();
1793     return true;
1794   }
1795 
1796   switch (ValType.getObjCLifetime()) {
1797   case Qualifiers::OCL_None:
1798   case Qualifiers::OCL_ExplicitNone:
1799     // okay
1800     break;
1801 
1802   case Qualifiers::OCL_Weak:
1803   case Qualifiers::OCL_Strong:
1804   case Qualifiers::OCL_Autoreleasing:
1805     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1806         << ValType << PointerArg->getSourceRange();
1807     return true;
1808   }
1809 
1810   if (IsLdrex) {
1811     TheCall->setType(ValType);
1812     return false;
1813   }
1814 
1815   // Initialize the argument to be stored.
1816   ExprResult ValArg = TheCall->getArg(0);
1817   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1818       Context, ValType, /*consume*/ false);
1819   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1820   if (ValArg.isInvalid())
1821     return true;
1822   TheCall->setArg(0, ValArg.get());
1823 
1824   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1825   // but the custom checker bypasses all default analysis.
1826   TheCall->setType(Context.IntTy);
1827   return false;
1828 }
1829 
1830 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1831   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1832       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1833       BuiltinID == ARM::BI__builtin_arm_strex ||
1834       BuiltinID == ARM::BI__builtin_arm_stlex) {
1835     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1836   }
1837 
1838   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1839     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1840       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1841   }
1842 
1843   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1844       BuiltinID == ARM::BI__builtin_arm_wsr64)
1845     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1846 
1847   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1848       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1849       BuiltinID == ARM::BI__builtin_arm_wsr ||
1850       BuiltinID == ARM::BI__builtin_arm_wsrp)
1851     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1852 
1853   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1854     return true;
1855 
1856   // For intrinsics which take an immediate value as part of the instruction,
1857   // range check them here.
1858   // FIXME: VFP Intrinsics should error if VFP not present.
1859   switch (BuiltinID) {
1860   default: return false;
1861   case ARM::BI__builtin_arm_ssat:
1862     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1863   case ARM::BI__builtin_arm_usat:
1864     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1865   case ARM::BI__builtin_arm_ssat16:
1866     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1867   case ARM::BI__builtin_arm_usat16:
1868     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1869   case ARM::BI__builtin_arm_vcvtr_f:
1870   case ARM::BI__builtin_arm_vcvtr_d:
1871     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1872   case ARM::BI__builtin_arm_dmb:
1873   case ARM::BI__builtin_arm_dsb:
1874   case ARM::BI__builtin_arm_isb:
1875   case ARM::BI__builtin_arm_dbg:
1876     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1877   }
1878 }
1879 
1880 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1881                                          CallExpr *TheCall) {
1882   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1883       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1884       BuiltinID == AArch64::BI__builtin_arm_strex ||
1885       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1886     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1887   }
1888 
1889   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1890     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1891       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1892       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1893       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1894   }
1895 
1896   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1897       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1898     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1899 
1900   // Memory Tagging Extensions (MTE) Intrinsics
1901   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1902       BuiltinID == AArch64::BI__builtin_arm_addg ||
1903       BuiltinID == AArch64::BI__builtin_arm_gmi ||
1904       BuiltinID == AArch64::BI__builtin_arm_ldg ||
1905       BuiltinID == AArch64::BI__builtin_arm_stg ||
1906       BuiltinID == AArch64::BI__builtin_arm_subp) {
1907     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1908   }
1909 
1910   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1911       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1912       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1913       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1914     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1915 
1916   // Only check the valid encoding range. Any constant in this range would be
1917   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1918   // an exception for incorrect registers. This matches MSVC behavior.
1919   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1920       BuiltinID == AArch64::BI_WriteStatusReg)
1921     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1922 
1923   if (BuiltinID == AArch64::BI__getReg)
1924     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1925 
1926   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1927     return true;
1928 
1929   // For intrinsics which take an immediate value as part of the instruction,
1930   // range check them here.
1931   unsigned i = 0, l = 0, u = 0;
1932   switch (BuiltinID) {
1933   default: return false;
1934   case AArch64::BI__builtin_arm_dmb:
1935   case AArch64::BI__builtin_arm_dsb:
1936   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1937   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
1938   }
1939 
1940   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1941 }
1942 
1943 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1944   struct BuiltinAndString {
1945     unsigned BuiltinID;
1946     const char *Str;
1947   };
1948 
1949   static BuiltinAndString ValidCPU[] = {
1950     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1951     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1952     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1953     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1954     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1955     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1958     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1970     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1971     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1972     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1973   };
1974 
1975   static BuiltinAndString ValidHVX[] = {
1976     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2671     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2672     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2673     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2674     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2675     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2676     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2677     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2678     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2679     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2680     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2681     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2682     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2683     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2684     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2685     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2686     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2687     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2688     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2689     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2690     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2691     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2692     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2693     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2694     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2695     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2696     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2697     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2706     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2708   };
2709 
2710   // Sort the tables on first execution so we can binary search them.
2711   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2712     return LHS.BuiltinID < RHS.BuiltinID;
2713   };
2714   static const bool SortOnce =
2715       (llvm::sort(ValidCPU, SortCmp),
2716        llvm::sort(ValidHVX, SortCmp), true);
2717   (void)SortOnce;
2718   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2719     return BI.BuiltinID < BuiltinID;
2720   };
2721 
2722   const TargetInfo &TI = Context.getTargetInfo();
2723 
2724   const BuiltinAndString *FC =
2725       llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2726   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2727     const TargetOptions &Opts = TI.getTargetOpts();
2728     StringRef CPU = Opts.CPU;
2729     if (!CPU.empty()) {
2730       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2731       CPU.consume_front("hexagon");
2732       SmallVector<StringRef, 3> CPUs;
2733       StringRef(FC->Str).split(CPUs, ',');
2734       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2735         return Diag(TheCall->getBeginLoc(),
2736                     diag::err_hexagon_builtin_unsupported_cpu);
2737     }
2738   }
2739 
2740   const BuiltinAndString *FH =
2741       llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2742   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2743     if (!TI.hasFeature("hvx"))
2744       return Diag(TheCall->getBeginLoc(),
2745                   diag::err_hexagon_builtin_requires_hvx);
2746 
2747     SmallVector<StringRef, 3> HVXs;
2748     StringRef(FH->Str).split(HVXs, ',');
2749     bool IsValid = llvm::any_of(HVXs,
2750                                 [&TI] (StringRef V) {
2751                                   std::string F = "hvx" + V.str();
2752                                   return TI.hasFeature(F);
2753                                 });
2754     if (!IsValid)
2755       return Diag(TheCall->getBeginLoc(),
2756                   diag::err_hexagon_builtin_unsupported_hvx);
2757   }
2758 
2759   return false;
2760 }
2761 
2762 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2763   struct ArgInfo {
2764     uint8_t OpNum;
2765     bool IsSigned;
2766     uint8_t BitWidth;
2767     uint8_t Align;
2768   };
2769   struct BuiltinInfo {
2770     unsigned BuiltinID;
2771     ArgInfo Infos[2];
2772   };
2773 
2774   static BuiltinInfo Infos[] = {
2775     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2776     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2777     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2779     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2780     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2782     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2783     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2784     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2785     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2786 
2787     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2790     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2791     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2792     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2798 
2799     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2851                                                       {{ 1, false, 6,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2859                                                       {{ 1, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2866                                                        { 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2868                                                        { 2, false, 6,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2870                                                        { 3, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2872                                                        { 3, false, 6,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2889                                                       {{ 2, false, 4,  0 },
2890                                                        { 3, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2892                                                       {{ 2, false, 4,  0 },
2893                                                        { 3, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2895                                                       {{ 2, false, 4,  0 },
2896                                                        { 3, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2898                                                       {{ 2, false, 4,  0 },
2899                                                        { 3, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2911                                                        { 2, false, 5,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2913                                                        { 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2923                                                       {{ 1, false, 4,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2926                                                       {{ 1, false, 4,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2947                                                       {{ 3, false, 1,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2952                                                       {{ 3, false, 1,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2957                                                       {{ 3, false, 1,  0 }} },
2958   };
2959 
2960   // Use a dynamically initialized static to sort the table exactly once on
2961   // first run.
2962   static const bool SortOnce =
2963       (llvm::sort(Infos,
2964                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2965                    return LHS.BuiltinID < RHS.BuiltinID;
2966                  }),
2967        true);
2968   (void)SortOnce;
2969 
2970   const BuiltinInfo *F = llvm::partition_point(
2971       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2972   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2973     return false;
2974 
2975   bool Error = false;
2976 
2977   for (const ArgInfo &A : F->Infos) {
2978     // Ignore empty ArgInfo elements.
2979     if (A.BitWidth == 0)
2980       continue;
2981 
2982     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2983     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2984     if (!A.Align) {
2985       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2986     } else {
2987       unsigned M = 1 << A.Align;
2988       Min *= M;
2989       Max *= M;
2990       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2991                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2992     }
2993   }
2994   return Error;
2995 }
2996 
2997 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2998                                            CallExpr *TheCall) {
2999   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3000          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001 }
3002 
3003 
3004 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3005 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3006 // ordering for DSP is unspecified. MSA is ordered by the data format used
3007 // by the underlying instruction i.e., df/m, df/n and then by size.
3008 //
3009 // FIXME: The size tests here should instead be tablegen'd along with the
3010 //        definitions from include/clang/Basic/BuiltinsMips.def.
3011 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3012 //        be too.
3013 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3014   unsigned i = 0, l = 0, u = 0, m = 0;
3015   switch (BuiltinID) {
3016   default: return false;
3017   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3018   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3019   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3020   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3021   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3022   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3023   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3024   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3025   // df/m field.
3026   // These intrinsics take an unsigned 3 bit immediate.
3027   case Mips::BI__builtin_msa_bclri_b:
3028   case Mips::BI__builtin_msa_bnegi_b:
3029   case Mips::BI__builtin_msa_bseti_b:
3030   case Mips::BI__builtin_msa_sat_s_b:
3031   case Mips::BI__builtin_msa_sat_u_b:
3032   case Mips::BI__builtin_msa_slli_b:
3033   case Mips::BI__builtin_msa_srai_b:
3034   case Mips::BI__builtin_msa_srari_b:
3035   case Mips::BI__builtin_msa_srli_b:
3036   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3037   case Mips::BI__builtin_msa_binsli_b:
3038   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3039   // These intrinsics take an unsigned 4 bit immediate.
3040   case Mips::BI__builtin_msa_bclri_h:
3041   case Mips::BI__builtin_msa_bnegi_h:
3042   case Mips::BI__builtin_msa_bseti_h:
3043   case Mips::BI__builtin_msa_sat_s_h:
3044   case Mips::BI__builtin_msa_sat_u_h:
3045   case Mips::BI__builtin_msa_slli_h:
3046   case Mips::BI__builtin_msa_srai_h:
3047   case Mips::BI__builtin_msa_srari_h:
3048   case Mips::BI__builtin_msa_srli_h:
3049   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3050   case Mips::BI__builtin_msa_binsli_h:
3051   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3052   // These intrinsics take an unsigned 5 bit immediate.
3053   // The first block of intrinsics actually have an unsigned 5 bit field,
3054   // not a df/n field.
3055   case Mips::BI__builtin_msa_cfcmsa:
3056   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3057   case Mips::BI__builtin_msa_clei_u_b:
3058   case Mips::BI__builtin_msa_clei_u_h:
3059   case Mips::BI__builtin_msa_clei_u_w:
3060   case Mips::BI__builtin_msa_clei_u_d:
3061   case Mips::BI__builtin_msa_clti_u_b:
3062   case Mips::BI__builtin_msa_clti_u_h:
3063   case Mips::BI__builtin_msa_clti_u_w:
3064   case Mips::BI__builtin_msa_clti_u_d:
3065   case Mips::BI__builtin_msa_maxi_u_b:
3066   case Mips::BI__builtin_msa_maxi_u_h:
3067   case Mips::BI__builtin_msa_maxi_u_w:
3068   case Mips::BI__builtin_msa_maxi_u_d:
3069   case Mips::BI__builtin_msa_mini_u_b:
3070   case Mips::BI__builtin_msa_mini_u_h:
3071   case Mips::BI__builtin_msa_mini_u_w:
3072   case Mips::BI__builtin_msa_mini_u_d:
3073   case Mips::BI__builtin_msa_addvi_b:
3074   case Mips::BI__builtin_msa_addvi_h:
3075   case Mips::BI__builtin_msa_addvi_w:
3076   case Mips::BI__builtin_msa_addvi_d:
3077   case Mips::BI__builtin_msa_bclri_w:
3078   case Mips::BI__builtin_msa_bnegi_w:
3079   case Mips::BI__builtin_msa_bseti_w:
3080   case Mips::BI__builtin_msa_sat_s_w:
3081   case Mips::BI__builtin_msa_sat_u_w:
3082   case Mips::BI__builtin_msa_slli_w:
3083   case Mips::BI__builtin_msa_srai_w:
3084   case Mips::BI__builtin_msa_srari_w:
3085   case Mips::BI__builtin_msa_srli_w:
3086   case Mips::BI__builtin_msa_srlri_w:
3087   case Mips::BI__builtin_msa_subvi_b:
3088   case Mips::BI__builtin_msa_subvi_h:
3089   case Mips::BI__builtin_msa_subvi_w:
3090   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3091   case Mips::BI__builtin_msa_binsli_w:
3092   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3093   // These intrinsics take an unsigned 6 bit immediate.
3094   case Mips::BI__builtin_msa_bclri_d:
3095   case Mips::BI__builtin_msa_bnegi_d:
3096   case Mips::BI__builtin_msa_bseti_d:
3097   case Mips::BI__builtin_msa_sat_s_d:
3098   case Mips::BI__builtin_msa_sat_u_d:
3099   case Mips::BI__builtin_msa_slli_d:
3100   case Mips::BI__builtin_msa_srai_d:
3101   case Mips::BI__builtin_msa_srari_d:
3102   case Mips::BI__builtin_msa_srli_d:
3103   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3104   case Mips::BI__builtin_msa_binsli_d:
3105   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3106   // These intrinsics take a signed 5 bit immediate.
3107   case Mips::BI__builtin_msa_ceqi_b:
3108   case Mips::BI__builtin_msa_ceqi_h:
3109   case Mips::BI__builtin_msa_ceqi_w:
3110   case Mips::BI__builtin_msa_ceqi_d:
3111   case Mips::BI__builtin_msa_clti_s_b:
3112   case Mips::BI__builtin_msa_clti_s_h:
3113   case Mips::BI__builtin_msa_clti_s_w:
3114   case Mips::BI__builtin_msa_clti_s_d:
3115   case Mips::BI__builtin_msa_clei_s_b:
3116   case Mips::BI__builtin_msa_clei_s_h:
3117   case Mips::BI__builtin_msa_clei_s_w:
3118   case Mips::BI__builtin_msa_clei_s_d:
3119   case Mips::BI__builtin_msa_maxi_s_b:
3120   case Mips::BI__builtin_msa_maxi_s_h:
3121   case Mips::BI__builtin_msa_maxi_s_w:
3122   case Mips::BI__builtin_msa_maxi_s_d:
3123   case Mips::BI__builtin_msa_mini_s_b:
3124   case Mips::BI__builtin_msa_mini_s_h:
3125   case Mips::BI__builtin_msa_mini_s_w:
3126   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3127   // These intrinsics take an unsigned 8 bit immediate.
3128   case Mips::BI__builtin_msa_andi_b:
3129   case Mips::BI__builtin_msa_nori_b:
3130   case Mips::BI__builtin_msa_ori_b:
3131   case Mips::BI__builtin_msa_shf_b:
3132   case Mips::BI__builtin_msa_shf_h:
3133   case Mips::BI__builtin_msa_shf_w:
3134   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3135   case Mips::BI__builtin_msa_bseli_b:
3136   case Mips::BI__builtin_msa_bmnzi_b:
3137   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3138   // df/n format
3139   // These intrinsics take an unsigned 4 bit immediate.
3140   case Mips::BI__builtin_msa_copy_s_b:
3141   case Mips::BI__builtin_msa_copy_u_b:
3142   case Mips::BI__builtin_msa_insve_b:
3143   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3144   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3145   // These intrinsics take an unsigned 3 bit immediate.
3146   case Mips::BI__builtin_msa_copy_s_h:
3147   case Mips::BI__builtin_msa_copy_u_h:
3148   case Mips::BI__builtin_msa_insve_h:
3149   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3150   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3151   // These intrinsics take an unsigned 2 bit immediate.
3152   case Mips::BI__builtin_msa_copy_s_w:
3153   case Mips::BI__builtin_msa_copy_u_w:
3154   case Mips::BI__builtin_msa_insve_w:
3155   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3156   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3157   // These intrinsics take an unsigned 1 bit immediate.
3158   case Mips::BI__builtin_msa_copy_s_d:
3159   case Mips::BI__builtin_msa_copy_u_d:
3160   case Mips::BI__builtin_msa_insve_d:
3161   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3162   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3163   // Memory offsets and immediate loads.
3164   // These intrinsics take a signed 10 bit immediate.
3165   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3166   case Mips::BI__builtin_msa_ldi_h:
3167   case Mips::BI__builtin_msa_ldi_w:
3168   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3169   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3170   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3171   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3172   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3173   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3174   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3175   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3176   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3177   }
3178 
3179   if (!m)
3180     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3181 
3182   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3183          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3184 }
3185 
3186 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3187   unsigned i = 0, l = 0, u = 0;
3188   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3189                       BuiltinID == PPC::BI__builtin_divdeu ||
3190                       BuiltinID == PPC::BI__builtin_bpermd;
3191   bool IsTarget64Bit = Context.getTargetInfo()
3192                               .getTypeWidth(Context
3193                                             .getTargetInfo()
3194                                             .getIntPtrType()) == 64;
3195   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3196                        BuiltinID == PPC::BI__builtin_divweu ||
3197                        BuiltinID == PPC::BI__builtin_divde ||
3198                        BuiltinID == PPC::BI__builtin_divdeu;
3199 
3200   if (Is64BitBltin && !IsTarget64Bit)
3201     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3202            << TheCall->getSourceRange();
3203 
3204   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3205       (BuiltinID == PPC::BI__builtin_bpermd &&
3206        !Context.getTargetInfo().hasFeature("bpermd")))
3207     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3208            << TheCall->getSourceRange();
3209 
3210   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3211     if (!Context.getTargetInfo().hasFeature("vsx"))
3212       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3213              << TheCall->getSourceRange();
3214     return false;
3215   };
3216 
3217   switch (BuiltinID) {
3218   default: return false;
3219   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3220   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3221     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3222            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3223   case PPC::BI__builtin_altivec_dss:
3224     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3225   case PPC::BI__builtin_tbegin:
3226   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3227   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3228   case PPC::BI__builtin_tabortwc:
3229   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3230   case PPC::BI__builtin_tabortwci:
3231   case PPC::BI__builtin_tabortdci:
3232     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3233            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3234   case PPC::BI__builtin_altivec_dst:
3235   case PPC::BI__builtin_altivec_dstt:
3236   case PPC::BI__builtin_altivec_dstst:
3237   case PPC::BI__builtin_altivec_dststt:
3238     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3239   case PPC::BI__builtin_vsx_xxpermdi:
3240   case PPC::BI__builtin_vsx_xxsldwi:
3241     return SemaBuiltinVSX(TheCall);
3242   case PPC::BI__builtin_unpack_vector_int128:
3243     return SemaVSXCheck(TheCall) ||
3244            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3245   case PPC::BI__builtin_pack_vector_int128:
3246     return SemaVSXCheck(TheCall);
3247   }
3248   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3249 }
3250 
3251 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3252                                            CallExpr *TheCall) {
3253   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3254     Expr *Arg = TheCall->getArg(0);
3255     llvm::APSInt AbortCode(32);
3256     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3257         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3258       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3259              << Arg->getSourceRange();
3260   }
3261 
3262   // For intrinsics which take an immediate value as part of the instruction,
3263   // range check them here.
3264   unsigned i = 0, l = 0, u = 0;
3265   switch (BuiltinID) {
3266   default: return false;
3267   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3268   case SystemZ::BI__builtin_s390_verimb:
3269   case SystemZ::BI__builtin_s390_verimh:
3270   case SystemZ::BI__builtin_s390_verimf:
3271   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3272   case SystemZ::BI__builtin_s390_vfaeb:
3273   case SystemZ::BI__builtin_s390_vfaeh:
3274   case SystemZ::BI__builtin_s390_vfaef:
3275   case SystemZ::BI__builtin_s390_vfaebs:
3276   case SystemZ::BI__builtin_s390_vfaehs:
3277   case SystemZ::BI__builtin_s390_vfaefs:
3278   case SystemZ::BI__builtin_s390_vfaezb:
3279   case SystemZ::BI__builtin_s390_vfaezh:
3280   case SystemZ::BI__builtin_s390_vfaezf:
3281   case SystemZ::BI__builtin_s390_vfaezbs:
3282   case SystemZ::BI__builtin_s390_vfaezhs:
3283   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3284   case SystemZ::BI__builtin_s390_vfisb:
3285   case SystemZ::BI__builtin_s390_vfidb:
3286     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3287            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3288   case SystemZ::BI__builtin_s390_vftcisb:
3289   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3290   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3291   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3292   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3293   case SystemZ::BI__builtin_s390_vstrcb:
3294   case SystemZ::BI__builtin_s390_vstrch:
3295   case SystemZ::BI__builtin_s390_vstrcf:
3296   case SystemZ::BI__builtin_s390_vstrczb:
3297   case SystemZ::BI__builtin_s390_vstrczh:
3298   case SystemZ::BI__builtin_s390_vstrczf:
3299   case SystemZ::BI__builtin_s390_vstrcbs:
3300   case SystemZ::BI__builtin_s390_vstrchs:
3301   case SystemZ::BI__builtin_s390_vstrcfs:
3302   case SystemZ::BI__builtin_s390_vstrczbs:
3303   case SystemZ::BI__builtin_s390_vstrczhs:
3304   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3305   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3306   case SystemZ::BI__builtin_s390_vfminsb:
3307   case SystemZ::BI__builtin_s390_vfmaxsb:
3308   case SystemZ::BI__builtin_s390_vfmindb:
3309   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3310   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3311   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3312   }
3313   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3314 }
3315 
3316 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3317 /// This checks that the target supports __builtin_cpu_supports and
3318 /// that the string argument is constant and valid.
3319 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3320   Expr *Arg = TheCall->getArg(0);
3321 
3322   // Check if the argument is a string literal.
3323   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3324     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3325            << Arg->getSourceRange();
3326 
3327   // Check the contents of the string.
3328   StringRef Feature =
3329       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3330   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3331     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3332            << Arg->getSourceRange();
3333   return false;
3334 }
3335 
3336 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3337 /// This checks that the target supports __builtin_cpu_is and
3338 /// that the string argument is constant and valid.
3339 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3340   Expr *Arg = TheCall->getArg(0);
3341 
3342   // Check if the argument is a string literal.
3343   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3344     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3345            << Arg->getSourceRange();
3346 
3347   // Check the contents of the string.
3348   StringRef Feature =
3349       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3350   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3351     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3352            << Arg->getSourceRange();
3353   return false;
3354 }
3355 
3356 // Check if the rounding mode is legal.
3357 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3358   // Indicates if this instruction has rounding control or just SAE.
3359   bool HasRC = false;
3360 
3361   unsigned ArgNum = 0;
3362   switch (BuiltinID) {
3363   default:
3364     return false;
3365   case X86::BI__builtin_ia32_vcvttsd2si32:
3366   case X86::BI__builtin_ia32_vcvttsd2si64:
3367   case X86::BI__builtin_ia32_vcvttsd2usi32:
3368   case X86::BI__builtin_ia32_vcvttsd2usi64:
3369   case X86::BI__builtin_ia32_vcvttss2si32:
3370   case X86::BI__builtin_ia32_vcvttss2si64:
3371   case X86::BI__builtin_ia32_vcvttss2usi32:
3372   case X86::BI__builtin_ia32_vcvttss2usi64:
3373     ArgNum = 1;
3374     break;
3375   case X86::BI__builtin_ia32_maxpd512:
3376   case X86::BI__builtin_ia32_maxps512:
3377   case X86::BI__builtin_ia32_minpd512:
3378   case X86::BI__builtin_ia32_minps512:
3379     ArgNum = 2;
3380     break;
3381   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3382   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3383   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3384   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3385   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3386   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3387   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3388   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3389   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3390   case X86::BI__builtin_ia32_exp2pd_mask:
3391   case X86::BI__builtin_ia32_exp2ps_mask:
3392   case X86::BI__builtin_ia32_getexppd512_mask:
3393   case X86::BI__builtin_ia32_getexpps512_mask:
3394   case X86::BI__builtin_ia32_rcp28pd_mask:
3395   case X86::BI__builtin_ia32_rcp28ps_mask:
3396   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3397   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3398   case X86::BI__builtin_ia32_vcomisd:
3399   case X86::BI__builtin_ia32_vcomiss:
3400   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3401     ArgNum = 3;
3402     break;
3403   case X86::BI__builtin_ia32_cmppd512_mask:
3404   case X86::BI__builtin_ia32_cmpps512_mask:
3405   case X86::BI__builtin_ia32_cmpsd_mask:
3406   case X86::BI__builtin_ia32_cmpss_mask:
3407   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3408   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3409   case X86::BI__builtin_ia32_getexpss128_round_mask:
3410   case X86::BI__builtin_ia32_getmantpd512_mask:
3411   case X86::BI__builtin_ia32_getmantps512_mask:
3412   case X86::BI__builtin_ia32_maxsd_round_mask:
3413   case X86::BI__builtin_ia32_maxss_round_mask:
3414   case X86::BI__builtin_ia32_minsd_round_mask:
3415   case X86::BI__builtin_ia32_minss_round_mask:
3416   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3417   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3418   case X86::BI__builtin_ia32_reducepd512_mask:
3419   case X86::BI__builtin_ia32_reduceps512_mask:
3420   case X86::BI__builtin_ia32_rndscalepd_mask:
3421   case X86::BI__builtin_ia32_rndscaleps_mask:
3422   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3423   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3424     ArgNum = 4;
3425     break;
3426   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3427   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3428   case X86::BI__builtin_ia32_fixupimmps512_mask:
3429   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3430   case X86::BI__builtin_ia32_fixupimmsd_mask:
3431   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3432   case X86::BI__builtin_ia32_fixupimmss_mask:
3433   case X86::BI__builtin_ia32_fixupimmss_maskz:
3434   case X86::BI__builtin_ia32_getmantsd_round_mask:
3435   case X86::BI__builtin_ia32_getmantss_round_mask:
3436   case X86::BI__builtin_ia32_rangepd512_mask:
3437   case X86::BI__builtin_ia32_rangeps512_mask:
3438   case X86::BI__builtin_ia32_rangesd128_round_mask:
3439   case X86::BI__builtin_ia32_rangess128_round_mask:
3440   case X86::BI__builtin_ia32_reducesd_mask:
3441   case X86::BI__builtin_ia32_reducess_mask:
3442   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3443   case X86::BI__builtin_ia32_rndscaless_round_mask:
3444     ArgNum = 5;
3445     break;
3446   case X86::BI__builtin_ia32_vcvtsd2si64:
3447   case X86::BI__builtin_ia32_vcvtsd2si32:
3448   case X86::BI__builtin_ia32_vcvtsd2usi32:
3449   case X86::BI__builtin_ia32_vcvtsd2usi64:
3450   case X86::BI__builtin_ia32_vcvtss2si32:
3451   case X86::BI__builtin_ia32_vcvtss2si64:
3452   case X86::BI__builtin_ia32_vcvtss2usi32:
3453   case X86::BI__builtin_ia32_vcvtss2usi64:
3454   case X86::BI__builtin_ia32_sqrtpd512:
3455   case X86::BI__builtin_ia32_sqrtps512:
3456     ArgNum = 1;
3457     HasRC = true;
3458     break;
3459   case X86::BI__builtin_ia32_addpd512:
3460   case X86::BI__builtin_ia32_addps512:
3461   case X86::BI__builtin_ia32_divpd512:
3462   case X86::BI__builtin_ia32_divps512:
3463   case X86::BI__builtin_ia32_mulpd512:
3464   case X86::BI__builtin_ia32_mulps512:
3465   case X86::BI__builtin_ia32_subpd512:
3466   case X86::BI__builtin_ia32_subps512:
3467   case X86::BI__builtin_ia32_cvtsi2sd64:
3468   case X86::BI__builtin_ia32_cvtsi2ss32:
3469   case X86::BI__builtin_ia32_cvtsi2ss64:
3470   case X86::BI__builtin_ia32_cvtusi2sd64:
3471   case X86::BI__builtin_ia32_cvtusi2ss32:
3472   case X86::BI__builtin_ia32_cvtusi2ss64:
3473     ArgNum = 2;
3474     HasRC = true;
3475     break;
3476   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3477   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3478   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3479   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3480   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3481   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3482   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3483   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3484   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3485   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3486   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3487   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3488   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3489   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3490   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3491     ArgNum = 3;
3492     HasRC = true;
3493     break;
3494   case X86::BI__builtin_ia32_addss_round_mask:
3495   case X86::BI__builtin_ia32_addsd_round_mask:
3496   case X86::BI__builtin_ia32_divss_round_mask:
3497   case X86::BI__builtin_ia32_divsd_round_mask:
3498   case X86::BI__builtin_ia32_mulss_round_mask:
3499   case X86::BI__builtin_ia32_mulsd_round_mask:
3500   case X86::BI__builtin_ia32_subss_round_mask:
3501   case X86::BI__builtin_ia32_subsd_round_mask:
3502   case X86::BI__builtin_ia32_scalefpd512_mask:
3503   case X86::BI__builtin_ia32_scalefps512_mask:
3504   case X86::BI__builtin_ia32_scalefsd_round_mask:
3505   case X86::BI__builtin_ia32_scalefss_round_mask:
3506   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3507   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3508   case X86::BI__builtin_ia32_sqrtss_round_mask:
3509   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3510   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3511   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3512   case X86::BI__builtin_ia32_vfmaddss3_mask:
3513   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3514   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3515   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3516   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3517   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3518   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3519   case X86::BI__builtin_ia32_vfmaddps512_mask:
3520   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3521   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3522   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3523   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3524   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3525   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3526   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3527   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3528   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3529   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3530   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3531     ArgNum = 4;
3532     HasRC = true;
3533     break;
3534   }
3535 
3536   llvm::APSInt Result;
3537 
3538   // We can't check the value of a dependent argument.
3539   Expr *Arg = TheCall->getArg(ArgNum);
3540   if (Arg->isTypeDependent() || Arg->isValueDependent())
3541     return false;
3542 
3543   // Check constant-ness first.
3544   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3545     return true;
3546 
3547   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3548   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3549   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3550   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3551   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3552       Result == 8/*ROUND_NO_EXC*/ ||
3553       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3554       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3555     return false;
3556 
3557   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3558          << Arg->getSourceRange();
3559 }
3560 
3561 // Check if the gather/scatter scale is legal.
3562 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3563                                              CallExpr *TheCall) {
3564   unsigned ArgNum = 0;
3565   switch (BuiltinID) {
3566   default:
3567     return false;
3568   case X86::BI__builtin_ia32_gatherpfdpd:
3569   case X86::BI__builtin_ia32_gatherpfdps:
3570   case X86::BI__builtin_ia32_gatherpfqpd:
3571   case X86::BI__builtin_ia32_gatherpfqps:
3572   case X86::BI__builtin_ia32_scatterpfdpd:
3573   case X86::BI__builtin_ia32_scatterpfdps:
3574   case X86::BI__builtin_ia32_scatterpfqpd:
3575   case X86::BI__builtin_ia32_scatterpfqps:
3576     ArgNum = 3;
3577     break;
3578   case X86::BI__builtin_ia32_gatherd_pd:
3579   case X86::BI__builtin_ia32_gatherd_pd256:
3580   case X86::BI__builtin_ia32_gatherq_pd:
3581   case X86::BI__builtin_ia32_gatherq_pd256:
3582   case X86::BI__builtin_ia32_gatherd_ps:
3583   case X86::BI__builtin_ia32_gatherd_ps256:
3584   case X86::BI__builtin_ia32_gatherq_ps:
3585   case X86::BI__builtin_ia32_gatherq_ps256:
3586   case X86::BI__builtin_ia32_gatherd_q:
3587   case X86::BI__builtin_ia32_gatherd_q256:
3588   case X86::BI__builtin_ia32_gatherq_q:
3589   case X86::BI__builtin_ia32_gatherq_q256:
3590   case X86::BI__builtin_ia32_gatherd_d:
3591   case X86::BI__builtin_ia32_gatherd_d256:
3592   case X86::BI__builtin_ia32_gatherq_d:
3593   case X86::BI__builtin_ia32_gatherq_d256:
3594   case X86::BI__builtin_ia32_gather3div2df:
3595   case X86::BI__builtin_ia32_gather3div2di:
3596   case X86::BI__builtin_ia32_gather3div4df:
3597   case X86::BI__builtin_ia32_gather3div4di:
3598   case X86::BI__builtin_ia32_gather3div4sf:
3599   case X86::BI__builtin_ia32_gather3div4si:
3600   case X86::BI__builtin_ia32_gather3div8sf:
3601   case X86::BI__builtin_ia32_gather3div8si:
3602   case X86::BI__builtin_ia32_gather3siv2df:
3603   case X86::BI__builtin_ia32_gather3siv2di:
3604   case X86::BI__builtin_ia32_gather3siv4df:
3605   case X86::BI__builtin_ia32_gather3siv4di:
3606   case X86::BI__builtin_ia32_gather3siv4sf:
3607   case X86::BI__builtin_ia32_gather3siv4si:
3608   case X86::BI__builtin_ia32_gather3siv8sf:
3609   case X86::BI__builtin_ia32_gather3siv8si:
3610   case X86::BI__builtin_ia32_gathersiv8df:
3611   case X86::BI__builtin_ia32_gathersiv16sf:
3612   case X86::BI__builtin_ia32_gatherdiv8df:
3613   case X86::BI__builtin_ia32_gatherdiv16sf:
3614   case X86::BI__builtin_ia32_gathersiv8di:
3615   case X86::BI__builtin_ia32_gathersiv16si:
3616   case X86::BI__builtin_ia32_gatherdiv8di:
3617   case X86::BI__builtin_ia32_gatherdiv16si:
3618   case X86::BI__builtin_ia32_scatterdiv2df:
3619   case X86::BI__builtin_ia32_scatterdiv2di:
3620   case X86::BI__builtin_ia32_scatterdiv4df:
3621   case X86::BI__builtin_ia32_scatterdiv4di:
3622   case X86::BI__builtin_ia32_scatterdiv4sf:
3623   case X86::BI__builtin_ia32_scatterdiv4si:
3624   case X86::BI__builtin_ia32_scatterdiv8sf:
3625   case X86::BI__builtin_ia32_scatterdiv8si:
3626   case X86::BI__builtin_ia32_scattersiv2df:
3627   case X86::BI__builtin_ia32_scattersiv2di:
3628   case X86::BI__builtin_ia32_scattersiv4df:
3629   case X86::BI__builtin_ia32_scattersiv4di:
3630   case X86::BI__builtin_ia32_scattersiv4sf:
3631   case X86::BI__builtin_ia32_scattersiv4si:
3632   case X86::BI__builtin_ia32_scattersiv8sf:
3633   case X86::BI__builtin_ia32_scattersiv8si:
3634   case X86::BI__builtin_ia32_scattersiv8df:
3635   case X86::BI__builtin_ia32_scattersiv16sf:
3636   case X86::BI__builtin_ia32_scatterdiv8df:
3637   case X86::BI__builtin_ia32_scatterdiv16sf:
3638   case X86::BI__builtin_ia32_scattersiv8di:
3639   case X86::BI__builtin_ia32_scattersiv16si:
3640   case X86::BI__builtin_ia32_scatterdiv8di:
3641   case X86::BI__builtin_ia32_scatterdiv16si:
3642     ArgNum = 4;
3643     break;
3644   }
3645 
3646   llvm::APSInt Result;
3647 
3648   // We can't check the value of a dependent argument.
3649   Expr *Arg = TheCall->getArg(ArgNum);
3650   if (Arg->isTypeDependent() || Arg->isValueDependent())
3651     return false;
3652 
3653   // Check constant-ness first.
3654   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3655     return true;
3656 
3657   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3658     return false;
3659 
3660   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3661          << Arg->getSourceRange();
3662 }
3663 
3664 static bool isX86_32Builtin(unsigned BuiltinID) {
3665   // These builtins only work on x86-32 targets.
3666   switch (BuiltinID) {
3667   case X86::BI__builtin_ia32_readeflags_u32:
3668   case X86::BI__builtin_ia32_writeeflags_u32:
3669     return true;
3670   }
3671 
3672   return false;
3673 }
3674 
3675 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3676   if (BuiltinID == X86::BI__builtin_cpu_supports)
3677     return SemaBuiltinCpuSupports(*this, TheCall);
3678 
3679   if (BuiltinID == X86::BI__builtin_cpu_is)
3680     return SemaBuiltinCpuIs(*this, TheCall);
3681 
3682   // Check for 32-bit only builtins on a 64-bit target.
3683   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3684   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3685     return Diag(TheCall->getCallee()->getBeginLoc(),
3686                 diag::err_32_bit_builtin_64_bit_tgt);
3687 
3688   // If the intrinsic has rounding or SAE make sure its valid.
3689   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3690     return true;
3691 
3692   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3693   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3694     return true;
3695 
3696   // For intrinsics which take an immediate value as part of the instruction,
3697   // range check them here.
3698   int i = 0, l = 0, u = 0;
3699   switch (BuiltinID) {
3700   default:
3701     return false;
3702   case X86::BI__builtin_ia32_vec_ext_v2si:
3703   case X86::BI__builtin_ia32_vec_ext_v2di:
3704   case X86::BI__builtin_ia32_vextractf128_pd256:
3705   case X86::BI__builtin_ia32_vextractf128_ps256:
3706   case X86::BI__builtin_ia32_vextractf128_si256:
3707   case X86::BI__builtin_ia32_extract128i256:
3708   case X86::BI__builtin_ia32_extractf64x4_mask:
3709   case X86::BI__builtin_ia32_extracti64x4_mask:
3710   case X86::BI__builtin_ia32_extractf32x8_mask:
3711   case X86::BI__builtin_ia32_extracti32x8_mask:
3712   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3713   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3714   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3715   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3716     i = 1; l = 0; u = 1;
3717     break;
3718   case X86::BI__builtin_ia32_vec_set_v2di:
3719   case X86::BI__builtin_ia32_vinsertf128_pd256:
3720   case X86::BI__builtin_ia32_vinsertf128_ps256:
3721   case X86::BI__builtin_ia32_vinsertf128_si256:
3722   case X86::BI__builtin_ia32_insert128i256:
3723   case X86::BI__builtin_ia32_insertf32x8:
3724   case X86::BI__builtin_ia32_inserti32x8:
3725   case X86::BI__builtin_ia32_insertf64x4:
3726   case X86::BI__builtin_ia32_inserti64x4:
3727   case X86::BI__builtin_ia32_insertf64x2_256:
3728   case X86::BI__builtin_ia32_inserti64x2_256:
3729   case X86::BI__builtin_ia32_insertf32x4_256:
3730   case X86::BI__builtin_ia32_inserti32x4_256:
3731     i = 2; l = 0; u = 1;
3732     break;
3733   case X86::BI__builtin_ia32_vpermilpd:
3734   case X86::BI__builtin_ia32_vec_ext_v4hi:
3735   case X86::BI__builtin_ia32_vec_ext_v4si:
3736   case X86::BI__builtin_ia32_vec_ext_v4sf:
3737   case X86::BI__builtin_ia32_vec_ext_v4di:
3738   case X86::BI__builtin_ia32_extractf32x4_mask:
3739   case X86::BI__builtin_ia32_extracti32x4_mask:
3740   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3741   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3742     i = 1; l = 0; u = 3;
3743     break;
3744   case X86::BI_mm_prefetch:
3745   case X86::BI__builtin_ia32_vec_ext_v8hi:
3746   case X86::BI__builtin_ia32_vec_ext_v8si:
3747     i = 1; l = 0; u = 7;
3748     break;
3749   case X86::BI__builtin_ia32_sha1rnds4:
3750   case X86::BI__builtin_ia32_blendpd:
3751   case X86::BI__builtin_ia32_shufpd:
3752   case X86::BI__builtin_ia32_vec_set_v4hi:
3753   case X86::BI__builtin_ia32_vec_set_v4si:
3754   case X86::BI__builtin_ia32_vec_set_v4di:
3755   case X86::BI__builtin_ia32_shuf_f32x4_256:
3756   case X86::BI__builtin_ia32_shuf_f64x2_256:
3757   case X86::BI__builtin_ia32_shuf_i32x4_256:
3758   case X86::BI__builtin_ia32_shuf_i64x2_256:
3759   case X86::BI__builtin_ia32_insertf64x2_512:
3760   case X86::BI__builtin_ia32_inserti64x2_512:
3761   case X86::BI__builtin_ia32_insertf32x4:
3762   case X86::BI__builtin_ia32_inserti32x4:
3763     i = 2; l = 0; u = 3;
3764     break;
3765   case X86::BI__builtin_ia32_vpermil2pd:
3766   case X86::BI__builtin_ia32_vpermil2pd256:
3767   case X86::BI__builtin_ia32_vpermil2ps:
3768   case X86::BI__builtin_ia32_vpermil2ps256:
3769     i = 3; l = 0; u = 3;
3770     break;
3771   case X86::BI__builtin_ia32_cmpb128_mask:
3772   case X86::BI__builtin_ia32_cmpw128_mask:
3773   case X86::BI__builtin_ia32_cmpd128_mask:
3774   case X86::BI__builtin_ia32_cmpq128_mask:
3775   case X86::BI__builtin_ia32_cmpb256_mask:
3776   case X86::BI__builtin_ia32_cmpw256_mask:
3777   case X86::BI__builtin_ia32_cmpd256_mask:
3778   case X86::BI__builtin_ia32_cmpq256_mask:
3779   case X86::BI__builtin_ia32_cmpb512_mask:
3780   case X86::BI__builtin_ia32_cmpw512_mask:
3781   case X86::BI__builtin_ia32_cmpd512_mask:
3782   case X86::BI__builtin_ia32_cmpq512_mask:
3783   case X86::BI__builtin_ia32_ucmpb128_mask:
3784   case X86::BI__builtin_ia32_ucmpw128_mask:
3785   case X86::BI__builtin_ia32_ucmpd128_mask:
3786   case X86::BI__builtin_ia32_ucmpq128_mask:
3787   case X86::BI__builtin_ia32_ucmpb256_mask:
3788   case X86::BI__builtin_ia32_ucmpw256_mask:
3789   case X86::BI__builtin_ia32_ucmpd256_mask:
3790   case X86::BI__builtin_ia32_ucmpq256_mask:
3791   case X86::BI__builtin_ia32_ucmpb512_mask:
3792   case X86::BI__builtin_ia32_ucmpw512_mask:
3793   case X86::BI__builtin_ia32_ucmpd512_mask:
3794   case X86::BI__builtin_ia32_ucmpq512_mask:
3795   case X86::BI__builtin_ia32_vpcomub:
3796   case X86::BI__builtin_ia32_vpcomuw:
3797   case X86::BI__builtin_ia32_vpcomud:
3798   case X86::BI__builtin_ia32_vpcomuq:
3799   case X86::BI__builtin_ia32_vpcomb:
3800   case X86::BI__builtin_ia32_vpcomw:
3801   case X86::BI__builtin_ia32_vpcomd:
3802   case X86::BI__builtin_ia32_vpcomq:
3803   case X86::BI__builtin_ia32_vec_set_v8hi:
3804   case X86::BI__builtin_ia32_vec_set_v8si:
3805     i = 2; l = 0; u = 7;
3806     break;
3807   case X86::BI__builtin_ia32_vpermilpd256:
3808   case X86::BI__builtin_ia32_roundps:
3809   case X86::BI__builtin_ia32_roundpd:
3810   case X86::BI__builtin_ia32_roundps256:
3811   case X86::BI__builtin_ia32_roundpd256:
3812   case X86::BI__builtin_ia32_getmantpd128_mask:
3813   case X86::BI__builtin_ia32_getmantpd256_mask:
3814   case X86::BI__builtin_ia32_getmantps128_mask:
3815   case X86::BI__builtin_ia32_getmantps256_mask:
3816   case X86::BI__builtin_ia32_getmantpd512_mask:
3817   case X86::BI__builtin_ia32_getmantps512_mask:
3818   case X86::BI__builtin_ia32_vec_ext_v16qi:
3819   case X86::BI__builtin_ia32_vec_ext_v16hi:
3820     i = 1; l = 0; u = 15;
3821     break;
3822   case X86::BI__builtin_ia32_pblendd128:
3823   case X86::BI__builtin_ia32_blendps:
3824   case X86::BI__builtin_ia32_blendpd256:
3825   case X86::BI__builtin_ia32_shufpd256:
3826   case X86::BI__builtin_ia32_roundss:
3827   case X86::BI__builtin_ia32_roundsd:
3828   case X86::BI__builtin_ia32_rangepd128_mask:
3829   case X86::BI__builtin_ia32_rangepd256_mask:
3830   case X86::BI__builtin_ia32_rangepd512_mask:
3831   case X86::BI__builtin_ia32_rangeps128_mask:
3832   case X86::BI__builtin_ia32_rangeps256_mask:
3833   case X86::BI__builtin_ia32_rangeps512_mask:
3834   case X86::BI__builtin_ia32_getmantsd_round_mask:
3835   case X86::BI__builtin_ia32_getmantss_round_mask:
3836   case X86::BI__builtin_ia32_vec_set_v16qi:
3837   case X86::BI__builtin_ia32_vec_set_v16hi:
3838     i = 2; l = 0; u = 15;
3839     break;
3840   case X86::BI__builtin_ia32_vec_ext_v32qi:
3841     i = 1; l = 0; u = 31;
3842     break;
3843   case X86::BI__builtin_ia32_cmpps:
3844   case X86::BI__builtin_ia32_cmpss:
3845   case X86::BI__builtin_ia32_cmppd:
3846   case X86::BI__builtin_ia32_cmpsd:
3847   case X86::BI__builtin_ia32_cmpps256:
3848   case X86::BI__builtin_ia32_cmppd256:
3849   case X86::BI__builtin_ia32_cmpps128_mask:
3850   case X86::BI__builtin_ia32_cmppd128_mask:
3851   case X86::BI__builtin_ia32_cmpps256_mask:
3852   case X86::BI__builtin_ia32_cmppd256_mask:
3853   case X86::BI__builtin_ia32_cmpps512_mask:
3854   case X86::BI__builtin_ia32_cmppd512_mask:
3855   case X86::BI__builtin_ia32_cmpsd_mask:
3856   case X86::BI__builtin_ia32_cmpss_mask:
3857   case X86::BI__builtin_ia32_vec_set_v32qi:
3858     i = 2; l = 0; u = 31;
3859     break;
3860   case X86::BI__builtin_ia32_permdf256:
3861   case X86::BI__builtin_ia32_permdi256:
3862   case X86::BI__builtin_ia32_permdf512:
3863   case X86::BI__builtin_ia32_permdi512:
3864   case X86::BI__builtin_ia32_vpermilps:
3865   case X86::BI__builtin_ia32_vpermilps256:
3866   case X86::BI__builtin_ia32_vpermilpd512:
3867   case X86::BI__builtin_ia32_vpermilps512:
3868   case X86::BI__builtin_ia32_pshufd:
3869   case X86::BI__builtin_ia32_pshufd256:
3870   case X86::BI__builtin_ia32_pshufd512:
3871   case X86::BI__builtin_ia32_pshufhw:
3872   case X86::BI__builtin_ia32_pshufhw256:
3873   case X86::BI__builtin_ia32_pshufhw512:
3874   case X86::BI__builtin_ia32_pshuflw:
3875   case X86::BI__builtin_ia32_pshuflw256:
3876   case X86::BI__builtin_ia32_pshuflw512:
3877   case X86::BI__builtin_ia32_vcvtps2ph:
3878   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3879   case X86::BI__builtin_ia32_vcvtps2ph256:
3880   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3881   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3882   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3883   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3884   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3885   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3886   case X86::BI__builtin_ia32_rndscaleps_mask:
3887   case X86::BI__builtin_ia32_rndscalepd_mask:
3888   case X86::BI__builtin_ia32_reducepd128_mask:
3889   case X86::BI__builtin_ia32_reducepd256_mask:
3890   case X86::BI__builtin_ia32_reducepd512_mask:
3891   case X86::BI__builtin_ia32_reduceps128_mask:
3892   case X86::BI__builtin_ia32_reduceps256_mask:
3893   case X86::BI__builtin_ia32_reduceps512_mask:
3894   case X86::BI__builtin_ia32_prold512:
3895   case X86::BI__builtin_ia32_prolq512:
3896   case X86::BI__builtin_ia32_prold128:
3897   case X86::BI__builtin_ia32_prold256:
3898   case X86::BI__builtin_ia32_prolq128:
3899   case X86::BI__builtin_ia32_prolq256:
3900   case X86::BI__builtin_ia32_prord512:
3901   case X86::BI__builtin_ia32_prorq512:
3902   case X86::BI__builtin_ia32_prord128:
3903   case X86::BI__builtin_ia32_prord256:
3904   case X86::BI__builtin_ia32_prorq128:
3905   case X86::BI__builtin_ia32_prorq256:
3906   case X86::BI__builtin_ia32_fpclasspd128_mask:
3907   case X86::BI__builtin_ia32_fpclasspd256_mask:
3908   case X86::BI__builtin_ia32_fpclassps128_mask:
3909   case X86::BI__builtin_ia32_fpclassps256_mask:
3910   case X86::BI__builtin_ia32_fpclassps512_mask:
3911   case X86::BI__builtin_ia32_fpclasspd512_mask:
3912   case X86::BI__builtin_ia32_fpclasssd_mask:
3913   case X86::BI__builtin_ia32_fpclassss_mask:
3914   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3915   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3916   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3917   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3918   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3919   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3920   case X86::BI__builtin_ia32_kshiftliqi:
3921   case X86::BI__builtin_ia32_kshiftlihi:
3922   case X86::BI__builtin_ia32_kshiftlisi:
3923   case X86::BI__builtin_ia32_kshiftlidi:
3924   case X86::BI__builtin_ia32_kshiftriqi:
3925   case X86::BI__builtin_ia32_kshiftrihi:
3926   case X86::BI__builtin_ia32_kshiftrisi:
3927   case X86::BI__builtin_ia32_kshiftridi:
3928     i = 1; l = 0; u = 255;
3929     break;
3930   case X86::BI__builtin_ia32_vperm2f128_pd256:
3931   case X86::BI__builtin_ia32_vperm2f128_ps256:
3932   case X86::BI__builtin_ia32_vperm2f128_si256:
3933   case X86::BI__builtin_ia32_permti256:
3934   case X86::BI__builtin_ia32_pblendw128:
3935   case X86::BI__builtin_ia32_pblendw256:
3936   case X86::BI__builtin_ia32_blendps256:
3937   case X86::BI__builtin_ia32_pblendd256:
3938   case X86::BI__builtin_ia32_palignr128:
3939   case X86::BI__builtin_ia32_palignr256:
3940   case X86::BI__builtin_ia32_palignr512:
3941   case X86::BI__builtin_ia32_alignq512:
3942   case X86::BI__builtin_ia32_alignd512:
3943   case X86::BI__builtin_ia32_alignd128:
3944   case X86::BI__builtin_ia32_alignd256:
3945   case X86::BI__builtin_ia32_alignq128:
3946   case X86::BI__builtin_ia32_alignq256:
3947   case X86::BI__builtin_ia32_vcomisd:
3948   case X86::BI__builtin_ia32_vcomiss:
3949   case X86::BI__builtin_ia32_shuf_f32x4:
3950   case X86::BI__builtin_ia32_shuf_f64x2:
3951   case X86::BI__builtin_ia32_shuf_i32x4:
3952   case X86::BI__builtin_ia32_shuf_i64x2:
3953   case X86::BI__builtin_ia32_shufpd512:
3954   case X86::BI__builtin_ia32_shufps:
3955   case X86::BI__builtin_ia32_shufps256:
3956   case X86::BI__builtin_ia32_shufps512:
3957   case X86::BI__builtin_ia32_dbpsadbw128:
3958   case X86::BI__builtin_ia32_dbpsadbw256:
3959   case X86::BI__builtin_ia32_dbpsadbw512:
3960   case X86::BI__builtin_ia32_vpshldd128:
3961   case X86::BI__builtin_ia32_vpshldd256:
3962   case X86::BI__builtin_ia32_vpshldd512:
3963   case X86::BI__builtin_ia32_vpshldq128:
3964   case X86::BI__builtin_ia32_vpshldq256:
3965   case X86::BI__builtin_ia32_vpshldq512:
3966   case X86::BI__builtin_ia32_vpshldw128:
3967   case X86::BI__builtin_ia32_vpshldw256:
3968   case X86::BI__builtin_ia32_vpshldw512:
3969   case X86::BI__builtin_ia32_vpshrdd128:
3970   case X86::BI__builtin_ia32_vpshrdd256:
3971   case X86::BI__builtin_ia32_vpshrdd512:
3972   case X86::BI__builtin_ia32_vpshrdq128:
3973   case X86::BI__builtin_ia32_vpshrdq256:
3974   case X86::BI__builtin_ia32_vpshrdq512:
3975   case X86::BI__builtin_ia32_vpshrdw128:
3976   case X86::BI__builtin_ia32_vpshrdw256:
3977   case X86::BI__builtin_ia32_vpshrdw512:
3978     i = 2; l = 0; u = 255;
3979     break;
3980   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3981   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3982   case X86::BI__builtin_ia32_fixupimmps512_mask:
3983   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3984   case X86::BI__builtin_ia32_fixupimmsd_mask:
3985   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3986   case X86::BI__builtin_ia32_fixupimmss_mask:
3987   case X86::BI__builtin_ia32_fixupimmss_maskz:
3988   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3989   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3990   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3991   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3992   case X86::BI__builtin_ia32_fixupimmps128_mask:
3993   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3994   case X86::BI__builtin_ia32_fixupimmps256_mask:
3995   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3996   case X86::BI__builtin_ia32_pternlogd512_mask:
3997   case X86::BI__builtin_ia32_pternlogd512_maskz:
3998   case X86::BI__builtin_ia32_pternlogq512_mask:
3999   case X86::BI__builtin_ia32_pternlogq512_maskz:
4000   case X86::BI__builtin_ia32_pternlogd128_mask:
4001   case X86::BI__builtin_ia32_pternlogd128_maskz:
4002   case X86::BI__builtin_ia32_pternlogd256_mask:
4003   case X86::BI__builtin_ia32_pternlogd256_maskz:
4004   case X86::BI__builtin_ia32_pternlogq128_mask:
4005   case X86::BI__builtin_ia32_pternlogq128_maskz:
4006   case X86::BI__builtin_ia32_pternlogq256_mask:
4007   case X86::BI__builtin_ia32_pternlogq256_maskz:
4008     i = 3; l = 0; u = 255;
4009     break;
4010   case X86::BI__builtin_ia32_gatherpfdpd:
4011   case X86::BI__builtin_ia32_gatherpfdps:
4012   case X86::BI__builtin_ia32_gatherpfqpd:
4013   case X86::BI__builtin_ia32_gatherpfqps:
4014   case X86::BI__builtin_ia32_scatterpfdpd:
4015   case X86::BI__builtin_ia32_scatterpfdps:
4016   case X86::BI__builtin_ia32_scatterpfqpd:
4017   case X86::BI__builtin_ia32_scatterpfqps:
4018     i = 4; l = 2; u = 3;
4019     break;
4020   case X86::BI__builtin_ia32_reducesd_mask:
4021   case X86::BI__builtin_ia32_reducess_mask:
4022   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4023   case X86::BI__builtin_ia32_rndscaless_round_mask:
4024     i = 4; l = 0; u = 255;
4025     break;
4026   }
4027 
4028   // Note that we don't force a hard error on the range check here, allowing
4029   // template-generated or macro-generated dead code to potentially have out-of-
4030   // range values. These need to code generate, but don't need to necessarily
4031   // make any sense. We use a warning that defaults to an error.
4032   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4033 }
4034 
4035 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4036 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4037 /// Returns true when the format fits the function and the FormatStringInfo has
4038 /// been populated.
4039 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4040                                FormatStringInfo *FSI) {
4041   FSI->HasVAListArg = Format->getFirstArg() == 0;
4042   FSI->FormatIdx = Format->getFormatIdx() - 1;
4043   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4044 
4045   // The way the format attribute works in GCC, the implicit this argument
4046   // of member functions is counted. However, it doesn't appear in our own
4047   // lists, so decrement format_idx in that case.
4048   if (IsCXXMember) {
4049     if(FSI->FormatIdx == 0)
4050       return false;
4051     --FSI->FormatIdx;
4052     if (FSI->FirstDataArg != 0)
4053       --FSI->FirstDataArg;
4054   }
4055   return true;
4056 }
4057 
4058 /// Checks if a the given expression evaluates to null.
4059 ///
4060 /// Returns true if the value evaluates to null.
4061 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4062   // If the expression has non-null type, it doesn't evaluate to null.
4063   if (auto nullability
4064         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4065     if (*nullability == NullabilityKind::NonNull)
4066       return false;
4067   }
4068 
4069   // As a special case, transparent unions initialized with zero are
4070   // considered null for the purposes of the nonnull attribute.
4071   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4072     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4073       if (const CompoundLiteralExpr *CLE =
4074           dyn_cast<CompoundLiteralExpr>(Expr))
4075         if (const InitListExpr *ILE =
4076             dyn_cast<InitListExpr>(CLE->getInitializer()))
4077           Expr = ILE->getInit(0);
4078   }
4079 
4080   bool Result;
4081   return (!Expr->isValueDependent() &&
4082           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4083           !Result);
4084 }
4085 
4086 static void CheckNonNullArgument(Sema &S,
4087                                  const Expr *ArgExpr,
4088                                  SourceLocation CallSiteLoc) {
4089   if (CheckNonNullExpr(S, ArgExpr))
4090     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4091                           S.PDiag(diag::warn_null_arg)
4092                               << ArgExpr->getSourceRange());
4093 }
4094 
4095 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4096   FormatStringInfo FSI;
4097   if ((GetFormatStringType(Format) == FST_NSString) &&
4098       getFormatStringInfo(Format, false, &FSI)) {
4099     Idx = FSI.FormatIdx;
4100     return true;
4101   }
4102   return false;
4103 }
4104 
4105 /// Diagnose use of %s directive in an NSString which is being passed
4106 /// as formatting string to formatting method.
4107 static void
4108 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4109                                         const NamedDecl *FDecl,
4110                                         Expr **Args,
4111                                         unsigned NumArgs) {
4112   unsigned Idx = 0;
4113   bool Format = false;
4114   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4115   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4116     Idx = 2;
4117     Format = true;
4118   }
4119   else
4120     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4121       if (S.GetFormatNSStringIdx(I, Idx)) {
4122         Format = true;
4123         break;
4124       }
4125     }
4126   if (!Format || NumArgs <= Idx)
4127     return;
4128   const Expr *FormatExpr = Args[Idx];
4129   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4130     FormatExpr = CSCE->getSubExpr();
4131   const StringLiteral *FormatString;
4132   if (const ObjCStringLiteral *OSL =
4133       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4134     FormatString = OSL->getString();
4135   else
4136     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4137   if (!FormatString)
4138     return;
4139   if (S.FormatStringHasSArg(FormatString)) {
4140     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4141       << "%s" << 1 << 1;
4142     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4143       << FDecl->getDeclName();
4144   }
4145 }
4146 
4147 /// Determine whether the given type has a non-null nullability annotation.
4148 static bool isNonNullType(ASTContext &ctx, QualType type) {
4149   if (auto nullability = type->getNullability(ctx))
4150     return *nullability == NullabilityKind::NonNull;
4151 
4152   return false;
4153 }
4154 
4155 static void CheckNonNullArguments(Sema &S,
4156                                   const NamedDecl *FDecl,
4157                                   const FunctionProtoType *Proto,
4158                                   ArrayRef<const Expr *> Args,
4159                                   SourceLocation CallSiteLoc) {
4160   assert((FDecl || Proto) && "Need a function declaration or prototype");
4161 
4162   // Already checked by by constant evaluator.
4163   if (S.isConstantEvaluated())
4164     return;
4165   // Check the attributes attached to the method/function itself.
4166   llvm::SmallBitVector NonNullArgs;
4167   if (FDecl) {
4168     // Handle the nonnull attribute on the function/method declaration itself.
4169     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4170       if (!NonNull->args_size()) {
4171         // Easy case: all pointer arguments are nonnull.
4172         for (const auto *Arg : Args)
4173           if (S.isValidPointerAttrType(Arg->getType()))
4174             CheckNonNullArgument(S, Arg, CallSiteLoc);
4175         return;
4176       }
4177 
4178       for (const ParamIdx &Idx : NonNull->args()) {
4179         unsigned IdxAST = Idx.getASTIndex();
4180         if (IdxAST >= Args.size())
4181           continue;
4182         if (NonNullArgs.empty())
4183           NonNullArgs.resize(Args.size());
4184         NonNullArgs.set(IdxAST);
4185       }
4186     }
4187   }
4188 
4189   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4190     // Handle the nonnull attribute on the parameters of the
4191     // function/method.
4192     ArrayRef<ParmVarDecl*> parms;
4193     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4194       parms = FD->parameters();
4195     else
4196       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4197 
4198     unsigned ParamIndex = 0;
4199     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4200          I != E; ++I, ++ParamIndex) {
4201       const ParmVarDecl *PVD = *I;
4202       if (PVD->hasAttr<NonNullAttr>() ||
4203           isNonNullType(S.Context, PVD->getType())) {
4204         if (NonNullArgs.empty())
4205           NonNullArgs.resize(Args.size());
4206 
4207         NonNullArgs.set(ParamIndex);
4208       }
4209     }
4210   } else {
4211     // If we have a non-function, non-method declaration but no
4212     // function prototype, try to dig out the function prototype.
4213     if (!Proto) {
4214       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4215         QualType type = VD->getType().getNonReferenceType();
4216         if (auto pointerType = type->getAs<PointerType>())
4217           type = pointerType->getPointeeType();
4218         else if (auto blockType = type->getAs<BlockPointerType>())
4219           type = blockType->getPointeeType();
4220         // FIXME: data member pointers?
4221 
4222         // Dig out the function prototype, if there is one.
4223         Proto = type->getAs<FunctionProtoType>();
4224       }
4225     }
4226 
4227     // Fill in non-null argument information from the nullability
4228     // information on the parameter types (if we have them).
4229     if (Proto) {
4230       unsigned Index = 0;
4231       for (auto paramType : Proto->getParamTypes()) {
4232         if (isNonNullType(S.Context, paramType)) {
4233           if (NonNullArgs.empty())
4234             NonNullArgs.resize(Args.size());
4235 
4236           NonNullArgs.set(Index);
4237         }
4238 
4239         ++Index;
4240       }
4241     }
4242   }
4243 
4244   // Check for non-null arguments.
4245   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4246        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4247     if (NonNullArgs[ArgIndex])
4248       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4249   }
4250 }
4251 
4252 /// Handles the checks for format strings, non-POD arguments to vararg
4253 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4254 /// attributes.
4255 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4256                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4257                      bool IsMemberFunction, SourceLocation Loc,
4258                      SourceRange Range, VariadicCallType CallType) {
4259   // FIXME: We should check as much as we can in the template definition.
4260   if (CurContext->isDependentContext())
4261     return;
4262 
4263   // Printf and scanf checking.
4264   llvm::SmallBitVector CheckedVarArgs;
4265   if (FDecl) {
4266     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4267       // Only create vector if there are format attributes.
4268       CheckedVarArgs.resize(Args.size());
4269 
4270       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4271                            CheckedVarArgs);
4272     }
4273   }
4274 
4275   // Refuse POD arguments that weren't caught by the format string
4276   // checks above.
4277   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4278   if (CallType != VariadicDoesNotApply &&
4279       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4280     unsigned NumParams = Proto ? Proto->getNumParams()
4281                        : FDecl && isa<FunctionDecl>(FDecl)
4282                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4283                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4284                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4285                        : 0;
4286 
4287     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4288       // Args[ArgIdx] can be null in malformed code.
4289       if (const Expr *Arg = Args[ArgIdx]) {
4290         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4291           checkVariadicArgument(Arg, CallType);
4292       }
4293     }
4294   }
4295 
4296   if (FDecl || Proto) {
4297     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4298 
4299     // Type safety checking.
4300     if (FDecl) {
4301       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4302         CheckArgumentWithTypeTag(I, Args, Loc);
4303     }
4304   }
4305 
4306   if (FD)
4307     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4308 }
4309 
4310 /// CheckConstructorCall - Check a constructor call for correctness and safety
4311 /// properties not enforced by the C type system.
4312 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4313                                 ArrayRef<const Expr *> Args,
4314                                 const FunctionProtoType *Proto,
4315                                 SourceLocation Loc) {
4316   VariadicCallType CallType =
4317     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4318   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4319             Loc, SourceRange(), CallType);
4320 }
4321 
4322 /// CheckFunctionCall - Check a direct function call for various correctness
4323 /// and safety properties not strictly enforced by the C type system.
4324 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4325                              const FunctionProtoType *Proto) {
4326   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4327                               isa<CXXMethodDecl>(FDecl);
4328   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4329                           IsMemberOperatorCall;
4330   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4331                                                   TheCall->getCallee());
4332   Expr** Args = TheCall->getArgs();
4333   unsigned NumArgs = TheCall->getNumArgs();
4334 
4335   Expr *ImplicitThis = nullptr;
4336   if (IsMemberOperatorCall) {
4337     // If this is a call to a member operator, hide the first argument
4338     // from checkCall.
4339     // FIXME: Our choice of AST representation here is less than ideal.
4340     ImplicitThis = Args[0];
4341     ++Args;
4342     --NumArgs;
4343   } else if (IsMemberFunction)
4344     ImplicitThis =
4345         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4346 
4347   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4348             IsMemberFunction, TheCall->getRParenLoc(),
4349             TheCall->getCallee()->getSourceRange(), CallType);
4350 
4351   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4352   // None of the checks below are needed for functions that don't have
4353   // simple names (e.g., C++ conversion functions).
4354   if (!FnInfo)
4355     return false;
4356 
4357   CheckAbsoluteValueFunction(TheCall, FDecl);
4358   CheckMaxUnsignedZero(TheCall, FDecl);
4359 
4360   if (getLangOpts().ObjC)
4361     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4362 
4363   unsigned CMId = FDecl->getMemoryFunctionKind();
4364   if (CMId == 0)
4365     return false;
4366 
4367   // Handle memory setting and copying functions.
4368   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4369     CheckStrlcpycatArguments(TheCall, FnInfo);
4370   else if (CMId == Builtin::BIstrncat)
4371     CheckStrncatArguments(TheCall, FnInfo);
4372   else
4373     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4374 
4375   return false;
4376 }
4377 
4378 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4379                                ArrayRef<const Expr *> Args) {
4380   VariadicCallType CallType =
4381       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4382 
4383   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4384             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4385             CallType);
4386 
4387   return false;
4388 }
4389 
4390 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4391                             const FunctionProtoType *Proto) {
4392   QualType Ty;
4393   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4394     Ty = V->getType().getNonReferenceType();
4395   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4396     Ty = F->getType().getNonReferenceType();
4397   else
4398     return false;
4399 
4400   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4401       !Ty->isFunctionProtoType())
4402     return false;
4403 
4404   VariadicCallType CallType;
4405   if (!Proto || !Proto->isVariadic()) {
4406     CallType = VariadicDoesNotApply;
4407   } else if (Ty->isBlockPointerType()) {
4408     CallType = VariadicBlock;
4409   } else { // Ty->isFunctionPointerType()
4410     CallType = VariadicFunction;
4411   }
4412 
4413   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4414             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4415             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4416             TheCall->getCallee()->getSourceRange(), CallType);
4417 
4418   return false;
4419 }
4420 
4421 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4422 /// such as function pointers returned from functions.
4423 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4424   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4425                                                   TheCall->getCallee());
4426   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4427             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4428             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4429             TheCall->getCallee()->getSourceRange(), CallType);
4430 
4431   return false;
4432 }
4433 
4434 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4435   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4436     return false;
4437 
4438   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4439   switch (Op) {
4440   case AtomicExpr::AO__c11_atomic_init:
4441   case AtomicExpr::AO__opencl_atomic_init:
4442     llvm_unreachable("There is no ordering argument for an init");
4443 
4444   case AtomicExpr::AO__c11_atomic_load:
4445   case AtomicExpr::AO__opencl_atomic_load:
4446   case AtomicExpr::AO__atomic_load_n:
4447   case AtomicExpr::AO__atomic_load:
4448     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4449            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4450 
4451   case AtomicExpr::AO__c11_atomic_store:
4452   case AtomicExpr::AO__opencl_atomic_store:
4453   case AtomicExpr::AO__atomic_store:
4454   case AtomicExpr::AO__atomic_store_n:
4455     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4456            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4457            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4458 
4459   default:
4460     return true;
4461   }
4462 }
4463 
4464 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4465                                          AtomicExpr::AtomicOp Op) {
4466   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4467   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4468   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4469   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4470                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4471                          Op);
4472 }
4473 
4474 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4475                                  SourceLocation RParenLoc, MultiExprArg Args,
4476                                  AtomicExpr::AtomicOp Op,
4477                                  AtomicArgumentOrder ArgOrder) {
4478   // All the non-OpenCL operations take one of the following forms.
4479   // The OpenCL operations take the __c11 forms with one extra argument for
4480   // synchronization scope.
4481   enum {
4482     // C    __c11_atomic_init(A *, C)
4483     Init,
4484 
4485     // C    __c11_atomic_load(A *, int)
4486     Load,
4487 
4488     // void __atomic_load(A *, CP, int)
4489     LoadCopy,
4490 
4491     // void __atomic_store(A *, CP, int)
4492     Copy,
4493 
4494     // C    __c11_atomic_add(A *, M, int)
4495     Arithmetic,
4496 
4497     // C    __atomic_exchange_n(A *, CP, int)
4498     Xchg,
4499 
4500     // void __atomic_exchange(A *, C *, CP, int)
4501     GNUXchg,
4502 
4503     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4504     C11CmpXchg,
4505 
4506     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4507     GNUCmpXchg
4508   } Form = Init;
4509 
4510   const unsigned NumForm = GNUCmpXchg + 1;
4511   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4512   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4513   // where:
4514   //   C is an appropriate type,
4515   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4516   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4517   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4518   //   the int parameters are for orderings.
4519 
4520   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4521       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4522       "need to update code for modified forms");
4523   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4524                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4525                         AtomicExpr::AO__atomic_load,
4526                 "need to update code for modified C11 atomics");
4527   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4528                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4529   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4530                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4531                IsOpenCL;
4532   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4533              Op == AtomicExpr::AO__atomic_store_n ||
4534              Op == AtomicExpr::AO__atomic_exchange_n ||
4535              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4536   bool IsAddSub = false;
4537   bool IsMinMax = false;
4538 
4539   switch (Op) {
4540   case AtomicExpr::AO__c11_atomic_init:
4541   case AtomicExpr::AO__opencl_atomic_init:
4542     Form = Init;
4543     break;
4544 
4545   case AtomicExpr::AO__c11_atomic_load:
4546   case AtomicExpr::AO__opencl_atomic_load:
4547   case AtomicExpr::AO__atomic_load_n:
4548     Form = Load;
4549     break;
4550 
4551   case AtomicExpr::AO__atomic_load:
4552     Form = LoadCopy;
4553     break;
4554 
4555   case AtomicExpr::AO__c11_atomic_store:
4556   case AtomicExpr::AO__opencl_atomic_store:
4557   case AtomicExpr::AO__atomic_store:
4558   case AtomicExpr::AO__atomic_store_n:
4559     Form = Copy;
4560     break;
4561 
4562   case AtomicExpr::AO__c11_atomic_fetch_add:
4563   case AtomicExpr::AO__c11_atomic_fetch_sub:
4564   case AtomicExpr::AO__opencl_atomic_fetch_add:
4565   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4566   case AtomicExpr::AO__opencl_atomic_fetch_min:
4567   case AtomicExpr::AO__opencl_atomic_fetch_max:
4568   case AtomicExpr::AO__atomic_fetch_add:
4569   case AtomicExpr::AO__atomic_fetch_sub:
4570   case AtomicExpr::AO__atomic_add_fetch:
4571   case AtomicExpr::AO__atomic_sub_fetch:
4572     IsAddSub = true;
4573     LLVM_FALLTHROUGH;
4574   case AtomicExpr::AO__c11_atomic_fetch_and:
4575   case AtomicExpr::AO__c11_atomic_fetch_or:
4576   case AtomicExpr::AO__c11_atomic_fetch_xor:
4577   case AtomicExpr::AO__opencl_atomic_fetch_and:
4578   case AtomicExpr::AO__opencl_atomic_fetch_or:
4579   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4580   case AtomicExpr::AO__atomic_fetch_and:
4581   case AtomicExpr::AO__atomic_fetch_or:
4582   case AtomicExpr::AO__atomic_fetch_xor:
4583   case AtomicExpr::AO__atomic_fetch_nand:
4584   case AtomicExpr::AO__atomic_and_fetch:
4585   case AtomicExpr::AO__atomic_or_fetch:
4586   case AtomicExpr::AO__atomic_xor_fetch:
4587   case AtomicExpr::AO__atomic_nand_fetch:
4588     Form = Arithmetic;
4589     break;
4590 
4591   case AtomicExpr::AO__atomic_fetch_min:
4592   case AtomicExpr::AO__atomic_fetch_max:
4593     IsMinMax = true;
4594     Form = Arithmetic;
4595     break;
4596 
4597   case AtomicExpr::AO__c11_atomic_exchange:
4598   case AtomicExpr::AO__opencl_atomic_exchange:
4599   case AtomicExpr::AO__atomic_exchange_n:
4600     Form = Xchg;
4601     break;
4602 
4603   case AtomicExpr::AO__atomic_exchange:
4604     Form = GNUXchg;
4605     break;
4606 
4607   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4608   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4609   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4610   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4611     Form = C11CmpXchg;
4612     break;
4613 
4614   case AtomicExpr::AO__atomic_compare_exchange:
4615   case AtomicExpr::AO__atomic_compare_exchange_n:
4616     Form = GNUCmpXchg;
4617     break;
4618   }
4619 
4620   unsigned AdjustedNumArgs = NumArgs[Form];
4621   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4622     ++AdjustedNumArgs;
4623   // Check we have the right number of arguments.
4624   if (Args.size() < AdjustedNumArgs) {
4625     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4626         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4627         << ExprRange;
4628     return ExprError();
4629   } else if (Args.size() > AdjustedNumArgs) {
4630     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4631          diag::err_typecheck_call_too_many_args)
4632         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4633         << ExprRange;
4634     return ExprError();
4635   }
4636 
4637   // Inspect the first argument of the atomic operation.
4638   Expr *Ptr = Args[0];
4639   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4640   if (ConvertedPtr.isInvalid())
4641     return ExprError();
4642 
4643   Ptr = ConvertedPtr.get();
4644   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4645   if (!pointerType) {
4646     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4647         << Ptr->getType() << Ptr->getSourceRange();
4648     return ExprError();
4649   }
4650 
4651   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4652   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4653   QualType ValType = AtomTy; // 'C'
4654   if (IsC11) {
4655     if (!AtomTy->isAtomicType()) {
4656       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4657           << Ptr->getType() << Ptr->getSourceRange();
4658       return ExprError();
4659     }
4660     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4661         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4662       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4663           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4664           << Ptr->getSourceRange();
4665       return ExprError();
4666     }
4667     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4668   } else if (Form != Load && Form != LoadCopy) {
4669     if (ValType.isConstQualified()) {
4670       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4671           << Ptr->getType() << Ptr->getSourceRange();
4672       return ExprError();
4673     }
4674   }
4675 
4676   // For an arithmetic operation, the implied arithmetic must be well-formed.
4677   if (Form == Arithmetic) {
4678     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4679     if (IsAddSub && !ValType->isIntegerType()
4680         && !ValType->isPointerType()) {
4681       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4682           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4683       return ExprError();
4684     }
4685     if (IsMinMax) {
4686       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4687       if (!BT || (BT->getKind() != BuiltinType::Int &&
4688                   BT->getKind() != BuiltinType::UInt)) {
4689         Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_int32_or_ptr);
4690         return ExprError();
4691       }
4692     }
4693     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4694       Diag(ExprRange.getBegin(), diag::err_atomic_op_bitwise_needs_atomic_int)
4695           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4696       return ExprError();
4697     }
4698     if (IsC11 && ValType->isPointerType() &&
4699         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4700                             diag::err_incomplete_type)) {
4701       return ExprError();
4702     }
4703   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4704     // For __atomic_*_n operations, the value type must be a scalar integral or
4705     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4706     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4707         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4708     return ExprError();
4709   }
4710 
4711   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4712       !AtomTy->isScalarType()) {
4713     // For GNU atomics, require a trivially-copyable type. This is not part of
4714     // the GNU atomics specification, but we enforce it for sanity.
4715     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4716         << Ptr->getType() << Ptr->getSourceRange();
4717     return ExprError();
4718   }
4719 
4720   switch (ValType.getObjCLifetime()) {
4721   case Qualifiers::OCL_None:
4722   case Qualifiers::OCL_ExplicitNone:
4723     // okay
4724     break;
4725 
4726   case Qualifiers::OCL_Weak:
4727   case Qualifiers::OCL_Strong:
4728   case Qualifiers::OCL_Autoreleasing:
4729     // FIXME: Can this happen? By this point, ValType should be known
4730     // to be trivially copyable.
4731     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4732         << ValType << Ptr->getSourceRange();
4733     return ExprError();
4734   }
4735 
4736   // All atomic operations have an overload which takes a pointer to a volatile
4737   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4738   // into the result or the other operands. Similarly atomic_load takes a
4739   // pointer to a const 'A'.
4740   ValType.removeLocalVolatile();
4741   ValType.removeLocalConst();
4742   QualType ResultType = ValType;
4743   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4744       Form == Init)
4745     ResultType = Context.VoidTy;
4746   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4747     ResultType = Context.BoolTy;
4748 
4749   // The type of a parameter passed 'by value'. In the GNU atomics, such
4750   // arguments are actually passed as pointers.
4751   QualType ByValType = ValType; // 'CP'
4752   bool IsPassedByAddress = false;
4753   if (!IsC11 && !IsN) {
4754     ByValType = Ptr->getType();
4755     IsPassedByAddress = true;
4756   }
4757 
4758   SmallVector<Expr *, 5> APIOrderedArgs;
4759   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4760     APIOrderedArgs.push_back(Args[0]);
4761     switch (Form) {
4762     case Init:
4763     case Load:
4764       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4765       break;
4766     case LoadCopy:
4767     case Copy:
4768     case Arithmetic:
4769     case Xchg:
4770       APIOrderedArgs.push_back(Args[2]); // Val1
4771       APIOrderedArgs.push_back(Args[1]); // Order
4772       break;
4773     case GNUXchg:
4774       APIOrderedArgs.push_back(Args[2]); // Val1
4775       APIOrderedArgs.push_back(Args[3]); // Val2
4776       APIOrderedArgs.push_back(Args[1]); // Order
4777       break;
4778     case C11CmpXchg:
4779       APIOrderedArgs.push_back(Args[2]); // Val1
4780       APIOrderedArgs.push_back(Args[4]); // Val2
4781       APIOrderedArgs.push_back(Args[1]); // Order
4782       APIOrderedArgs.push_back(Args[3]); // OrderFail
4783       break;
4784     case GNUCmpXchg:
4785       APIOrderedArgs.push_back(Args[2]); // Val1
4786       APIOrderedArgs.push_back(Args[4]); // Val2
4787       APIOrderedArgs.push_back(Args[5]); // Weak
4788       APIOrderedArgs.push_back(Args[1]); // Order
4789       APIOrderedArgs.push_back(Args[3]); // OrderFail
4790       break;
4791     }
4792   } else
4793     APIOrderedArgs.append(Args.begin(), Args.end());
4794 
4795   // The first argument's non-CV pointer type is used to deduce the type of
4796   // subsequent arguments, except for:
4797   //  - weak flag (always converted to bool)
4798   //  - memory order (always converted to int)
4799   //  - scope  (always converted to int)
4800   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4801     QualType Ty;
4802     if (i < NumVals[Form] + 1) {
4803       switch (i) {
4804       case 0:
4805         // The first argument is always a pointer. It has a fixed type.
4806         // It is always dereferenced, a nullptr is undefined.
4807         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4808         // Nothing else to do: we already know all we want about this pointer.
4809         continue;
4810       case 1:
4811         // The second argument is the non-atomic operand. For arithmetic, this
4812         // is always passed by value, and for a compare_exchange it is always
4813         // passed by address. For the rest, GNU uses by-address and C11 uses
4814         // by-value.
4815         assert(Form != Load);
4816         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4817           Ty = ValType;
4818         else if (Form == Copy || Form == Xchg) {
4819           if (IsPassedByAddress) {
4820             // The value pointer is always dereferenced, a nullptr is undefined.
4821             CheckNonNullArgument(*this, APIOrderedArgs[i],
4822                                  ExprRange.getBegin());
4823           }
4824           Ty = ByValType;
4825         } else if (Form == Arithmetic)
4826           Ty = Context.getPointerDiffType();
4827         else {
4828           Expr *ValArg = APIOrderedArgs[i];
4829           // The value pointer is always dereferenced, a nullptr is undefined.
4830           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4831           LangAS AS = LangAS::Default;
4832           // Keep address space of non-atomic pointer type.
4833           if (const PointerType *PtrTy =
4834                   ValArg->getType()->getAs<PointerType>()) {
4835             AS = PtrTy->getPointeeType().getAddressSpace();
4836           }
4837           Ty = Context.getPointerType(
4838               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4839         }
4840         break;
4841       case 2:
4842         // The third argument to compare_exchange / GNU exchange is the desired
4843         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4844         if (IsPassedByAddress)
4845           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4846         Ty = ByValType;
4847         break;
4848       case 3:
4849         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4850         Ty = Context.BoolTy;
4851         break;
4852       }
4853     } else {
4854       // The order(s) and scope are always converted to int.
4855       Ty = Context.IntTy;
4856     }
4857 
4858     InitializedEntity Entity =
4859         InitializedEntity::InitializeParameter(Context, Ty, false);
4860     ExprResult Arg = APIOrderedArgs[i];
4861     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4862     if (Arg.isInvalid())
4863       return true;
4864     APIOrderedArgs[i] = Arg.get();
4865   }
4866 
4867   // Permute the arguments into a 'consistent' order.
4868   SmallVector<Expr*, 5> SubExprs;
4869   SubExprs.push_back(Ptr);
4870   switch (Form) {
4871   case Init:
4872     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4873     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4874     break;
4875   case Load:
4876     SubExprs.push_back(APIOrderedArgs[1]); // Order
4877     break;
4878   case LoadCopy:
4879   case Copy:
4880   case Arithmetic:
4881   case Xchg:
4882     SubExprs.push_back(APIOrderedArgs[2]); // Order
4883     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4884     break;
4885   case GNUXchg:
4886     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4887     SubExprs.push_back(APIOrderedArgs[3]); // Order
4888     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4889     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4890     break;
4891   case C11CmpXchg:
4892     SubExprs.push_back(APIOrderedArgs[3]); // Order
4893     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4894     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4895     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4896     break;
4897   case GNUCmpXchg:
4898     SubExprs.push_back(APIOrderedArgs[4]); // Order
4899     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4900     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4901     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4902     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4903     break;
4904   }
4905 
4906   if (SubExprs.size() >= 2 && Form != Init) {
4907     llvm::APSInt Result(32);
4908     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4909         !isValidOrderingForOp(Result.getSExtValue(), Op))
4910       Diag(SubExprs[1]->getBeginLoc(),
4911            diag::warn_atomic_op_has_invalid_memory_order)
4912           << SubExprs[1]->getSourceRange();
4913   }
4914 
4915   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4916     auto *Scope = Args[Args.size() - 1];
4917     llvm::APSInt Result(32);
4918     if (Scope->isIntegerConstantExpr(Result, Context) &&
4919         !ScopeModel->isValid(Result.getZExtValue())) {
4920       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4921           << Scope->getSourceRange();
4922     }
4923     SubExprs.push_back(Scope);
4924   }
4925 
4926   AtomicExpr *AE = new (Context)
4927       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4928 
4929   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4930        Op == AtomicExpr::AO__c11_atomic_store ||
4931        Op == AtomicExpr::AO__opencl_atomic_load ||
4932        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4933       Context.AtomicUsesUnsupportedLibcall(AE))
4934     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4935         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4936              Op == AtomicExpr::AO__opencl_atomic_load)
4937                 ? 0
4938                 : 1);
4939 
4940   return AE;
4941 }
4942 
4943 /// checkBuiltinArgument - Given a call to a builtin function, perform
4944 /// normal type-checking on the given argument, updating the call in
4945 /// place.  This is useful when a builtin function requires custom
4946 /// type-checking for some of its arguments but not necessarily all of
4947 /// them.
4948 ///
4949 /// Returns true on error.
4950 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4951   FunctionDecl *Fn = E->getDirectCallee();
4952   assert(Fn && "builtin call without direct callee!");
4953 
4954   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4955   InitializedEntity Entity =
4956     InitializedEntity::InitializeParameter(S.Context, Param);
4957 
4958   ExprResult Arg = E->getArg(0);
4959   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4960   if (Arg.isInvalid())
4961     return true;
4962 
4963   E->setArg(ArgIndex, Arg.get());
4964   return false;
4965 }
4966 
4967 /// We have a call to a function like __sync_fetch_and_add, which is an
4968 /// overloaded function based on the pointer type of its first argument.
4969 /// The main BuildCallExpr routines have already promoted the types of
4970 /// arguments because all of these calls are prototyped as void(...).
4971 ///
4972 /// This function goes through and does final semantic checking for these
4973 /// builtins, as well as generating any warnings.
4974 ExprResult
4975 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4976   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4977   Expr *Callee = TheCall->getCallee();
4978   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4979   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4980 
4981   // Ensure that we have at least one argument to do type inference from.
4982   if (TheCall->getNumArgs() < 1) {
4983     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4984         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4985     return ExprError();
4986   }
4987 
4988   // Inspect the first argument of the atomic builtin.  This should always be
4989   // a pointer type, whose element is an integral scalar or pointer type.
4990   // Because it is a pointer type, we don't have to worry about any implicit
4991   // casts here.
4992   // FIXME: We don't allow floating point scalars as input.
4993   Expr *FirstArg = TheCall->getArg(0);
4994   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4995   if (FirstArgResult.isInvalid())
4996     return ExprError();
4997   FirstArg = FirstArgResult.get();
4998   TheCall->setArg(0, FirstArg);
4999 
5000   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5001   if (!pointerType) {
5002     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5003         << FirstArg->getType() << FirstArg->getSourceRange();
5004     return ExprError();
5005   }
5006 
5007   QualType ValType = pointerType->getPointeeType();
5008   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5009       !ValType->isBlockPointerType()) {
5010     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5011         << FirstArg->getType() << FirstArg->getSourceRange();
5012     return ExprError();
5013   }
5014 
5015   if (ValType.isConstQualified()) {
5016     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5017         << FirstArg->getType() << FirstArg->getSourceRange();
5018     return ExprError();
5019   }
5020 
5021   switch (ValType.getObjCLifetime()) {
5022   case Qualifiers::OCL_None:
5023   case Qualifiers::OCL_ExplicitNone:
5024     // okay
5025     break;
5026 
5027   case Qualifiers::OCL_Weak:
5028   case Qualifiers::OCL_Strong:
5029   case Qualifiers::OCL_Autoreleasing:
5030     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5031         << ValType << FirstArg->getSourceRange();
5032     return ExprError();
5033   }
5034 
5035   // Strip any qualifiers off ValType.
5036   ValType = ValType.getUnqualifiedType();
5037 
5038   // The majority of builtins return a value, but a few have special return
5039   // types, so allow them to override appropriately below.
5040   QualType ResultType = ValType;
5041 
5042   // We need to figure out which concrete builtin this maps onto.  For example,
5043   // __sync_fetch_and_add with a 2 byte object turns into
5044   // __sync_fetch_and_add_2.
5045 #define BUILTIN_ROW(x) \
5046   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5047     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5048 
5049   static const unsigned BuiltinIndices[][5] = {
5050     BUILTIN_ROW(__sync_fetch_and_add),
5051     BUILTIN_ROW(__sync_fetch_and_sub),
5052     BUILTIN_ROW(__sync_fetch_and_or),
5053     BUILTIN_ROW(__sync_fetch_and_and),
5054     BUILTIN_ROW(__sync_fetch_and_xor),
5055     BUILTIN_ROW(__sync_fetch_and_nand),
5056 
5057     BUILTIN_ROW(__sync_add_and_fetch),
5058     BUILTIN_ROW(__sync_sub_and_fetch),
5059     BUILTIN_ROW(__sync_and_and_fetch),
5060     BUILTIN_ROW(__sync_or_and_fetch),
5061     BUILTIN_ROW(__sync_xor_and_fetch),
5062     BUILTIN_ROW(__sync_nand_and_fetch),
5063 
5064     BUILTIN_ROW(__sync_val_compare_and_swap),
5065     BUILTIN_ROW(__sync_bool_compare_and_swap),
5066     BUILTIN_ROW(__sync_lock_test_and_set),
5067     BUILTIN_ROW(__sync_lock_release),
5068     BUILTIN_ROW(__sync_swap)
5069   };
5070 #undef BUILTIN_ROW
5071 
5072   // Determine the index of the size.
5073   unsigned SizeIndex;
5074   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5075   case 1: SizeIndex = 0; break;
5076   case 2: SizeIndex = 1; break;
5077   case 4: SizeIndex = 2; break;
5078   case 8: SizeIndex = 3; break;
5079   case 16: SizeIndex = 4; break;
5080   default:
5081     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5082         << FirstArg->getType() << FirstArg->getSourceRange();
5083     return ExprError();
5084   }
5085 
5086   // Each of these builtins has one pointer argument, followed by some number of
5087   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5088   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5089   // as the number of fixed args.
5090   unsigned BuiltinID = FDecl->getBuiltinID();
5091   unsigned BuiltinIndex, NumFixed = 1;
5092   bool WarnAboutSemanticsChange = false;
5093   switch (BuiltinID) {
5094   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5095   case Builtin::BI__sync_fetch_and_add:
5096   case Builtin::BI__sync_fetch_and_add_1:
5097   case Builtin::BI__sync_fetch_and_add_2:
5098   case Builtin::BI__sync_fetch_and_add_4:
5099   case Builtin::BI__sync_fetch_and_add_8:
5100   case Builtin::BI__sync_fetch_and_add_16:
5101     BuiltinIndex = 0;
5102     break;
5103 
5104   case Builtin::BI__sync_fetch_and_sub:
5105   case Builtin::BI__sync_fetch_and_sub_1:
5106   case Builtin::BI__sync_fetch_and_sub_2:
5107   case Builtin::BI__sync_fetch_and_sub_4:
5108   case Builtin::BI__sync_fetch_and_sub_8:
5109   case Builtin::BI__sync_fetch_and_sub_16:
5110     BuiltinIndex = 1;
5111     break;
5112 
5113   case Builtin::BI__sync_fetch_and_or:
5114   case Builtin::BI__sync_fetch_and_or_1:
5115   case Builtin::BI__sync_fetch_and_or_2:
5116   case Builtin::BI__sync_fetch_and_or_4:
5117   case Builtin::BI__sync_fetch_and_or_8:
5118   case Builtin::BI__sync_fetch_and_or_16:
5119     BuiltinIndex = 2;
5120     break;
5121 
5122   case Builtin::BI__sync_fetch_and_and:
5123   case Builtin::BI__sync_fetch_and_and_1:
5124   case Builtin::BI__sync_fetch_and_and_2:
5125   case Builtin::BI__sync_fetch_and_and_4:
5126   case Builtin::BI__sync_fetch_and_and_8:
5127   case Builtin::BI__sync_fetch_and_and_16:
5128     BuiltinIndex = 3;
5129     break;
5130 
5131   case Builtin::BI__sync_fetch_and_xor:
5132   case Builtin::BI__sync_fetch_and_xor_1:
5133   case Builtin::BI__sync_fetch_and_xor_2:
5134   case Builtin::BI__sync_fetch_and_xor_4:
5135   case Builtin::BI__sync_fetch_and_xor_8:
5136   case Builtin::BI__sync_fetch_and_xor_16:
5137     BuiltinIndex = 4;
5138     break;
5139 
5140   case Builtin::BI__sync_fetch_and_nand:
5141   case Builtin::BI__sync_fetch_and_nand_1:
5142   case Builtin::BI__sync_fetch_and_nand_2:
5143   case Builtin::BI__sync_fetch_and_nand_4:
5144   case Builtin::BI__sync_fetch_and_nand_8:
5145   case Builtin::BI__sync_fetch_and_nand_16:
5146     BuiltinIndex = 5;
5147     WarnAboutSemanticsChange = true;
5148     break;
5149 
5150   case Builtin::BI__sync_add_and_fetch:
5151   case Builtin::BI__sync_add_and_fetch_1:
5152   case Builtin::BI__sync_add_and_fetch_2:
5153   case Builtin::BI__sync_add_and_fetch_4:
5154   case Builtin::BI__sync_add_and_fetch_8:
5155   case Builtin::BI__sync_add_and_fetch_16:
5156     BuiltinIndex = 6;
5157     break;
5158 
5159   case Builtin::BI__sync_sub_and_fetch:
5160   case Builtin::BI__sync_sub_and_fetch_1:
5161   case Builtin::BI__sync_sub_and_fetch_2:
5162   case Builtin::BI__sync_sub_and_fetch_4:
5163   case Builtin::BI__sync_sub_and_fetch_8:
5164   case Builtin::BI__sync_sub_and_fetch_16:
5165     BuiltinIndex = 7;
5166     break;
5167 
5168   case Builtin::BI__sync_and_and_fetch:
5169   case Builtin::BI__sync_and_and_fetch_1:
5170   case Builtin::BI__sync_and_and_fetch_2:
5171   case Builtin::BI__sync_and_and_fetch_4:
5172   case Builtin::BI__sync_and_and_fetch_8:
5173   case Builtin::BI__sync_and_and_fetch_16:
5174     BuiltinIndex = 8;
5175     break;
5176 
5177   case Builtin::BI__sync_or_and_fetch:
5178   case Builtin::BI__sync_or_and_fetch_1:
5179   case Builtin::BI__sync_or_and_fetch_2:
5180   case Builtin::BI__sync_or_and_fetch_4:
5181   case Builtin::BI__sync_or_and_fetch_8:
5182   case Builtin::BI__sync_or_and_fetch_16:
5183     BuiltinIndex = 9;
5184     break;
5185 
5186   case Builtin::BI__sync_xor_and_fetch:
5187   case Builtin::BI__sync_xor_and_fetch_1:
5188   case Builtin::BI__sync_xor_and_fetch_2:
5189   case Builtin::BI__sync_xor_and_fetch_4:
5190   case Builtin::BI__sync_xor_and_fetch_8:
5191   case Builtin::BI__sync_xor_and_fetch_16:
5192     BuiltinIndex = 10;
5193     break;
5194 
5195   case Builtin::BI__sync_nand_and_fetch:
5196   case Builtin::BI__sync_nand_and_fetch_1:
5197   case Builtin::BI__sync_nand_and_fetch_2:
5198   case Builtin::BI__sync_nand_and_fetch_4:
5199   case Builtin::BI__sync_nand_and_fetch_8:
5200   case Builtin::BI__sync_nand_and_fetch_16:
5201     BuiltinIndex = 11;
5202     WarnAboutSemanticsChange = true;
5203     break;
5204 
5205   case Builtin::BI__sync_val_compare_and_swap:
5206   case Builtin::BI__sync_val_compare_and_swap_1:
5207   case Builtin::BI__sync_val_compare_and_swap_2:
5208   case Builtin::BI__sync_val_compare_and_swap_4:
5209   case Builtin::BI__sync_val_compare_and_swap_8:
5210   case Builtin::BI__sync_val_compare_and_swap_16:
5211     BuiltinIndex = 12;
5212     NumFixed = 2;
5213     break;
5214 
5215   case Builtin::BI__sync_bool_compare_and_swap:
5216   case Builtin::BI__sync_bool_compare_and_swap_1:
5217   case Builtin::BI__sync_bool_compare_and_swap_2:
5218   case Builtin::BI__sync_bool_compare_and_swap_4:
5219   case Builtin::BI__sync_bool_compare_and_swap_8:
5220   case Builtin::BI__sync_bool_compare_and_swap_16:
5221     BuiltinIndex = 13;
5222     NumFixed = 2;
5223     ResultType = Context.BoolTy;
5224     break;
5225 
5226   case Builtin::BI__sync_lock_test_and_set:
5227   case Builtin::BI__sync_lock_test_and_set_1:
5228   case Builtin::BI__sync_lock_test_and_set_2:
5229   case Builtin::BI__sync_lock_test_and_set_4:
5230   case Builtin::BI__sync_lock_test_and_set_8:
5231   case Builtin::BI__sync_lock_test_and_set_16:
5232     BuiltinIndex = 14;
5233     break;
5234 
5235   case Builtin::BI__sync_lock_release:
5236   case Builtin::BI__sync_lock_release_1:
5237   case Builtin::BI__sync_lock_release_2:
5238   case Builtin::BI__sync_lock_release_4:
5239   case Builtin::BI__sync_lock_release_8:
5240   case Builtin::BI__sync_lock_release_16:
5241     BuiltinIndex = 15;
5242     NumFixed = 0;
5243     ResultType = Context.VoidTy;
5244     break;
5245 
5246   case Builtin::BI__sync_swap:
5247   case Builtin::BI__sync_swap_1:
5248   case Builtin::BI__sync_swap_2:
5249   case Builtin::BI__sync_swap_4:
5250   case Builtin::BI__sync_swap_8:
5251   case Builtin::BI__sync_swap_16:
5252     BuiltinIndex = 16;
5253     break;
5254   }
5255 
5256   // Now that we know how many fixed arguments we expect, first check that we
5257   // have at least that many.
5258   if (TheCall->getNumArgs() < 1+NumFixed) {
5259     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5260         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5261         << Callee->getSourceRange();
5262     return ExprError();
5263   }
5264 
5265   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5266       << Callee->getSourceRange();
5267 
5268   if (WarnAboutSemanticsChange) {
5269     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5270         << Callee->getSourceRange();
5271   }
5272 
5273   // Get the decl for the concrete builtin from this, we can tell what the
5274   // concrete integer type we should convert to is.
5275   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5276   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5277   FunctionDecl *NewBuiltinDecl;
5278   if (NewBuiltinID == BuiltinID)
5279     NewBuiltinDecl = FDecl;
5280   else {
5281     // Perform builtin lookup to avoid redeclaring it.
5282     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5283     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5284     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5285     assert(Res.getFoundDecl());
5286     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5287     if (!NewBuiltinDecl)
5288       return ExprError();
5289   }
5290 
5291   // The first argument --- the pointer --- has a fixed type; we
5292   // deduce the types of the rest of the arguments accordingly.  Walk
5293   // the remaining arguments, converting them to the deduced value type.
5294   for (unsigned i = 0; i != NumFixed; ++i) {
5295     ExprResult Arg = TheCall->getArg(i+1);
5296 
5297     // GCC does an implicit conversion to the pointer or integer ValType.  This
5298     // can fail in some cases (1i -> int**), check for this error case now.
5299     // Initialize the argument.
5300     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5301                                                    ValType, /*consume*/ false);
5302     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5303     if (Arg.isInvalid())
5304       return ExprError();
5305 
5306     // Okay, we have something that *can* be converted to the right type.  Check
5307     // to see if there is a potentially weird extension going on here.  This can
5308     // happen when you do an atomic operation on something like an char* and
5309     // pass in 42.  The 42 gets converted to char.  This is even more strange
5310     // for things like 45.123 -> char, etc.
5311     // FIXME: Do this check.
5312     TheCall->setArg(i+1, Arg.get());
5313   }
5314 
5315   // Create a new DeclRefExpr to refer to the new decl.
5316   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5317       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5318       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5319       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5320 
5321   // Set the callee in the CallExpr.
5322   // FIXME: This loses syntactic information.
5323   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5324   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5325                                               CK_BuiltinFnToFnPtr);
5326   TheCall->setCallee(PromotedCall.get());
5327 
5328   // Change the result type of the call to match the original value type. This
5329   // is arbitrary, but the codegen for these builtins ins design to handle it
5330   // gracefully.
5331   TheCall->setType(ResultType);
5332 
5333   return TheCallResult;
5334 }
5335 
5336 /// SemaBuiltinNontemporalOverloaded - We have a call to
5337 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5338 /// overloaded function based on the pointer type of its last argument.
5339 ///
5340 /// This function goes through and does final semantic checking for these
5341 /// builtins.
5342 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5343   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5344   DeclRefExpr *DRE =
5345       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5346   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5347   unsigned BuiltinID = FDecl->getBuiltinID();
5348   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5349           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5350          "Unexpected nontemporal load/store builtin!");
5351   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5352   unsigned numArgs = isStore ? 2 : 1;
5353 
5354   // Ensure that we have the proper number of arguments.
5355   if (checkArgCount(*this, TheCall, numArgs))
5356     return ExprError();
5357 
5358   // Inspect the last argument of the nontemporal builtin.  This should always
5359   // be a pointer type, from which we imply the type of the memory access.
5360   // Because it is a pointer type, we don't have to worry about any implicit
5361   // casts here.
5362   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5363   ExprResult PointerArgResult =
5364       DefaultFunctionArrayLvalueConversion(PointerArg);
5365 
5366   if (PointerArgResult.isInvalid())
5367     return ExprError();
5368   PointerArg = PointerArgResult.get();
5369   TheCall->setArg(numArgs - 1, PointerArg);
5370 
5371   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5372   if (!pointerType) {
5373     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5374         << PointerArg->getType() << PointerArg->getSourceRange();
5375     return ExprError();
5376   }
5377 
5378   QualType ValType = pointerType->getPointeeType();
5379 
5380   // Strip any qualifiers off ValType.
5381   ValType = ValType.getUnqualifiedType();
5382   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5383       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5384       !ValType->isVectorType()) {
5385     Diag(DRE->getBeginLoc(),
5386          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5387         << PointerArg->getType() << PointerArg->getSourceRange();
5388     return ExprError();
5389   }
5390 
5391   if (!isStore) {
5392     TheCall->setType(ValType);
5393     return TheCallResult;
5394   }
5395 
5396   ExprResult ValArg = TheCall->getArg(0);
5397   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5398       Context, ValType, /*consume*/ false);
5399   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5400   if (ValArg.isInvalid())
5401     return ExprError();
5402 
5403   TheCall->setArg(0, ValArg.get());
5404   TheCall->setType(Context.VoidTy);
5405   return TheCallResult;
5406 }
5407 
5408 /// CheckObjCString - Checks that the argument to the builtin
5409 /// CFString constructor is correct
5410 /// Note: It might also make sense to do the UTF-16 conversion here (would
5411 /// simplify the backend).
5412 bool Sema::CheckObjCString(Expr *Arg) {
5413   Arg = Arg->IgnoreParenCasts();
5414   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5415 
5416   if (!Literal || !Literal->isAscii()) {
5417     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5418         << Arg->getSourceRange();
5419     return true;
5420   }
5421 
5422   if (Literal->containsNonAsciiOrNull()) {
5423     StringRef String = Literal->getString();
5424     unsigned NumBytes = String.size();
5425     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5426     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5427     llvm::UTF16 *ToPtr = &ToBuf[0];
5428 
5429     llvm::ConversionResult Result =
5430         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5431                                  ToPtr + NumBytes, llvm::strictConversion);
5432     // Check for conversion failure.
5433     if (Result != llvm::conversionOK)
5434       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5435           << Arg->getSourceRange();
5436   }
5437   return false;
5438 }
5439 
5440 /// CheckObjCString - Checks that the format string argument to the os_log()
5441 /// and os_trace() functions is correct, and converts it to const char *.
5442 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5443   Arg = Arg->IgnoreParenCasts();
5444   auto *Literal = dyn_cast<StringLiteral>(Arg);
5445   if (!Literal) {
5446     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5447       Literal = ObjcLiteral->getString();
5448     }
5449   }
5450 
5451   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5452     return ExprError(
5453         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5454         << Arg->getSourceRange());
5455   }
5456 
5457   ExprResult Result(Literal);
5458   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5459   InitializedEntity Entity =
5460       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5461   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5462   return Result;
5463 }
5464 
5465 /// Check that the user is calling the appropriate va_start builtin for the
5466 /// target and calling convention.
5467 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5468   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5469   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5470   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5471   bool IsWindows = TT.isOSWindows();
5472   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5473   if (IsX64 || IsAArch64) {
5474     CallingConv CC = CC_C;
5475     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5476       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5477     if (IsMSVAStart) {
5478       // Don't allow this in System V ABI functions.
5479       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5480         return S.Diag(Fn->getBeginLoc(),
5481                       diag::err_ms_va_start_used_in_sysv_function);
5482     } else {
5483       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5484       // On x64 Windows, don't allow this in System V ABI functions.
5485       // (Yes, that means there's no corresponding way to support variadic
5486       // System V ABI functions on Windows.)
5487       if ((IsWindows && CC == CC_X86_64SysV) ||
5488           (!IsWindows && CC == CC_Win64))
5489         return S.Diag(Fn->getBeginLoc(),
5490                       diag::err_va_start_used_in_wrong_abi_function)
5491                << !IsWindows;
5492     }
5493     return false;
5494   }
5495 
5496   if (IsMSVAStart)
5497     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5498   return false;
5499 }
5500 
5501 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5502                                              ParmVarDecl **LastParam = nullptr) {
5503   // Determine whether the current function, block, or obj-c method is variadic
5504   // and get its parameter list.
5505   bool IsVariadic = false;
5506   ArrayRef<ParmVarDecl *> Params;
5507   DeclContext *Caller = S.CurContext;
5508   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5509     IsVariadic = Block->isVariadic();
5510     Params = Block->parameters();
5511   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5512     IsVariadic = FD->isVariadic();
5513     Params = FD->parameters();
5514   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5515     IsVariadic = MD->isVariadic();
5516     // FIXME: This isn't correct for methods (results in bogus warning).
5517     Params = MD->parameters();
5518   } else if (isa<CapturedDecl>(Caller)) {
5519     // We don't support va_start in a CapturedDecl.
5520     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5521     return true;
5522   } else {
5523     // This must be some other declcontext that parses exprs.
5524     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5525     return true;
5526   }
5527 
5528   if (!IsVariadic) {
5529     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5530     return true;
5531   }
5532 
5533   if (LastParam)
5534     *LastParam = Params.empty() ? nullptr : Params.back();
5535 
5536   return false;
5537 }
5538 
5539 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5540 /// for validity.  Emit an error and return true on failure; return false
5541 /// on success.
5542 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5543   Expr *Fn = TheCall->getCallee();
5544 
5545   if (checkVAStartABI(*this, BuiltinID, Fn))
5546     return true;
5547 
5548   if (TheCall->getNumArgs() > 2) {
5549     Diag(TheCall->getArg(2)->getBeginLoc(),
5550          diag::err_typecheck_call_too_many_args)
5551         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5552         << Fn->getSourceRange()
5553         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5554                        (*(TheCall->arg_end() - 1))->getEndLoc());
5555     return true;
5556   }
5557 
5558   if (TheCall->getNumArgs() < 2) {
5559     return Diag(TheCall->getEndLoc(),
5560                 diag::err_typecheck_call_too_few_args_at_least)
5561            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5562   }
5563 
5564   // Type-check the first argument normally.
5565   if (checkBuiltinArgument(*this, TheCall, 0))
5566     return true;
5567 
5568   // Check that the current function is variadic, and get its last parameter.
5569   ParmVarDecl *LastParam;
5570   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5571     return true;
5572 
5573   // Verify that the second argument to the builtin is the last argument of the
5574   // current function or method.
5575   bool SecondArgIsLastNamedArgument = false;
5576   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5577 
5578   // These are valid if SecondArgIsLastNamedArgument is false after the next
5579   // block.
5580   QualType Type;
5581   SourceLocation ParamLoc;
5582   bool IsCRegister = false;
5583 
5584   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5585     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5586       SecondArgIsLastNamedArgument = PV == LastParam;
5587 
5588       Type = PV->getType();
5589       ParamLoc = PV->getLocation();
5590       IsCRegister =
5591           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5592     }
5593   }
5594 
5595   if (!SecondArgIsLastNamedArgument)
5596     Diag(TheCall->getArg(1)->getBeginLoc(),
5597          diag::warn_second_arg_of_va_start_not_last_named_param);
5598   else if (IsCRegister || Type->isReferenceType() ||
5599            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5600              // Promotable integers are UB, but enumerations need a bit of
5601              // extra checking to see what their promotable type actually is.
5602              if (!Type->isPromotableIntegerType())
5603                return false;
5604              if (!Type->isEnumeralType())
5605                return true;
5606              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5607              return !(ED &&
5608                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5609            }()) {
5610     unsigned Reason = 0;
5611     if (Type->isReferenceType())  Reason = 1;
5612     else if (IsCRegister)         Reason = 2;
5613     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5614     Diag(ParamLoc, diag::note_parameter_type) << Type;
5615   }
5616 
5617   TheCall->setType(Context.VoidTy);
5618   return false;
5619 }
5620 
5621 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5622   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5623   //                 const char *named_addr);
5624 
5625   Expr *Func = Call->getCallee();
5626 
5627   if (Call->getNumArgs() < 3)
5628     return Diag(Call->getEndLoc(),
5629                 diag::err_typecheck_call_too_few_args_at_least)
5630            << 0 /*function call*/ << 3 << Call->getNumArgs();
5631 
5632   // Type-check the first argument normally.
5633   if (checkBuiltinArgument(*this, Call, 0))
5634     return true;
5635 
5636   // Check that the current function is variadic.
5637   if (checkVAStartIsInVariadicFunction(*this, Func))
5638     return true;
5639 
5640   // __va_start on Windows does not validate the parameter qualifiers
5641 
5642   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5643   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5644 
5645   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5646   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5647 
5648   const QualType &ConstCharPtrTy =
5649       Context.getPointerType(Context.CharTy.withConst());
5650   if (!Arg1Ty->isPointerType() ||
5651       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5652     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5653         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5654         << 0                                      /* qualifier difference */
5655         << 3                                      /* parameter mismatch */
5656         << 2 << Arg1->getType() << ConstCharPtrTy;
5657 
5658   const QualType SizeTy = Context.getSizeType();
5659   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5660     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5661         << Arg2->getType() << SizeTy << 1 /* different class */
5662         << 0                              /* qualifier difference */
5663         << 3                              /* parameter mismatch */
5664         << 3 << Arg2->getType() << SizeTy;
5665 
5666   return false;
5667 }
5668 
5669 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5670 /// friends.  This is declared to take (...), so we have to check everything.
5671 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5672   if (TheCall->getNumArgs() < 2)
5673     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5674            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5675   if (TheCall->getNumArgs() > 2)
5676     return Diag(TheCall->getArg(2)->getBeginLoc(),
5677                 diag::err_typecheck_call_too_many_args)
5678            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5679            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5680                           (*(TheCall->arg_end() - 1))->getEndLoc());
5681 
5682   ExprResult OrigArg0 = TheCall->getArg(0);
5683   ExprResult OrigArg1 = TheCall->getArg(1);
5684 
5685   // Do standard promotions between the two arguments, returning their common
5686   // type.
5687   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5688   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5689     return true;
5690 
5691   // Make sure any conversions are pushed back into the call; this is
5692   // type safe since unordered compare builtins are declared as "_Bool
5693   // foo(...)".
5694   TheCall->setArg(0, OrigArg0.get());
5695   TheCall->setArg(1, OrigArg1.get());
5696 
5697   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5698     return false;
5699 
5700   // If the common type isn't a real floating type, then the arguments were
5701   // invalid for this operation.
5702   if (Res.isNull() || !Res->isRealFloatingType())
5703     return Diag(OrigArg0.get()->getBeginLoc(),
5704                 diag::err_typecheck_call_invalid_ordered_compare)
5705            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5706            << SourceRange(OrigArg0.get()->getBeginLoc(),
5707                           OrigArg1.get()->getEndLoc());
5708 
5709   return false;
5710 }
5711 
5712 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5713 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5714 /// to check everything. We expect the last argument to be a floating point
5715 /// value.
5716 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5717   if (TheCall->getNumArgs() < NumArgs)
5718     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5719            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5720   if (TheCall->getNumArgs() > NumArgs)
5721     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5722                 diag::err_typecheck_call_too_many_args)
5723            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5724            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5725                           (*(TheCall->arg_end() - 1))->getEndLoc());
5726 
5727   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5728 
5729   if (OrigArg->isTypeDependent())
5730     return false;
5731 
5732   // This operation requires a non-_Complex floating-point number.
5733   if (!OrigArg->getType()->isRealFloatingType())
5734     return Diag(OrigArg->getBeginLoc(),
5735                 diag::err_typecheck_call_invalid_unary_fp)
5736            << OrigArg->getType() << OrigArg->getSourceRange();
5737 
5738   // If this is an implicit conversion from float -> float, double, or
5739   // long double, remove it.
5740   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5741     // Only remove standard FloatCasts, leaving other casts inplace
5742     if (Cast->getCastKind() == CK_FloatingCast) {
5743       Expr *CastArg = Cast->getSubExpr();
5744       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5745         assert(
5746             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5747              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5748              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5749             "promotion from float to either float, double, or long double is "
5750             "the only expected cast here");
5751         Cast->setSubExpr(nullptr);
5752         TheCall->setArg(NumArgs-1, CastArg);
5753       }
5754     }
5755   }
5756 
5757   return false;
5758 }
5759 
5760 // Customized Sema Checking for VSX builtins that have the following signature:
5761 // vector [...] builtinName(vector [...], vector [...], const int);
5762 // Which takes the same type of vectors (any legal vector type) for the first
5763 // two arguments and takes compile time constant for the third argument.
5764 // Example builtins are :
5765 // vector double vec_xxpermdi(vector double, vector double, int);
5766 // vector short vec_xxsldwi(vector short, vector short, int);
5767 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5768   unsigned ExpectedNumArgs = 3;
5769   if (TheCall->getNumArgs() < ExpectedNumArgs)
5770     return Diag(TheCall->getEndLoc(),
5771                 diag::err_typecheck_call_too_few_args_at_least)
5772            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5773            << TheCall->getSourceRange();
5774 
5775   if (TheCall->getNumArgs() > ExpectedNumArgs)
5776     return Diag(TheCall->getEndLoc(),
5777                 diag::err_typecheck_call_too_many_args_at_most)
5778            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5779            << TheCall->getSourceRange();
5780 
5781   // Check the third argument is a compile time constant
5782   llvm::APSInt Value;
5783   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5784     return Diag(TheCall->getBeginLoc(),
5785                 diag::err_vsx_builtin_nonconstant_argument)
5786            << 3 /* argument index */ << TheCall->getDirectCallee()
5787            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5788                           TheCall->getArg(2)->getEndLoc());
5789 
5790   QualType Arg1Ty = TheCall->getArg(0)->getType();
5791   QualType Arg2Ty = TheCall->getArg(1)->getType();
5792 
5793   // Check the type of argument 1 and argument 2 are vectors.
5794   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5795   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5796       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5797     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5798            << TheCall->getDirectCallee()
5799            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5800                           TheCall->getArg(1)->getEndLoc());
5801   }
5802 
5803   // Check the first two arguments are the same type.
5804   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5805     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5806            << TheCall->getDirectCallee()
5807            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5808                           TheCall->getArg(1)->getEndLoc());
5809   }
5810 
5811   // When default clang type checking is turned off and the customized type
5812   // checking is used, the returning type of the function must be explicitly
5813   // set. Otherwise it is _Bool by default.
5814   TheCall->setType(Arg1Ty);
5815 
5816   return false;
5817 }
5818 
5819 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5820 // This is declared to take (...), so we have to check everything.
5821 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5822   if (TheCall->getNumArgs() < 2)
5823     return ExprError(Diag(TheCall->getEndLoc(),
5824                           diag::err_typecheck_call_too_few_args_at_least)
5825                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5826                      << TheCall->getSourceRange());
5827 
5828   // Determine which of the following types of shufflevector we're checking:
5829   // 1) unary, vector mask: (lhs, mask)
5830   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5831   QualType resType = TheCall->getArg(0)->getType();
5832   unsigned numElements = 0;
5833 
5834   if (!TheCall->getArg(0)->isTypeDependent() &&
5835       !TheCall->getArg(1)->isTypeDependent()) {
5836     QualType LHSType = TheCall->getArg(0)->getType();
5837     QualType RHSType = TheCall->getArg(1)->getType();
5838 
5839     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5840       return ExprError(
5841           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5842           << TheCall->getDirectCallee()
5843           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5844                          TheCall->getArg(1)->getEndLoc()));
5845 
5846     numElements = LHSType->castAs<VectorType>()->getNumElements();
5847     unsigned numResElements = TheCall->getNumArgs() - 2;
5848 
5849     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5850     // with mask.  If so, verify that RHS is an integer vector type with the
5851     // same number of elts as lhs.
5852     if (TheCall->getNumArgs() == 2) {
5853       if (!RHSType->hasIntegerRepresentation() ||
5854           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5855         return ExprError(Diag(TheCall->getBeginLoc(),
5856                               diag::err_vec_builtin_incompatible_vector)
5857                          << TheCall->getDirectCallee()
5858                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5859                                         TheCall->getArg(1)->getEndLoc()));
5860     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5861       return ExprError(Diag(TheCall->getBeginLoc(),
5862                             diag::err_vec_builtin_incompatible_vector)
5863                        << TheCall->getDirectCallee()
5864                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5865                                       TheCall->getArg(1)->getEndLoc()));
5866     } else if (numElements != numResElements) {
5867       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5868       resType = Context.getVectorType(eltType, numResElements,
5869                                       VectorType::GenericVector);
5870     }
5871   }
5872 
5873   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5874     if (TheCall->getArg(i)->isTypeDependent() ||
5875         TheCall->getArg(i)->isValueDependent())
5876       continue;
5877 
5878     llvm::APSInt Result(32);
5879     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5880       return ExprError(Diag(TheCall->getBeginLoc(),
5881                             diag::err_shufflevector_nonconstant_argument)
5882                        << TheCall->getArg(i)->getSourceRange());
5883 
5884     // Allow -1 which will be translated to undef in the IR.
5885     if (Result.isSigned() && Result.isAllOnesValue())
5886       continue;
5887 
5888     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5889       return ExprError(Diag(TheCall->getBeginLoc(),
5890                             diag::err_shufflevector_argument_too_large)
5891                        << TheCall->getArg(i)->getSourceRange());
5892   }
5893 
5894   SmallVector<Expr*, 32> exprs;
5895 
5896   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5897     exprs.push_back(TheCall->getArg(i));
5898     TheCall->setArg(i, nullptr);
5899   }
5900 
5901   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5902                                          TheCall->getCallee()->getBeginLoc(),
5903                                          TheCall->getRParenLoc());
5904 }
5905 
5906 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5907 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5908                                        SourceLocation BuiltinLoc,
5909                                        SourceLocation RParenLoc) {
5910   ExprValueKind VK = VK_RValue;
5911   ExprObjectKind OK = OK_Ordinary;
5912   QualType DstTy = TInfo->getType();
5913   QualType SrcTy = E->getType();
5914 
5915   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5916     return ExprError(Diag(BuiltinLoc,
5917                           diag::err_convertvector_non_vector)
5918                      << E->getSourceRange());
5919   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5920     return ExprError(Diag(BuiltinLoc,
5921                           diag::err_convertvector_non_vector_type));
5922 
5923   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5924     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5925     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5926     if (SrcElts != DstElts)
5927       return ExprError(Diag(BuiltinLoc,
5928                             diag::err_convertvector_incompatible_vector)
5929                        << E->getSourceRange());
5930   }
5931 
5932   return new (Context)
5933       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5934 }
5935 
5936 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5937 // This is declared to take (const void*, ...) and can take two
5938 // optional constant int args.
5939 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5940   unsigned NumArgs = TheCall->getNumArgs();
5941 
5942   if (NumArgs > 3)
5943     return Diag(TheCall->getEndLoc(),
5944                 diag::err_typecheck_call_too_many_args_at_most)
5945            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5946 
5947   // Argument 0 is checked for us and the remaining arguments must be
5948   // constant integers.
5949   for (unsigned i = 1; i != NumArgs; ++i)
5950     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5951       return true;
5952 
5953   return false;
5954 }
5955 
5956 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5957 // __assume does not evaluate its arguments, and should warn if its argument
5958 // has side effects.
5959 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5960   Expr *Arg = TheCall->getArg(0);
5961   if (Arg->isInstantiationDependent()) return false;
5962 
5963   if (Arg->HasSideEffects(Context))
5964     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5965         << Arg->getSourceRange()
5966         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5967 
5968   return false;
5969 }
5970 
5971 /// Handle __builtin_alloca_with_align. This is declared
5972 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5973 /// than 8.
5974 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5975   // The alignment must be a constant integer.
5976   Expr *Arg = TheCall->getArg(1);
5977 
5978   // We can't check the value of a dependent argument.
5979   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5980     if (const auto *UE =
5981             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5982       if (UE->getKind() == UETT_AlignOf ||
5983           UE->getKind() == UETT_PreferredAlignOf)
5984         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5985             << Arg->getSourceRange();
5986 
5987     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5988 
5989     if (!Result.isPowerOf2())
5990       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5991              << Arg->getSourceRange();
5992 
5993     if (Result < Context.getCharWidth())
5994       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5995              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5996 
5997     if (Result > std::numeric_limits<int32_t>::max())
5998       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5999              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6000   }
6001 
6002   return false;
6003 }
6004 
6005 /// Handle __builtin_assume_aligned. This is declared
6006 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6007 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6008   unsigned NumArgs = TheCall->getNumArgs();
6009 
6010   if (NumArgs > 3)
6011     return Diag(TheCall->getEndLoc(),
6012                 diag::err_typecheck_call_too_many_args_at_most)
6013            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6014 
6015   // The alignment must be a constant integer.
6016   Expr *Arg = TheCall->getArg(1);
6017 
6018   // We can't check the value of a dependent argument.
6019   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6020     llvm::APSInt Result;
6021     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6022       return true;
6023 
6024     if (!Result.isPowerOf2())
6025       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6026              << Arg->getSourceRange();
6027   }
6028 
6029   if (NumArgs > 2) {
6030     ExprResult Arg(TheCall->getArg(2));
6031     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6032       Context.getSizeType(), false);
6033     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6034     if (Arg.isInvalid()) return true;
6035     TheCall->setArg(2, Arg.get());
6036   }
6037 
6038   return false;
6039 }
6040 
6041 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6042   unsigned BuiltinID =
6043       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6044   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6045 
6046   unsigned NumArgs = TheCall->getNumArgs();
6047   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6048   if (NumArgs < NumRequiredArgs) {
6049     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6050            << 0 /* function call */ << NumRequiredArgs << NumArgs
6051            << TheCall->getSourceRange();
6052   }
6053   if (NumArgs >= NumRequiredArgs + 0x100) {
6054     return Diag(TheCall->getEndLoc(),
6055                 diag::err_typecheck_call_too_many_args_at_most)
6056            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6057            << TheCall->getSourceRange();
6058   }
6059   unsigned i = 0;
6060 
6061   // For formatting call, check buffer arg.
6062   if (!IsSizeCall) {
6063     ExprResult Arg(TheCall->getArg(i));
6064     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6065         Context, Context.VoidPtrTy, false);
6066     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6067     if (Arg.isInvalid())
6068       return true;
6069     TheCall->setArg(i, Arg.get());
6070     i++;
6071   }
6072 
6073   // Check string literal arg.
6074   unsigned FormatIdx = i;
6075   {
6076     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6077     if (Arg.isInvalid())
6078       return true;
6079     TheCall->setArg(i, Arg.get());
6080     i++;
6081   }
6082 
6083   // Make sure variadic args are scalar.
6084   unsigned FirstDataArg = i;
6085   while (i < NumArgs) {
6086     ExprResult Arg = DefaultVariadicArgumentPromotion(
6087         TheCall->getArg(i), VariadicFunction, nullptr);
6088     if (Arg.isInvalid())
6089       return true;
6090     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6091     if (ArgSize.getQuantity() >= 0x100) {
6092       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6093              << i << (int)ArgSize.getQuantity() << 0xff
6094              << TheCall->getSourceRange();
6095     }
6096     TheCall->setArg(i, Arg.get());
6097     i++;
6098   }
6099 
6100   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6101   // call to avoid duplicate diagnostics.
6102   if (!IsSizeCall) {
6103     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6104     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6105     bool Success = CheckFormatArguments(
6106         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6107         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6108         CheckedVarArgs);
6109     if (!Success)
6110       return true;
6111   }
6112 
6113   if (IsSizeCall) {
6114     TheCall->setType(Context.getSizeType());
6115   } else {
6116     TheCall->setType(Context.VoidPtrTy);
6117   }
6118   return false;
6119 }
6120 
6121 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6122 /// TheCall is a constant expression.
6123 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6124                                   llvm::APSInt &Result) {
6125   Expr *Arg = TheCall->getArg(ArgNum);
6126   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6127   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6128 
6129   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6130 
6131   if (!Arg->isIntegerConstantExpr(Result, Context))
6132     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6133            << FDecl->getDeclName() << Arg->getSourceRange();
6134 
6135   return false;
6136 }
6137 
6138 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6139 /// TheCall is a constant expression in the range [Low, High].
6140 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6141                                        int Low, int High, bool RangeIsError) {
6142   if (isConstantEvaluated())
6143     return false;
6144   llvm::APSInt Result;
6145 
6146   // We can't check the value of a dependent argument.
6147   Expr *Arg = TheCall->getArg(ArgNum);
6148   if (Arg->isTypeDependent() || Arg->isValueDependent())
6149     return false;
6150 
6151   // Check constant-ness first.
6152   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6153     return true;
6154 
6155   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6156     if (RangeIsError)
6157       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6158              << Result.toString(10) << Low << High << Arg->getSourceRange();
6159     else
6160       // Defer the warning until we know if the code will be emitted so that
6161       // dead code can ignore this.
6162       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6163                           PDiag(diag::warn_argument_invalid_range)
6164                               << Result.toString(10) << Low << High
6165                               << Arg->getSourceRange());
6166   }
6167 
6168   return false;
6169 }
6170 
6171 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6172 /// TheCall is a constant expression is a multiple of Num..
6173 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6174                                           unsigned Num) {
6175   llvm::APSInt Result;
6176 
6177   // We can't check the value of a dependent argument.
6178   Expr *Arg = TheCall->getArg(ArgNum);
6179   if (Arg->isTypeDependent() || Arg->isValueDependent())
6180     return false;
6181 
6182   // Check constant-ness first.
6183   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6184     return true;
6185 
6186   if (Result.getSExtValue() % Num != 0)
6187     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6188            << Num << Arg->getSourceRange();
6189 
6190   return false;
6191 }
6192 
6193 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6194 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6195   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6196     if (checkArgCount(*this, TheCall, 2))
6197       return true;
6198     Expr *Arg0 = TheCall->getArg(0);
6199     Expr *Arg1 = TheCall->getArg(1);
6200 
6201     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6202     if (FirstArg.isInvalid())
6203       return true;
6204     QualType FirstArgType = FirstArg.get()->getType();
6205     if (!FirstArgType->isAnyPointerType())
6206       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6207                << "first" << FirstArgType << Arg0->getSourceRange();
6208     TheCall->setArg(0, FirstArg.get());
6209 
6210     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6211     if (SecArg.isInvalid())
6212       return true;
6213     QualType SecArgType = SecArg.get()->getType();
6214     if (!SecArgType->isIntegerType())
6215       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6216                << "second" << SecArgType << Arg1->getSourceRange();
6217 
6218     // Derive the return type from the pointer argument.
6219     TheCall->setType(FirstArgType);
6220     return false;
6221   }
6222 
6223   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6224     if (checkArgCount(*this, TheCall, 2))
6225       return true;
6226 
6227     Expr *Arg0 = TheCall->getArg(0);
6228     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6229     if (FirstArg.isInvalid())
6230       return true;
6231     QualType FirstArgType = FirstArg.get()->getType();
6232     if (!FirstArgType->isAnyPointerType())
6233       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6234                << "first" << FirstArgType << Arg0->getSourceRange();
6235     TheCall->setArg(0, FirstArg.get());
6236 
6237     // Derive the return type from the pointer argument.
6238     TheCall->setType(FirstArgType);
6239 
6240     // Second arg must be an constant in range [0,15]
6241     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6242   }
6243 
6244   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6245     if (checkArgCount(*this, TheCall, 2))
6246       return true;
6247     Expr *Arg0 = TheCall->getArg(0);
6248     Expr *Arg1 = TheCall->getArg(1);
6249 
6250     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6251     if (FirstArg.isInvalid())
6252       return true;
6253     QualType FirstArgType = FirstArg.get()->getType();
6254     if (!FirstArgType->isAnyPointerType())
6255       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6256                << "first" << FirstArgType << Arg0->getSourceRange();
6257 
6258     QualType SecArgType = Arg1->getType();
6259     if (!SecArgType->isIntegerType())
6260       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6261                << "second" << SecArgType << Arg1->getSourceRange();
6262     TheCall->setType(Context.IntTy);
6263     return false;
6264   }
6265 
6266   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6267       BuiltinID == AArch64::BI__builtin_arm_stg) {
6268     if (checkArgCount(*this, TheCall, 1))
6269       return true;
6270     Expr *Arg0 = TheCall->getArg(0);
6271     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6272     if (FirstArg.isInvalid())
6273       return true;
6274 
6275     QualType FirstArgType = FirstArg.get()->getType();
6276     if (!FirstArgType->isAnyPointerType())
6277       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6278                << "first" << FirstArgType << Arg0->getSourceRange();
6279     TheCall->setArg(0, FirstArg.get());
6280 
6281     // Derive the return type from the pointer argument.
6282     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6283       TheCall->setType(FirstArgType);
6284     return false;
6285   }
6286 
6287   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6288     Expr *ArgA = TheCall->getArg(0);
6289     Expr *ArgB = TheCall->getArg(1);
6290 
6291     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6292     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6293 
6294     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6295       return true;
6296 
6297     QualType ArgTypeA = ArgExprA.get()->getType();
6298     QualType ArgTypeB = ArgExprB.get()->getType();
6299 
6300     auto isNull = [&] (Expr *E) -> bool {
6301       return E->isNullPointerConstant(
6302                         Context, Expr::NPC_ValueDependentIsNotNull); };
6303 
6304     // argument should be either a pointer or null
6305     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6306       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6307         << "first" << ArgTypeA << ArgA->getSourceRange();
6308 
6309     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6310       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6311         << "second" << ArgTypeB << ArgB->getSourceRange();
6312 
6313     // Ensure Pointee types are compatible
6314     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6315         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6316       QualType pointeeA = ArgTypeA->getPointeeType();
6317       QualType pointeeB = ArgTypeB->getPointeeType();
6318       if (!Context.typesAreCompatible(
6319              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6320              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6321         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6322           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6323           << ArgB->getSourceRange();
6324       }
6325     }
6326 
6327     // at least one argument should be pointer type
6328     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6329       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6330         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6331 
6332     if (isNull(ArgA)) // adopt type of the other pointer
6333       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6334 
6335     if (isNull(ArgB))
6336       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6337 
6338     TheCall->setArg(0, ArgExprA.get());
6339     TheCall->setArg(1, ArgExprB.get());
6340     TheCall->setType(Context.LongLongTy);
6341     return false;
6342   }
6343   assert(false && "Unhandled ARM MTE intrinsic");
6344   return true;
6345 }
6346 
6347 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6348 /// TheCall is an ARM/AArch64 special register string literal.
6349 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6350                                     int ArgNum, unsigned ExpectedFieldNum,
6351                                     bool AllowName) {
6352   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6353                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6354                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6355                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6356                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6357                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6358   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6359                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6360                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6361                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6362                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6363                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6364   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6365 
6366   // We can't check the value of a dependent argument.
6367   Expr *Arg = TheCall->getArg(ArgNum);
6368   if (Arg->isTypeDependent() || Arg->isValueDependent())
6369     return false;
6370 
6371   // Check if the argument is a string literal.
6372   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6373     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6374            << Arg->getSourceRange();
6375 
6376   // Check the type of special register given.
6377   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6378   SmallVector<StringRef, 6> Fields;
6379   Reg.split(Fields, ":");
6380 
6381   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6382     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6383            << Arg->getSourceRange();
6384 
6385   // If the string is the name of a register then we cannot check that it is
6386   // valid here but if the string is of one the forms described in ACLE then we
6387   // can check that the supplied fields are integers and within the valid
6388   // ranges.
6389   if (Fields.size() > 1) {
6390     bool FiveFields = Fields.size() == 5;
6391 
6392     bool ValidString = true;
6393     if (IsARMBuiltin) {
6394       ValidString &= Fields[0].startswith_lower("cp") ||
6395                      Fields[0].startswith_lower("p");
6396       if (ValidString)
6397         Fields[0] =
6398           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6399 
6400       ValidString &= Fields[2].startswith_lower("c");
6401       if (ValidString)
6402         Fields[2] = Fields[2].drop_front(1);
6403 
6404       if (FiveFields) {
6405         ValidString &= Fields[3].startswith_lower("c");
6406         if (ValidString)
6407           Fields[3] = Fields[3].drop_front(1);
6408       }
6409     }
6410 
6411     SmallVector<int, 5> Ranges;
6412     if (FiveFields)
6413       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6414     else
6415       Ranges.append({15, 7, 15});
6416 
6417     for (unsigned i=0; i<Fields.size(); ++i) {
6418       int IntField;
6419       ValidString &= !Fields[i].getAsInteger(10, IntField);
6420       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6421     }
6422 
6423     if (!ValidString)
6424       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6425              << Arg->getSourceRange();
6426   } else if (IsAArch64Builtin && Fields.size() == 1) {
6427     // If the register name is one of those that appear in the condition below
6428     // and the special register builtin being used is one of the write builtins,
6429     // then we require that the argument provided for writing to the register
6430     // is an integer constant expression. This is because it will be lowered to
6431     // an MSR (immediate) instruction, so we need to know the immediate at
6432     // compile time.
6433     if (TheCall->getNumArgs() != 2)
6434       return false;
6435 
6436     std::string RegLower = Reg.lower();
6437     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6438         RegLower != "pan" && RegLower != "uao")
6439       return false;
6440 
6441     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6442   }
6443 
6444   return false;
6445 }
6446 
6447 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6448 /// This checks that the target supports __builtin_longjmp and
6449 /// that val is a constant 1.
6450 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6451   if (!Context.getTargetInfo().hasSjLjLowering())
6452     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6453            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6454 
6455   Expr *Arg = TheCall->getArg(1);
6456   llvm::APSInt Result;
6457 
6458   // TODO: This is less than ideal. Overload this to take a value.
6459   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6460     return true;
6461 
6462   if (Result != 1)
6463     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6464            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6465 
6466   return false;
6467 }
6468 
6469 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6470 /// This checks that the target supports __builtin_setjmp.
6471 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6472   if (!Context.getTargetInfo().hasSjLjLowering())
6473     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6474            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6475   return false;
6476 }
6477 
6478 namespace {
6479 
6480 class UncoveredArgHandler {
6481   enum { Unknown = -1, AllCovered = -2 };
6482 
6483   signed FirstUncoveredArg = Unknown;
6484   SmallVector<const Expr *, 4> DiagnosticExprs;
6485 
6486 public:
6487   UncoveredArgHandler() = default;
6488 
6489   bool hasUncoveredArg() const {
6490     return (FirstUncoveredArg >= 0);
6491   }
6492 
6493   unsigned getUncoveredArg() const {
6494     assert(hasUncoveredArg() && "no uncovered argument");
6495     return FirstUncoveredArg;
6496   }
6497 
6498   void setAllCovered() {
6499     // A string has been found with all arguments covered, so clear out
6500     // the diagnostics.
6501     DiagnosticExprs.clear();
6502     FirstUncoveredArg = AllCovered;
6503   }
6504 
6505   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6506     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6507 
6508     // Don't update if a previous string covers all arguments.
6509     if (FirstUncoveredArg == AllCovered)
6510       return;
6511 
6512     // UncoveredArgHandler tracks the highest uncovered argument index
6513     // and with it all the strings that match this index.
6514     if (NewFirstUncoveredArg == FirstUncoveredArg)
6515       DiagnosticExprs.push_back(StrExpr);
6516     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6517       DiagnosticExprs.clear();
6518       DiagnosticExprs.push_back(StrExpr);
6519       FirstUncoveredArg = NewFirstUncoveredArg;
6520     }
6521   }
6522 
6523   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6524 };
6525 
6526 enum StringLiteralCheckType {
6527   SLCT_NotALiteral,
6528   SLCT_UncheckedLiteral,
6529   SLCT_CheckedLiteral
6530 };
6531 
6532 } // namespace
6533 
6534 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6535                                      BinaryOperatorKind BinOpKind,
6536                                      bool AddendIsRight) {
6537   unsigned BitWidth = Offset.getBitWidth();
6538   unsigned AddendBitWidth = Addend.getBitWidth();
6539   // There might be negative interim results.
6540   if (Addend.isUnsigned()) {
6541     Addend = Addend.zext(++AddendBitWidth);
6542     Addend.setIsSigned(true);
6543   }
6544   // Adjust the bit width of the APSInts.
6545   if (AddendBitWidth > BitWidth) {
6546     Offset = Offset.sext(AddendBitWidth);
6547     BitWidth = AddendBitWidth;
6548   } else if (BitWidth > AddendBitWidth) {
6549     Addend = Addend.sext(BitWidth);
6550   }
6551 
6552   bool Ov = false;
6553   llvm::APSInt ResOffset = Offset;
6554   if (BinOpKind == BO_Add)
6555     ResOffset = Offset.sadd_ov(Addend, Ov);
6556   else {
6557     assert(AddendIsRight && BinOpKind == BO_Sub &&
6558            "operator must be add or sub with addend on the right");
6559     ResOffset = Offset.ssub_ov(Addend, Ov);
6560   }
6561 
6562   // We add an offset to a pointer here so we should support an offset as big as
6563   // possible.
6564   if (Ov) {
6565     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6566            "index (intermediate) result too big");
6567     Offset = Offset.sext(2 * BitWidth);
6568     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6569     return;
6570   }
6571 
6572   Offset = ResOffset;
6573 }
6574 
6575 namespace {
6576 
6577 // This is a wrapper class around StringLiteral to support offsetted string
6578 // literals as format strings. It takes the offset into account when returning
6579 // the string and its length or the source locations to display notes correctly.
6580 class FormatStringLiteral {
6581   const StringLiteral *FExpr;
6582   int64_t Offset;
6583 
6584  public:
6585   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6586       : FExpr(fexpr), Offset(Offset) {}
6587 
6588   StringRef getString() const {
6589     return FExpr->getString().drop_front(Offset);
6590   }
6591 
6592   unsigned getByteLength() const {
6593     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6594   }
6595 
6596   unsigned getLength() const { return FExpr->getLength() - Offset; }
6597   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6598 
6599   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6600 
6601   QualType getType() const { return FExpr->getType(); }
6602 
6603   bool isAscii() const { return FExpr->isAscii(); }
6604   bool isWide() const { return FExpr->isWide(); }
6605   bool isUTF8() const { return FExpr->isUTF8(); }
6606   bool isUTF16() const { return FExpr->isUTF16(); }
6607   bool isUTF32() const { return FExpr->isUTF32(); }
6608   bool isPascal() const { return FExpr->isPascal(); }
6609 
6610   SourceLocation getLocationOfByte(
6611       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6612       const TargetInfo &Target, unsigned *StartToken = nullptr,
6613       unsigned *StartTokenByteOffset = nullptr) const {
6614     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6615                                     StartToken, StartTokenByteOffset);
6616   }
6617 
6618   SourceLocation getBeginLoc() const LLVM_READONLY {
6619     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6620   }
6621 
6622   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6623 };
6624 
6625 }  // namespace
6626 
6627 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6628                               const Expr *OrigFormatExpr,
6629                               ArrayRef<const Expr *> Args,
6630                               bool HasVAListArg, unsigned format_idx,
6631                               unsigned firstDataArg,
6632                               Sema::FormatStringType Type,
6633                               bool inFunctionCall,
6634                               Sema::VariadicCallType CallType,
6635                               llvm::SmallBitVector &CheckedVarArgs,
6636                               UncoveredArgHandler &UncoveredArg,
6637                               bool IgnoreStringsWithoutSpecifiers);
6638 
6639 // Determine if an expression is a string literal or constant string.
6640 // If this function returns false on the arguments to a function expecting a
6641 // format string, we will usually need to emit a warning.
6642 // True string literals are then checked by CheckFormatString.
6643 static StringLiteralCheckType
6644 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6645                       bool HasVAListArg, unsigned format_idx,
6646                       unsigned firstDataArg, Sema::FormatStringType Type,
6647                       Sema::VariadicCallType CallType, bool InFunctionCall,
6648                       llvm::SmallBitVector &CheckedVarArgs,
6649                       UncoveredArgHandler &UncoveredArg,
6650                       llvm::APSInt Offset,
6651                       bool IgnoreStringsWithoutSpecifiers = false) {
6652   if (S.isConstantEvaluated())
6653     return SLCT_NotALiteral;
6654  tryAgain:
6655   assert(Offset.isSigned() && "invalid offset");
6656 
6657   if (E->isTypeDependent() || E->isValueDependent())
6658     return SLCT_NotALiteral;
6659 
6660   E = E->IgnoreParenCasts();
6661 
6662   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6663     // Technically -Wformat-nonliteral does not warn about this case.
6664     // The behavior of printf and friends in this case is implementation
6665     // dependent.  Ideally if the format string cannot be null then
6666     // it should have a 'nonnull' attribute in the function prototype.
6667     return SLCT_UncheckedLiteral;
6668 
6669   switch (E->getStmtClass()) {
6670   case Stmt::BinaryConditionalOperatorClass:
6671   case Stmt::ConditionalOperatorClass: {
6672     // The expression is a literal if both sub-expressions were, and it was
6673     // completely checked only if both sub-expressions were checked.
6674     const AbstractConditionalOperator *C =
6675         cast<AbstractConditionalOperator>(E);
6676 
6677     // Determine whether it is necessary to check both sub-expressions, for
6678     // example, because the condition expression is a constant that can be
6679     // evaluated at compile time.
6680     bool CheckLeft = true, CheckRight = true;
6681 
6682     bool Cond;
6683     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6684                                                  S.isConstantEvaluated())) {
6685       if (Cond)
6686         CheckRight = false;
6687       else
6688         CheckLeft = false;
6689     }
6690 
6691     // We need to maintain the offsets for the right and the left hand side
6692     // separately to check if every possible indexed expression is a valid
6693     // string literal. They might have different offsets for different string
6694     // literals in the end.
6695     StringLiteralCheckType Left;
6696     if (!CheckLeft)
6697       Left = SLCT_UncheckedLiteral;
6698     else {
6699       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6700                                    HasVAListArg, format_idx, firstDataArg,
6701                                    Type, CallType, InFunctionCall,
6702                                    CheckedVarArgs, UncoveredArg, Offset,
6703                                    IgnoreStringsWithoutSpecifiers);
6704       if (Left == SLCT_NotALiteral || !CheckRight) {
6705         return Left;
6706       }
6707     }
6708 
6709     StringLiteralCheckType Right = checkFormatStringExpr(
6710         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6711         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6712         IgnoreStringsWithoutSpecifiers);
6713 
6714     return (CheckLeft && Left < Right) ? Left : Right;
6715   }
6716 
6717   case Stmt::ImplicitCastExprClass:
6718     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6719     goto tryAgain;
6720 
6721   case Stmt::OpaqueValueExprClass:
6722     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6723       E = src;
6724       goto tryAgain;
6725     }
6726     return SLCT_NotALiteral;
6727 
6728   case Stmt::PredefinedExprClass:
6729     // While __func__, etc., are technically not string literals, they
6730     // cannot contain format specifiers and thus are not a security
6731     // liability.
6732     return SLCT_UncheckedLiteral;
6733 
6734   case Stmt::DeclRefExprClass: {
6735     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6736 
6737     // As an exception, do not flag errors for variables binding to
6738     // const string literals.
6739     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6740       bool isConstant = false;
6741       QualType T = DR->getType();
6742 
6743       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6744         isConstant = AT->getElementType().isConstant(S.Context);
6745       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6746         isConstant = T.isConstant(S.Context) &&
6747                      PT->getPointeeType().isConstant(S.Context);
6748       } else if (T->isObjCObjectPointerType()) {
6749         // In ObjC, there is usually no "const ObjectPointer" type,
6750         // so don't check if the pointee type is constant.
6751         isConstant = T.isConstant(S.Context);
6752       }
6753 
6754       if (isConstant) {
6755         if (const Expr *Init = VD->getAnyInitializer()) {
6756           // Look through initializers like const char c[] = { "foo" }
6757           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6758             if (InitList->isStringLiteralInit())
6759               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6760           }
6761           return checkFormatStringExpr(S, Init, Args,
6762                                        HasVAListArg, format_idx,
6763                                        firstDataArg, Type, CallType,
6764                                        /*InFunctionCall*/ false, CheckedVarArgs,
6765                                        UncoveredArg, Offset);
6766         }
6767       }
6768 
6769       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6770       // special check to see if the format string is a function parameter
6771       // of the function calling the printf function.  If the function
6772       // has an attribute indicating it is a printf-like function, then we
6773       // should suppress warnings concerning non-literals being used in a call
6774       // to a vprintf function.  For example:
6775       //
6776       // void
6777       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6778       //      va_list ap;
6779       //      va_start(ap, fmt);
6780       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6781       //      ...
6782       // }
6783       if (HasVAListArg) {
6784         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6785           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6786             int PVIndex = PV->getFunctionScopeIndex() + 1;
6787             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6788               // adjust for implicit parameter
6789               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6790                 if (MD->isInstance())
6791                   ++PVIndex;
6792               // We also check if the formats are compatible.
6793               // We can't pass a 'scanf' string to a 'printf' function.
6794               if (PVIndex == PVFormat->getFormatIdx() &&
6795                   Type == S.GetFormatStringType(PVFormat))
6796                 return SLCT_UncheckedLiteral;
6797             }
6798           }
6799         }
6800       }
6801     }
6802 
6803     return SLCT_NotALiteral;
6804   }
6805 
6806   case Stmt::CallExprClass:
6807   case Stmt::CXXMemberCallExprClass: {
6808     const CallExpr *CE = cast<CallExpr>(E);
6809     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6810       bool IsFirst = true;
6811       StringLiteralCheckType CommonResult;
6812       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6813         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6814         StringLiteralCheckType Result = checkFormatStringExpr(
6815             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6816             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6817             IgnoreStringsWithoutSpecifiers);
6818         if (IsFirst) {
6819           CommonResult = Result;
6820           IsFirst = false;
6821         }
6822       }
6823       if (!IsFirst)
6824         return CommonResult;
6825 
6826       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6827         unsigned BuiltinID = FD->getBuiltinID();
6828         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6829             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6830           const Expr *Arg = CE->getArg(0);
6831           return checkFormatStringExpr(S, Arg, Args,
6832                                        HasVAListArg, format_idx,
6833                                        firstDataArg, Type, CallType,
6834                                        InFunctionCall, CheckedVarArgs,
6835                                        UncoveredArg, Offset,
6836                                        IgnoreStringsWithoutSpecifiers);
6837         }
6838       }
6839     }
6840 
6841     return SLCT_NotALiteral;
6842   }
6843   case Stmt::ObjCMessageExprClass: {
6844     const auto *ME = cast<ObjCMessageExpr>(E);
6845     if (const auto *MD = ME->getMethodDecl()) {
6846       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6847         // As a special case heuristic, if we're using the method -[NSBundle
6848         // localizedStringForKey:value:table:], ignore any key strings that lack
6849         // format specifiers. The idea is that if the key doesn't have any
6850         // format specifiers then its probably just a key to map to the
6851         // localized strings. If it does have format specifiers though, then its
6852         // likely that the text of the key is the format string in the
6853         // programmer's language, and should be checked.
6854         const ObjCInterfaceDecl *IFace;
6855         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6856             IFace->getIdentifier()->isStr("NSBundle") &&
6857             MD->getSelector().isKeywordSelector(
6858                 {"localizedStringForKey", "value", "table"})) {
6859           IgnoreStringsWithoutSpecifiers = true;
6860         }
6861 
6862         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6863         return checkFormatStringExpr(
6864             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6865             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6866             IgnoreStringsWithoutSpecifiers);
6867       }
6868     }
6869 
6870     return SLCT_NotALiteral;
6871   }
6872   case Stmt::ObjCStringLiteralClass:
6873   case Stmt::StringLiteralClass: {
6874     const StringLiteral *StrE = nullptr;
6875 
6876     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6877       StrE = ObjCFExpr->getString();
6878     else
6879       StrE = cast<StringLiteral>(E);
6880 
6881     if (StrE) {
6882       if (Offset.isNegative() || Offset > StrE->getLength()) {
6883         // TODO: It would be better to have an explicit warning for out of
6884         // bounds literals.
6885         return SLCT_NotALiteral;
6886       }
6887       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6888       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6889                         firstDataArg, Type, InFunctionCall, CallType,
6890                         CheckedVarArgs, UncoveredArg,
6891                         IgnoreStringsWithoutSpecifiers);
6892       return SLCT_CheckedLiteral;
6893     }
6894 
6895     return SLCT_NotALiteral;
6896   }
6897   case Stmt::BinaryOperatorClass: {
6898     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6899 
6900     // A string literal + an int offset is still a string literal.
6901     if (BinOp->isAdditiveOp()) {
6902       Expr::EvalResult LResult, RResult;
6903 
6904       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6905           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6906       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6907           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6908 
6909       if (LIsInt != RIsInt) {
6910         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6911 
6912         if (LIsInt) {
6913           if (BinOpKind == BO_Add) {
6914             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6915             E = BinOp->getRHS();
6916             goto tryAgain;
6917           }
6918         } else {
6919           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6920           E = BinOp->getLHS();
6921           goto tryAgain;
6922         }
6923       }
6924     }
6925 
6926     return SLCT_NotALiteral;
6927   }
6928   case Stmt::UnaryOperatorClass: {
6929     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6930     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6931     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6932       Expr::EvalResult IndexResult;
6933       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6934                                        Expr::SE_NoSideEffects,
6935                                        S.isConstantEvaluated())) {
6936         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6937                    /*RHS is int*/ true);
6938         E = ASE->getBase();
6939         goto tryAgain;
6940       }
6941     }
6942 
6943     return SLCT_NotALiteral;
6944   }
6945 
6946   default:
6947     return SLCT_NotALiteral;
6948   }
6949 }
6950 
6951 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6952   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6953       .Case("scanf", FST_Scanf)
6954       .Cases("printf", "printf0", FST_Printf)
6955       .Cases("NSString", "CFString", FST_NSString)
6956       .Case("strftime", FST_Strftime)
6957       .Case("strfmon", FST_Strfmon)
6958       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6959       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6960       .Case("os_trace", FST_OSLog)
6961       .Case("os_log", FST_OSLog)
6962       .Default(FST_Unknown);
6963 }
6964 
6965 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6966 /// functions) for correct use of format strings.
6967 /// Returns true if a format string has been fully checked.
6968 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6969                                 ArrayRef<const Expr *> Args,
6970                                 bool IsCXXMember,
6971                                 VariadicCallType CallType,
6972                                 SourceLocation Loc, SourceRange Range,
6973                                 llvm::SmallBitVector &CheckedVarArgs) {
6974   FormatStringInfo FSI;
6975   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6976     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6977                                 FSI.FirstDataArg, GetFormatStringType(Format),
6978                                 CallType, Loc, Range, CheckedVarArgs);
6979   return false;
6980 }
6981 
6982 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6983                                 bool HasVAListArg, unsigned format_idx,
6984                                 unsigned firstDataArg, FormatStringType Type,
6985                                 VariadicCallType CallType,
6986                                 SourceLocation Loc, SourceRange Range,
6987                                 llvm::SmallBitVector &CheckedVarArgs) {
6988   // CHECK: printf/scanf-like function is called with no format string.
6989   if (format_idx >= Args.size()) {
6990     Diag(Loc, diag::warn_missing_format_string) << Range;
6991     return false;
6992   }
6993 
6994   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6995 
6996   // CHECK: format string is not a string literal.
6997   //
6998   // Dynamically generated format strings are difficult to
6999   // automatically vet at compile time.  Requiring that format strings
7000   // are string literals: (1) permits the checking of format strings by
7001   // the compiler and thereby (2) can practically remove the source of
7002   // many format string exploits.
7003 
7004   // Format string can be either ObjC string (e.g. @"%d") or
7005   // C string (e.g. "%d")
7006   // ObjC string uses the same format specifiers as C string, so we can use
7007   // the same format string checking logic for both ObjC and C strings.
7008   UncoveredArgHandler UncoveredArg;
7009   StringLiteralCheckType CT =
7010       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7011                             format_idx, firstDataArg, Type, CallType,
7012                             /*IsFunctionCall*/ true, CheckedVarArgs,
7013                             UncoveredArg,
7014                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7015 
7016   // Generate a diagnostic where an uncovered argument is detected.
7017   if (UncoveredArg.hasUncoveredArg()) {
7018     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7019     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7020     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7021   }
7022 
7023   if (CT != SLCT_NotALiteral)
7024     // Literal format string found, check done!
7025     return CT == SLCT_CheckedLiteral;
7026 
7027   // Strftime is particular as it always uses a single 'time' argument,
7028   // so it is safe to pass a non-literal string.
7029   if (Type == FST_Strftime)
7030     return false;
7031 
7032   // Do not emit diag when the string param is a macro expansion and the
7033   // format is either NSString or CFString. This is a hack to prevent
7034   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7035   // which are usually used in place of NS and CF string literals.
7036   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7037   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7038     return false;
7039 
7040   // If there are no arguments specified, warn with -Wformat-security, otherwise
7041   // warn only with -Wformat-nonliteral.
7042   if (Args.size() == firstDataArg) {
7043     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7044       << OrigFormatExpr->getSourceRange();
7045     switch (Type) {
7046     default:
7047       break;
7048     case FST_Kprintf:
7049     case FST_FreeBSDKPrintf:
7050     case FST_Printf:
7051       Diag(FormatLoc, diag::note_format_security_fixit)
7052         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7053       break;
7054     case FST_NSString:
7055       Diag(FormatLoc, diag::note_format_security_fixit)
7056         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7057       break;
7058     }
7059   } else {
7060     Diag(FormatLoc, diag::warn_format_nonliteral)
7061       << OrigFormatExpr->getSourceRange();
7062   }
7063   return false;
7064 }
7065 
7066 namespace {
7067 
7068 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7069 protected:
7070   Sema &S;
7071   const FormatStringLiteral *FExpr;
7072   const Expr *OrigFormatExpr;
7073   const Sema::FormatStringType FSType;
7074   const unsigned FirstDataArg;
7075   const unsigned NumDataArgs;
7076   const char *Beg; // Start of format string.
7077   const bool HasVAListArg;
7078   ArrayRef<const Expr *> Args;
7079   unsigned FormatIdx;
7080   llvm::SmallBitVector CoveredArgs;
7081   bool usesPositionalArgs = false;
7082   bool atFirstArg = true;
7083   bool inFunctionCall;
7084   Sema::VariadicCallType CallType;
7085   llvm::SmallBitVector &CheckedVarArgs;
7086   UncoveredArgHandler &UncoveredArg;
7087 
7088 public:
7089   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7090                      const Expr *origFormatExpr,
7091                      const Sema::FormatStringType type, unsigned firstDataArg,
7092                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7093                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7094                      bool inFunctionCall, Sema::VariadicCallType callType,
7095                      llvm::SmallBitVector &CheckedVarArgs,
7096                      UncoveredArgHandler &UncoveredArg)
7097       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7098         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7099         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7100         inFunctionCall(inFunctionCall), CallType(callType),
7101         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7102     CoveredArgs.resize(numDataArgs);
7103     CoveredArgs.reset();
7104   }
7105 
7106   void DoneProcessing();
7107 
7108   void HandleIncompleteSpecifier(const char *startSpecifier,
7109                                  unsigned specifierLen) override;
7110 
7111   void HandleInvalidLengthModifier(
7112                            const analyze_format_string::FormatSpecifier &FS,
7113                            const analyze_format_string::ConversionSpecifier &CS,
7114                            const char *startSpecifier, unsigned specifierLen,
7115                            unsigned DiagID);
7116 
7117   void HandleNonStandardLengthModifier(
7118                     const analyze_format_string::FormatSpecifier &FS,
7119                     const char *startSpecifier, unsigned specifierLen);
7120 
7121   void HandleNonStandardConversionSpecifier(
7122                     const analyze_format_string::ConversionSpecifier &CS,
7123                     const char *startSpecifier, unsigned specifierLen);
7124 
7125   void HandlePosition(const char *startPos, unsigned posLen) override;
7126 
7127   void HandleInvalidPosition(const char *startSpecifier,
7128                              unsigned specifierLen,
7129                              analyze_format_string::PositionContext p) override;
7130 
7131   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7132 
7133   void HandleNullChar(const char *nullCharacter) override;
7134 
7135   template <typename Range>
7136   static void
7137   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7138                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7139                        bool IsStringLocation, Range StringRange,
7140                        ArrayRef<FixItHint> Fixit = None);
7141 
7142 protected:
7143   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7144                                         const char *startSpec,
7145                                         unsigned specifierLen,
7146                                         const char *csStart, unsigned csLen);
7147 
7148   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7149                                          const char *startSpec,
7150                                          unsigned specifierLen);
7151 
7152   SourceRange getFormatStringRange();
7153   CharSourceRange getSpecifierRange(const char *startSpecifier,
7154                                     unsigned specifierLen);
7155   SourceLocation getLocationOfByte(const char *x);
7156 
7157   const Expr *getDataArg(unsigned i) const;
7158 
7159   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7160                     const analyze_format_string::ConversionSpecifier &CS,
7161                     const char *startSpecifier, unsigned specifierLen,
7162                     unsigned argIndex);
7163 
7164   template <typename Range>
7165   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7166                             bool IsStringLocation, Range StringRange,
7167                             ArrayRef<FixItHint> Fixit = None);
7168 };
7169 
7170 } // namespace
7171 
7172 SourceRange CheckFormatHandler::getFormatStringRange() {
7173   return OrigFormatExpr->getSourceRange();
7174 }
7175 
7176 CharSourceRange CheckFormatHandler::
7177 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7178   SourceLocation Start = getLocationOfByte(startSpecifier);
7179   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7180 
7181   // Advance the end SourceLocation by one due to half-open ranges.
7182   End = End.getLocWithOffset(1);
7183 
7184   return CharSourceRange::getCharRange(Start, End);
7185 }
7186 
7187 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7188   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7189                                   S.getLangOpts(), S.Context.getTargetInfo());
7190 }
7191 
7192 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7193                                                    unsigned specifierLen){
7194   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7195                        getLocationOfByte(startSpecifier),
7196                        /*IsStringLocation*/true,
7197                        getSpecifierRange(startSpecifier, specifierLen));
7198 }
7199 
7200 void CheckFormatHandler::HandleInvalidLengthModifier(
7201     const analyze_format_string::FormatSpecifier &FS,
7202     const analyze_format_string::ConversionSpecifier &CS,
7203     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7204   using namespace analyze_format_string;
7205 
7206   const LengthModifier &LM = FS.getLengthModifier();
7207   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7208 
7209   // See if we know how to fix this length modifier.
7210   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7211   if (FixedLM) {
7212     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7213                          getLocationOfByte(LM.getStart()),
7214                          /*IsStringLocation*/true,
7215                          getSpecifierRange(startSpecifier, specifierLen));
7216 
7217     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7218       << FixedLM->toString()
7219       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7220 
7221   } else {
7222     FixItHint Hint;
7223     if (DiagID == diag::warn_format_nonsensical_length)
7224       Hint = FixItHint::CreateRemoval(LMRange);
7225 
7226     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7227                          getLocationOfByte(LM.getStart()),
7228                          /*IsStringLocation*/true,
7229                          getSpecifierRange(startSpecifier, specifierLen),
7230                          Hint);
7231   }
7232 }
7233 
7234 void CheckFormatHandler::HandleNonStandardLengthModifier(
7235     const analyze_format_string::FormatSpecifier &FS,
7236     const char *startSpecifier, unsigned specifierLen) {
7237   using namespace analyze_format_string;
7238 
7239   const LengthModifier &LM = FS.getLengthModifier();
7240   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7241 
7242   // See if we know how to fix this length modifier.
7243   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7244   if (FixedLM) {
7245     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7246                            << LM.toString() << 0,
7247                          getLocationOfByte(LM.getStart()),
7248                          /*IsStringLocation*/true,
7249                          getSpecifierRange(startSpecifier, specifierLen));
7250 
7251     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7252       << FixedLM->toString()
7253       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7254 
7255   } else {
7256     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7257                            << LM.toString() << 0,
7258                          getLocationOfByte(LM.getStart()),
7259                          /*IsStringLocation*/true,
7260                          getSpecifierRange(startSpecifier, specifierLen));
7261   }
7262 }
7263 
7264 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7265     const analyze_format_string::ConversionSpecifier &CS,
7266     const char *startSpecifier, unsigned specifierLen) {
7267   using namespace analyze_format_string;
7268 
7269   // See if we know how to fix this conversion specifier.
7270   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7271   if (FixedCS) {
7272     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7273                           << CS.toString() << /*conversion specifier*/1,
7274                          getLocationOfByte(CS.getStart()),
7275                          /*IsStringLocation*/true,
7276                          getSpecifierRange(startSpecifier, specifierLen));
7277 
7278     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7279     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7280       << FixedCS->toString()
7281       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7282   } else {
7283     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7284                           << CS.toString() << /*conversion specifier*/1,
7285                          getLocationOfByte(CS.getStart()),
7286                          /*IsStringLocation*/true,
7287                          getSpecifierRange(startSpecifier, specifierLen));
7288   }
7289 }
7290 
7291 void CheckFormatHandler::HandlePosition(const char *startPos,
7292                                         unsigned posLen) {
7293   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7294                                getLocationOfByte(startPos),
7295                                /*IsStringLocation*/true,
7296                                getSpecifierRange(startPos, posLen));
7297 }
7298 
7299 void
7300 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7301                                      analyze_format_string::PositionContext p) {
7302   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7303                          << (unsigned) p,
7304                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7305                        getSpecifierRange(startPos, posLen));
7306 }
7307 
7308 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7309                                             unsigned posLen) {
7310   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7311                                getLocationOfByte(startPos),
7312                                /*IsStringLocation*/true,
7313                                getSpecifierRange(startPos, posLen));
7314 }
7315 
7316 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7317   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7318     // The presence of a null character is likely an error.
7319     EmitFormatDiagnostic(
7320       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7321       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7322       getFormatStringRange());
7323   }
7324 }
7325 
7326 // Note that this may return NULL if there was an error parsing or building
7327 // one of the argument expressions.
7328 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7329   return Args[FirstDataArg + i];
7330 }
7331 
7332 void CheckFormatHandler::DoneProcessing() {
7333   // Does the number of data arguments exceed the number of
7334   // format conversions in the format string?
7335   if (!HasVAListArg) {
7336       // Find any arguments that weren't covered.
7337     CoveredArgs.flip();
7338     signed notCoveredArg = CoveredArgs.find_first();
7339     if (notCoveredArg >= 0) {
7340       assert((unsigned)notCoveredArg < NumDataArgs);
7341       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7342     } else {
7343       UncoveredArg.setAllCovered();
7344     }
7345   }
7346 }
7347 
7348 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7349                                    const Expr *ArgExpr) {
7350   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7351          "Invalid state");
7352 
7353   if (!ArgExpr)
7354     return;
7355 
7356   SourceLocation Loc = ArgExpr->getBeginLoc();
7357 
7358   if (S.getSourceManager().isInSystemMacro(Loc))
7359     return;
7360 
7361   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7362   for (auto E : DiagnosticExprs)
7363     PDiag << E->getSourceRange();
7364 
7365   CheckFormatHandler::EmitFormatDiagnostic(
7366                                   S, IsFunctionCall, DiagnosticExprs[0],
7367                                   PDiag, Loc, /*IsStringLocation*/false,
7368                                   DiagnosticExprs[0]->getSourceRange());
7369 }
7370 
7371 bool
7372 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7373                                                      SourceLocation Loc,
7374                                                      const char *startSpec,
7375                                                      unsigned specifierLen,
7376                                                      const char *csStart,
7377                                                      unsigned csLen) {
7378   bool keepGoing = true;
7379   if (argIndex < NumDataArgs) {
7380     // Consider the argument coverered, even though the specifier doesn't
7381     // make sense.
7382     CoveredArgs.set(argIndex);
7383   }
7384   else {
7385     // If argIndex exceeds the number of data arguments we
7386     // don't issue a warning because that is just a cascade of warnings (and
7387     // they may have intended '%%' anyway). We don't want to continue processing
7388     // the format string after this point, however, as we will like just get
7389     // gibberish when trying to match arguments.
7390     keepGoing = false;
7391   }
7392 
7393   StringRef Specifier(csStart, csLen);
7394 
7395   // If the specifier in non-printable, it could be the first byte of a UTF-8
7396   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7397   // hex value.
7398   std::string CodePointStr;
7399   if (!llvm::sys::locale::isPrint(*csStart)) {
7400     llvm::UTF32 CodePoint;
7401     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7402     const llvm::UTF8 *E =
7403         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7404     llvm::ConversionResult Result =
7405         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7406 
7407     if (Result != llvm::conversionOK) {
7408       unsigned char FirstChar = *csStart;
7409       CodePoint = (llvm::UTF32)FirstChar;
7410     }
7411 
7412     llvm::raw_string_ostream OS(CodePointStr);
7413     if (CodePoint < 256)
7414       OS << "\\x" << llvm::format("%02x", CodePoint);
7415     else if (CodePoint <= 0xFFFF)
7416       OS << "\\u" << llvm::format("%04x", CodePoint);
7417     else
7418       OS << "\\U" << llvm::format("%08x", CodePoint);
7419     OS.flush();
7420     Specifier = CodePointStr;
7421   }
7422 
7423   EmitFormatDiagnostic(
7424       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7425       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7426 
7427   return keepGoing;
7428 }
7429 
7430 void
7431 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7432                                                       const char *startSpec,
7433                                                       unsigned specifierLen) {
7434   EmitFormatDiagnostic(
7435     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7436     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7437 }
7438 
7439 bool
7440 CheckFormatHandler::CheckNumArgs(
7441   const analyze_format_string::FormatSpecifier &FS,
7442   const analyze_format_string::ConversionSpecifier &CS,
7443   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7444 
7445   if (argIndex >= NumDataArgs) {
7446     PartialDiagnostic PDiag = FS.usesPositionalArg()
7447       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7448            << (argIndex+1) << NumDataArgs)
7449       : S.PDiag(diag::warn_printf_insufficient_data_args);
7450     EmitFormatDiagnostic(
7451       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7452       getSpecifierRange(startSpecifier, specifierLen));
7453 
7454     // Since more arguments than conversion tokens are given, by extension
7455     // all arguments are covered, so mark this as so.
7456     UncoveredArg.setAllCovered();
7457     return false;
7458   }
7459   return true;
7460 }
7461 
7462 template<typename Range>
7463 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7464                                               SourceLocation Loc,
7465                                               bool IsStringLocation,
7466                                               Range StringRange,
7467                                               ArrayRef<FixItHint> FixIt) {
7468   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7469                        Loc, IsStringLocation, StringRange, FixIt);
7470 }
7471 
7472 /// If the format string is not within the function call, emit a note
7473 /// so that the function call and string are in diagnostic messages.
7474 ///
7475 /// \param InFunctionCall if true, the format string is within the function
7476 /// call and only one diagnostic message will be produced.  Otherwise, an
7477 /// extra note will be emitted pointing to location of the format string.
7478 ///
7479 /// \param ArgumentExpr the expression that is passed as the format string
7480 /// argument in the function call.  Used for getting locations when two
7481 /// diagnostics are emitted.
7482 ///
7483 /// \param PDiag the callee should already have provided any strings for the
7484 /// diagnostic message.  This function only adds locations and fixits
7485 /// to diagnostics.
7486 ///
7487 /// \param Loc primary location for diagnostic.  If two diagnostics are
7488 /// required, one will be at Loc and a new SourceLocation will be created for
7489 /// the other one.
7490 ///
7491 /// \param IsStringLocation if true, Loc points to the format string should be
7492 /// used for the note.  Otherwise, Loc points to the argument list and will
7493 /// be used with PDiag.
7494 ///
7495 /// \param StringRange some or all of the string to highlight.  This is
7496 /// templated so it can accept either a CharSourceRange or a SourceRange.
7497 ///
7498 /// \param FixIt optional fix it hint for the format string.
7499 template <typename Range>
7500 void CheckFormatHandler::EmitFormatDiagnostic(
7501     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7502     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7503     Range StringRange, ArrayRef<FixItHint> FixIt) {
7504   if (InFunctionCall) {
7505     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7506     D << StringRange;
7507     D << FixIt;
7508   } else {
7509     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7510       << ArgumentExpr->getSourceRange();
7511 
7512     const Sema::SemaDiagnosticBuilder &Note =
7513       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7514              diag::note_format_string_defined);
7515 
7516     Note << StringRange;
7517     Note << FixIt;
7518   }
7519 }
7520 
7521 //===--- CHECK: Printf format string checking ------------------------------===//
7522 
7523 namespace {
7524 
7525 class CheckPrintfHandler : public CheckFormatHandler {
7526 public:
7527   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7528                      const Expr *origFormatExpr,
7529                      const Sema::FormatStringType type, unsigned firstDataArg,
7530                      unsigned numDataArgs, bool isObjC, const char *beg,
7531                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7532                      unsigned formatIdx, bool inFunctionCall,
7533                      Sema::VariadicCallType CallType,
7534                      llvm::SmallBitVector &CheckedVarArgs,
7535                      UncoveredArgHandler &UncoveredArg)
7536       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7537                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7538                            inFunctionCall, CallType, CheckedVarArgs,
7539                            UncoveredArg) {}
7540 
7541   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7542 
7543   /// Returns true if '%@' specifiers are allowed in the format string.
7544   bool allowsObjCArg() const {
7545     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7546            FSType == Sema::FST_OSTrace;
7547   }
7548 
7549   bool HandleInvalidPrintfConversionSpecifier(
7550                                       const analyze_printf::PrintfSpecifier &FS,
7551                                       const char *startSpecifier,
7552                                       unsigned specifierLen) override;
7553 
7554   void handleInvalidMaskType(StringRef MaskType) override;
7555 
7556   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7557                              const char *startSpecifier,
7558                              unsigned specifierLen) override;
7559   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7560                        const char *StartSpecifier,
7561                        unsigned SpecifierLen,
7562                        const Expr *E);
7563 
7564   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7565                     const char *startSpecifier, unsigned specifierLen);
7566   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7567                            const analyze_printf::OptionalAmount &Amt,
7568                            unsigned type,
7569                            const char *startSpecifier, unsigned specifierLen);
7570   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7571                   const analyze_printf::OptionalFlag &flag,
7572                   const char *startSpecifier, unsigned specifierLen);
7573   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7574                          const analyze_printf::OptionalFlag &ignoredFlag,
7575                          const analyze_printf::OptionalFlag &flag,
7576                          const char *startSpecifier, unsigned specifierLen);
7577   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7578                            const Expr *E);
7579 
7580   void HandleEmptyObjCModifierFlag(const char *startFlag,
7581                                    unsigned flagLen) override;
7582 
7583   void HandleInvalidObjCModifierFlag(const char *startFlag,
7584                                             unsigned flagLen) override;
7585 
7586   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7587                                            const char *flagsEnd,
7588                                            const char *conversionPosition)
7589                                              override;
7590 };
7591 
7592 } // namespace
7593 
7594 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7595                                       const analyze_printf::PrintfSpecifier &FS,
7596                                       const char *startSpecifier,
7597                                       unsigned specifierLen) {
7598   const analyze_printf::PrintfConversionSpecifier &CS =
7599     FS.getConversionSpecifier();
7600 
7601   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7602                                           getLocationOfByte(CS.getStart()),
7603                                           startSpecifier, specifierLen,
7604                                           CS.getStart(), CS.getLength());
7605 }
7606 
7607 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7608   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7609 }
7610 
7611 bool CheckPrintfHandler::HandleAmount(
7612                                const analyze_format_string::OptionalAmount &Amt,
7613                                unsigned k, const char *startSpecifier,
7614                                unsigned specifierLen) {
7615   if (Amt.hasDataArgument()) {
7616     if (!HasVAListArg) {
7617       unsigned argIndex = Amt.getArgIndex();
7618       if (argIndex >= NumDataArgs) {
7619         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7620                                << k,
7621                              getLocationOfByte(Amt.getStart()),
7622                              /*IsStringLocation*/true,
7623                              getSpecifierRange(startSpecifier, specifierLen));
7624         // Don't do any more checking.  We will just emit
7625         // spurious errors.
7626         return false;
7627       }
7628 
7629       // Type check the data argument.  It should be an 'int'.
7630       // Although not in conformance with C99, we also allow the argument to be
7631       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7632       // doesn't emit a warning for that case.
7633       CoveredArgs.set(argIndex);
7634       const Expr *Arg = getDataArg(argIndex);
7635       if (!Arg)
7636         return false;
7637 
7638       QualType T = Arg->getType();
7639 
7640       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7641       assert(AT.isValid());
7642 
7643       if (!AT.matchesType(S.Context, T)) {
7644         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7645                                << k << AT.getRepresentativeTypeName(S.Context)
7646                                << T << Arg->getSourceRange(),
7647                              getLocationOfByte(Amt.getStart()),
7648                              /*IsStringLocation*/true,
7649                              getSpecifierRange(startSpecifier, specifierLen));
7650         // Don't do any more checking.  We will just emit
7651         // spurious errors.
7652         return false;
7653       }
7654     }
7655   }
7656   return true;
7657 }
7658 
7659 void CheckPrintfHandler::HandleInvalidAmount(
7660                                       const analyze_printf::PrintfSpecifier &FS,
7661                                       const analyze_printf::OptionalAmount &Amt,
7662                                       unsigned type,
7663                                       const char *startSpecifier,
7664                                       unsigned specifierLen) {
7665   const analyze_printf::PrintfConversionSpecifier &CS =
7666     FS.getConversionSpecifier();
7667 
7668   FixItHint fixit =
7669     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7670       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7671                                  Amt.getConstantLength()))
7672       : FixItHint();
7673 
7674   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7675                          << type << CS.toString(),
7676                        getLocationOfByte(Amt.getStart()),
7677                        /*IsStringLocation*/true,
7678                        getSpecifierRange(startSpecifier, specifierLen),
7679                        fixit);
7680 }
7681 
7682 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7683                                     const analyze_printf::OptionalFlag &flag,
7684                                     const char *startSpecifier,
7685                                     unsigned specifierLen) {
7686   // Warn about pointless flag with a fixit removal.
7687   const analyze_printf::PrintfConversionSpecifier &CS =
7688     FS.getConversionSpecifier();
7689   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7690                          << flag.toString() << CS.toString(),
7691                        getLocationOfByte(flag.getPosition()),
7692                        /*IsStringLocation*/true,
7693                        getSpecifierRange(startSpecifier, specifierLen),
7694                        FixItHint::CreateRemoval(
7695                          getSpecifierRange(flag.getPosition(), 1)));
7696 }
7697 
7698 void CheckPrintfHandler::HandleIgnoredFlag(
7699                                 const analyze_printf::PrintfSpecifier &FS,
7700                                 const analyze_printf::OptionalFlag &ignoredFlag,
7701                                 const analyze_printf::OptionalFlag &flag,
7702                                 const char *startSpecifier,
7703                                 unsigned specifierLen) {
7704   // Warn about ignored flag with a fixit removal.
7705   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7706                          << ignoredFlag.toString() << flag.toString(),
7707                        getLocationOfByte(ignoredFlag.getPosition()),
7708                        /*IsStringLocation*/true,
7709                        getSpecifierRange(startSpecifier, specifierLen),
7710                        FixItHint::CreateRemoval(
7711                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7712 }
7713 
7714 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7715                                                      unsigned flagLen) {
7716   // Warn about an empty flag.
7717   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7718                        getLocationOfByte(startFlag),
7719                        /*IsStringLocation*/true,
7720                        getSpecifierRange(startFlag, flagLen));
7721 }
7722 
7723 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7724                                                        unsigned flagLen) {
7725   // Warn about an invalid flag.
7726   auto Range = getSpecifierRange(startFlag, flagLen);
7727   StringRef flag(startFlag, flagLen);
7728   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7729                       getLocationOfByte(startFlag),
7730                       /*IsStringLocation*/true,
7731                       Range, FixItHint::CreateRemoval(Range));
7732 }
7733 
7734 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7735     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7736     // Warn about using '[...]' without a '@' conversion.
7737     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7738     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7739     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7740                          getLocationOfByte(conversionPosition),
7741                          /*IsStringLocation*/true,
7742                          Range, FixItHint::CreateRemoval(Range));
7743 }
7744 
7745 // Determines if the specified is a C++ class or struct containing
7746 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7747 // "c_str()").
7748 template<typename MemberKind>
7749 static llvm::SmallPtrSet<MemberKind*, 1>
7750 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7751   const RecordType *RT = Ty->getAs<RecordType>();
7752   llvm::SmallPtrSet<MemberKind*, 1> Results;
7753 
7754   if (!RT)
7755     return Results;
7756   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7757   if (!RD || !RD->getDefinition())
7758     return Results;
7759 
7760   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7761                  Sema::LookupMemberName);
7762   R.suppressDiagnostics();
7763 
7764   // We just need to include all members of the right kind turned up by the
7765   // filter, at this point.
7766   if (S.LookupQualifiedName(R, RT->getDecl()))
7767     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7768       NamedDecl *decl = (*I)->getUnderlyingDecl();
7769       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7770         Results.insert(FK);
7771     }
7772   return Results;
7773 }
7774 
7775 /// Check if we could call '.c_str()' on an object.
7776 ///
7777 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7778 /// allow the call, or if it would be ambiguous).
7779 bool Sema::hasCStrMethod(const Expr *E) {
7780   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7781 
7782   MethodSet Results =
7783       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7784   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7785        MI != ME; ++MI)
7786     if ((*MI)->getMinRequiredArguments() == 0)
7787       return true;
7788   return false;
7789 }
7790 
7791 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7792 // better diagnostic if so. AT is assumed to be valid.
7793 // Returns true when a c_str() conversion method is found.
7794 bool CheckPrintfHandler::checkForCStrMembers(
7795     const analyze_printf::ArgType &AT, const Expr *E) {
7796   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7797 
7798   MethodSet Results =
7799       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7800 
7801   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7802        MI != ME; ++MI) {
7803     const CXXMethodDecl *Method = *MI;
7804     if (Method->getMinRequiredArguments() == 0 &&
7805         AT.matchesType(S.Context, Method->getReturnType())) {
7806       // FIXME: Suggest parens if the expression needs them.
7807       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7808       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7809           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7810       return true;
7811     }
7812   }
7813 
7814   return false;
7815 }
7816 
7817 bool
7818 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7819                                             &FS,
7820                                           const char *startSpecifier,
7821                                           unsigned specifierLen) {
7822   using namespace analyze_format_string;
7823   using namespace analyze_printf;
7824 
7825   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7826 
7827   if (FS.consumesDataArgument()) {
7828     if (atFirstArg) {
7829         atFirstArg = false;
7830         usesPositionalArgs = FS.usesPositionalArg();
7831     }
7832     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7833       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7834                                         startSpecifier, specifierLen);
7835       return false;
7836     }
7837   }
7838 
7839   // First check if the field width, precision, and conversion specifier
7840   // have matching data arguments.
7841   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7842                     startSpecifier, specifierLen)) {
7843     return false;
7844   }
7845 
7846   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7847                     startSpecifier, specifierLen)) {
7848     return false;
7849   }
7850 
7851   if (!CS.consumesDataArgument()) {
7852     // FIXME: Technically specifying a precision or field width here
7853     // makes no sense.  Worth issuing a warning at some point.
7854     return true;
7855   }
7856 
7857   // Consume the argument.
7858   unsigned argIndex = FS.getArgIndex();
7859   if (argIndex < NumDataArgs) {
7860     // The check to see if the argIndex is valid will come later.
7861     // We set the bit here because we may exit early from this
7862     // function if we encounter some other error.
7863     CoveredArgs.set(argIndex);
7864   }
7865 
7866   // FreeBSD kernel extensions.
7867   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7868       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7869     // We need at least two arguments.
7870     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7871       return false;
7872 
7873     // Claim the second argument.
7874     CoveredArgs.set(argIndex + 1);
7875 
7876     // Type check the first argument (int for %b, pointer for %D)
7877     const Expr *Ex = getDataArg(argIndex);
7878     const analyze_printf::ArgType &AT =
7879       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7880         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7881     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7882       EmitFormatDiagnostic(
7883           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7884               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7885               << false << Ex->getSourceRange(),
7886           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7887           getSpecifierRange(startSpecifier, specifierLen));
7888 
7889     // Type check the second argument (char * for both %b and %D)
7890     Ex = getDataArg(argIndex + 1);
7891     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7892     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7893       EmitFormatDiagnostic(
7894           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7895               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7896               << false << Ex->getSourceRange(),
7897           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7898           getSpecifierRange(startSpecifier, specifierLen));
7899 
7900      return true;
7901   }
7902 
7903   // Check for using an Objective-C specific conversion specifier
7904   // in a non-ObjC literal.
7905   if (!allowsObjCArg() && CS.isObjCArg()) {
7906     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7907                                                   specifierLen);
7908   }
7909 
7910   // %P can only be used with os_log.
7911   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7912     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7913                                                   specifierLen);
7914   }
7915 
7916   // %n is not allowed with os_log.
7917   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7918     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7919                          getLocationOfByte(CS.getStart()),
7920                          /*IsStringLocation*/ false,
7921                          getSpecifierRange(startSpecifier, specifierLen));
7922 
7923     return true;
7924   }
7925 
7926   // Only scalars are allowed for os_trace.
7927   if (FSType == Sema::FST_OSTrace &&
7928       (CS.getKind() == ConversionSpecifier::PArg ||
7929        CS.getKind() == ConversionSpecifier::sArg ||
7930        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7931     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7932                                                   specifierLen);
7933   }
7934 
7935   // Check for use of public/private annotation outside of os_log().
7936   if (FSType != Sema::FST_OSLog) {
7937     if (FS.isPublic().isSet()) {
7938       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7939                                << "public",
7940                            getLocationOfByte(FS.isPublic().getPosition()),
7941                            /*IsStringLocation*/ false,
7942                            getSpecifierRange(startSpecifier, specifierLen));
7943     }
7944     if (FS.isPrivate().isSet()) {
7945       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7946                                << "private",
7947                            getLocationOfByte(FS.isPrivate().getPosition()),
7948                            /*IsStringLocation*/ false,
7949                            getSpecifierRange(startSpecifier, specifierLen));
7950     }
7951   }
7952 
7953   // Check for invalid use of field width
7954   if (!FS.hasValidFieldWidth()) {
7955     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7956         startSpecifier, specifierLen);
7957   }
7958 
7959   // Check for invalid use of precision
7960   if (!FS.hasValidPrecision()) {
7961     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7962         startSpecifier, specifierLen);
7963   }
7964 
7965   // Precision is mandatory for %P specifier.
7966   if (CS.getKind() == ConversionSpecifier::PArg &&
7967       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7968     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7969                          getLocationOfByte(startSpecifier),
7970                          /*IsStringLocation*/ false,
7971                          getSpecifierRange(startSpecifier, specifierLen));
7972   }
7973 
7974   // Check each flag does not conflict with any other component.
7975   if (!FS.hasValidThousandsGroupingPrefix())
7976     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7977   if (!FS.hasValidLeadingZeros())
7978     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7979   if (!FS.hasValidPlusPrefix())
7980     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7981   if (!FS.hasValidSpacePrefix())
7982     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7983   if (!FS.hasValidAlternativeForm())
7984     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7985   if (!FS.hasValidLeftJustified())
7986     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7987 
7988   // Check that flags are not ignored by another flag
7989   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7990     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7991         startSpecifier, specifierLen);
7992   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7993     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7994             startSpecifier, specifierLen);
7995 
7996   // Check the length modifier is valid with the given conversion specifier.
7997   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7998                                  S.getLangOpts()))
7999     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8000                                 diag::warn_format_nonsensical_length);
8001   else if (!FS.hasStandardLengthModifier())
8002     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8003   else if (!FS.hasStandardLengthConversionCombination())
8004     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8005                                 diag::warn_format_non_standard_conversion_spec);
8006 
8007   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8008     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8009 
8010   // The remaining checks depend on the data arguments.
8011   if (HasVAListArg)
8012     return true;
8013 
8014   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8015     return false;
8016 
8017   const Expr *Arg = getDataArg(argIndex);
8018   if (!Arg)
8019     return true;
8020 
8021   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8022 }
8023 
8024 static bool requiresParensToAddCast(const Expr *E) {
8025   // FIXME: We should have a general way to reason about operator
8026   // precedence and whether parens are actually needed here.
8027   // Take care of a few common cases where they aren't.
8028   const Expr *Inside = E->IgnoreImpCasts();
8029   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8030     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8031 
8032   switch (Inside->getStmtClass()) {
8033   case Stmt::ArraySubscriptExprClass:
8034   case Stmt::CallExprClass:
8035   case Stmt::CharacterLiteralClass:
8036   case Stmt::CXXBoolLiteralExprClass:
8037   case Stmt::DeclRefExprClass:
8038   case Stmt::FloatingLiteralClass:
8039   case Stmt::IntegerLiteralClass:
8040   case Stmt::MemberExprClass:
8041   case Stmt::ObjCArrayLiteralClass:
8042   case Stmt::ObjCBoolLiteralExprClass:
8043   case Stmt::ObjCBoxedExprClass:
8044   case Stmt::ObjCDictionaryLiteralClass:
8045   case Stmt::ObjCEncodeExprClass:
8046   case Stmt::ObjCIvarRefExprClass:
8047   case Stmt::ObjCMessageExprClass:
8048   case Stmt::ObjCPropertyRefExprClass:
8049   case Stmt::ObjCStringLiteralClass:
8050   case Stmt::ObjCSubscriptRefExprClass:
8051   case Stmt::ParenExprClass:
8052   case Stmt::StringLiteralClass:
8053   case Stmt::UnaryOperatorClass:
8054     return false;
8055   default:
8056     return true;
8057   }
8058 }
8059 
8060 static std::pair<QualType, StringRef>
8061 shouldNotPrintDirectly(const ASTContext &Context,
8062                        QualType IntendedTy,
8063                        const Expr *E) {
8064   // Use a 'while' to peel off layers of typedefs.
8065   QualType TyTy = IntendedTy;
8066   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8067     StringRef Name = UserTy->getDecl()->getName();
8068     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8069       .Case("CFIndex", Context.getNSIntegerType())
8070       .Case("NSInteger", Context.getNSIntegerType())
8071       .Case("NSUInteger", Context.getNSUIntegerType())
8072       .Case("SInt32", Context.IntTy)
8073       .Case("UInt32", Context.UnsignedIntTy)
8074       .Default(QualType());
8075 
8076     if (!CastTy.isNull())
8077       return std::make_pair(CastTy, Name);
8078 
8079     TyTy = UserTy->desugar();
8080   }
8081 
8082   // Strip parens if necessary.
8083   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8084     return shouldNotPrintDirectly(Context,
8085                                   PE->getSubExpr()->getType(),
8086                                   PE->getSubExpr());
8087 
8088   // If this is a conditional expression, then its result type is constructed
8089   // via usual arithmetic conversions and thus there might be no necessary
8090   // typedef sugar there.  Recurse to operands to check for NSInteger &
8091   // Co. usage condition.
8092   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8093     QualType TrueTy, FalseTy;
8094     StringRef TrueName, FalseName;
8095 
8096     std::tie(TrueTy, TrueName) =
8097       shouldNotPrintDirectly(Context,
8098                              CO->getTrueExpr()->getType(),
8099                              CO->getTrueExpr());
8100     std::tie(FalseTy, FalseName) =
8101       shouldNotPrintDirectly(Context,
8102                              CO->getFalseExpr()->getType(),
8103                              CO->getFalseExpr());
8104 
8105     if (TrueTy == FalseTy)
8106       return std::make_pair(TrueTy, TrueName);
8107     else if (TrueTy.isNull())
8108       return std::make_pair(FalseTy, FalseName);
8109     else if (FalseTy.isNull())
8110       return std::make_pair(TrueTy, TrueName);
8111   }
8112 
8113   return std::make_pair(QualType(), StringRef());
8114 }
8115 
8116 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8117 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8118 /// type do not count.
8119 static bool
8120 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8121   QualType From = ICE->getSubExpr()->getType();
8122   QualType To = ICE->getType();
8123   // It's an integer promotion if the destination type is the promoted
8124   // source type.
8125   if (ICE->getCastKind() == CK_IntegralCast &&
8126       From->isPromotableIntegerType() &&
8127       S.Context.getPromotedIntegerType(From) == To)
8128     return true;
8129   // Look through vector types, since we do default argument promotion for
8130   // those in OpenCL.
8131   if (const auto *VecTy = From->getAs<ExtVectorType>())
8132     From = VecTy->getElementType();
8133   if (const auto *VecTy = To->getAs<ExtVectorType>())
8134     To = VecTy->getElementType();
8135   // It's a floating promotion if the source type is a lower rank.
8136   return ICE->getCastKind() == CK_FloatingCast &&
8137          S.Context.getFloatingTypeOrder(From, To) < 0;
8138 }
8139 
8140 bool
8141 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8142                                     const char *StartSpecifier,
8143                                     unsigned SpecifierLen,
8144                                     const Expr *E) {
8145   using namespace analyze_format_string;
8146   using namespace analyze_printf;
8147 
8148   // Now type check the data expression that matches the
8149   // format specifier.
8150   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8151   if (!AT.isValid())
8152     return true;
8153 
8154   QualType ExprTy = E->getType();
8155   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8156     ExprTy = TET->getUnderlyingExpr()->getType();
8157   }
8158 
8159   // Diagnose attempts to print a boolean value as a character. Unlike other
8160   // -Wformat diagnostics, this is fine from a type perspective, but it still
8161   // doesn't make sense.
8162   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8163       E->isKnownToHaveBooleanValue()) {
8164     const CharSourceRange &CSR =
8165         getSpecifierRange(StartSpecifier, SpecifierLen);
8166     SmallString<4> FSString;
8167     llvm::raw_svector_ostream os(FSString);
8168     FS.toString(os);
8169     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8170                              << FSString,
8171                          E->getExprLoc(), false, CSR);
8172     return true;
8173   }
8174 
8175   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8176   if (Match == analyze_printf::ArgType::Match)
8177     return true;
8178 
8179   // Look through argument promotions for our error message's reported type.
8180   // This includes the integral and floating promotions, but excludes array
8181   // and function pointer decay (seeing that an argument intended to be a
8182   // string has type 'char [6]' is probably more confusing than 'char *') and
8183   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8184   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8185     if (isArithmeticArgumentPromotion(S, ICE)) {
8186       E = ICE->getSubExpr();
8187       ExprTy = E->getType();
8188 
8189       // Check if we didn't match because of an implicit cast from a 'char'
8190       // or 'short' to an 'int'.  This is done because printf is a varargs
8191       // function.
8192       if (ICE->getType() == S.Context.IntTy ||
8193           ICE->getType() == S.Context.UnsignedIntTy) {
8194         // All further checking is done on the subexpression
8195         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8196             AT.matchesType(S.Context, ExprTy);
8197         if (ImplicitMatch == analyze_printf::ArgType::Match)
8198           return true;
8199         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8200             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8201           Match = ImplicitMatch;
8202       }
8203     }
8204   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8205     // Special case for 'a', which has type 'int' in C.
8206     // Note, however, that we do /not/ want to treat multibyte constants like
8207     // 'MooV' as characters! This form is deprecated but still exists.
8208     if (ExprTy == S.Context.IntTy)
8209       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8210         ExprTy = S.Context.CharTy;
8211   }
8212 
8213   // Look through enums to their underlying type.
8214   bool IsEnum = false;
8215   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8216     ExprTy = EnumTy->getDecl()->getIntegerType();
8217     IsEnum = true;
8218   }
8219 
8220   // %C in an Objective-C context prints a unichar, not a wchar_t.
8221   // If the argument is an integer of some kind, believe the %C and suggest
8222   // a cast instead of changing the conversion specifier.
8223   QualType IntendedTy = ExprTy;
8224   if (isObjCContext() &&
8225       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8226     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8227         !ExprTy->isCharType()) {
8228       // 'unichar' is defined as a typedef of unsigned short, but we should
8229       // prefer using the typedef if it is visible.
8230       IntendedTy = S.Context.UnsignedShortTy;
8231 
8232       // While we are here, check if the value is an IntegerLiteral that happens
8233       // to be within the valid range.
8234       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8235         const llvm::APInt &V = IL->getValue();
8236         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8237           return true;
8238       }
8239 
8240       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8241                           Sema::LookupOrdinaryName);
8242       if (S.LookupName(Result, S.getCurScope())) {
8243         NamedDecl *ND = Result.getFoundDecl();
8244         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8245           if (TD->getUnderlyingType() == IntendedTy)
8246             IntendedTy = S.Context.getTypedefType(TD);
8247       }
8248     }
8249   }
8250 
8251   // Special-case some of Darwin's platform-independence types by suggesting
8252   // casts to primitive types that are known to be large enough.
8253   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8254   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8255     QualType CastTy;
8256     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8257     if (!CastTy.isNull()) {
8258       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8259       // (long in ASTContext). Only complain to pedants.
8260       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8261           (AT.isSizeT() || AT.isPtrdiffT()) &&
8262           AT.matchesType(S.Context, CastTy))
8263         Match = ArgType::NoMatchPedantic;
8264       IntendedTy = CastTy;
8265       ShouldNotPrintDirectly = true;
8266     }
8267   }
8268 
8269   // We may be able to offer a FixItHint if it is a supported type.
8270   PrintfSpecifier fixedFS = FS;
8271   bool Success =
8272       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8273 
8274   if (Success) {
8275     // Get the fix string from the fixed format specifier
8276     SmallString<16> buf;
8277     llvm::raw_svector_ostream os(buf);
8278     fixedFS.toString(os);
8279 
8280     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8281 
8282     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8283       unsigned Diag;
8284       switch (Match) {
8285       case ArgType::Match: llvm_unreachable("expected non-matching");
8286       case ArgType::NoMatchPedantic:
8287         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8288         break;
8289       case ArgType::NoMatchTypeConfusion:
8290         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8291         break;
8292       case ArgType::NoMatch:
8293         Diag = diag::warn_format_conversion_argument_type_mismatch;
8294         break;
8295       }
8296 
8297       // In this case, the specifier is wrong and should be changed to match
8298       // the argument.
8299       EmitFormatDiagnostic(S.PDiag(Diag)
8300                                << AT.getRepresentativeTypeName(S.Context)
8301                                << IntendedTy << IsEnum << E->getSourceRange(),
8302                            E->getBeginLoc(),
8303                            /*IsStringLocation*/ false, SpecRange,
8304                            FixItHint::CreateReplacement(SpecRange, os.str()));
8305     } else {
8306       // The canonical type for formatting this value is different from the
8307       // actual type of the expression. (This occurs, for example, with Darwin's
8308       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8309       // should be printed as 'long' for 64-bit compatibility.)
8310       // Rather than emitting a normal format/argument mismatch, we want to
8311       // add a cast to the recommended type (and correct the format string
8312       // if necessary).
8313       SmallString<16> CastBuf;
8314       llvm::raw_svector_ostream CastFix(CastBuf);
8315       CastFix << "(";
8316       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8317       CastFix << ")";
8318 
8319       SmallVector<FixItHint,4> Hints;
8320       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8321         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8322 
8323       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8324         // If there's already a cast present, just replace it.
8325         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8326         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8327 
8328       } else if (!requiresParensToAddCast(E)) {
8329         // If the expression has high enough precedence,
8330         // just write the C-style cast.
8331         Hints.push_back(
8332             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8333       } else {
8334         // Otherwise, add parens around the expression as well as the cast.
8335         CastFix << "(";
8336         Hints.push_back(
8337             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8338 
8339         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8340         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8341       }
8342 
8343       if (ShouldNotPrintDirectly) {
8344         // The expression has a type that should not be printed directly.
8345         // We extract the name from the typedef because we don't want to show
8346         // the underlying type in the diagnostic.
8347         StringRef Name;
8348         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8349           Name = TypedefTy->getDecl()->getName();
8350         else
8351           Name = CastTyName;
8352         unsigned Diag = Match == ArgType::NoMatchPedantic
8353                             ? diag::warn_format_argument_needs_cast_pedantic
8354                             : diag::warn_format_argument_needs_cast;
8355         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8356                                            << E->getSourceRange(),
8357                              E->getBeginLoc(), /*IsStringLocation=*/false,
8358                              SpecRange, Hints);
8359       } else {
8360         // In this case, the expression could be printed using a different
8361         // specifier, but we've decided that the specifier is probably correct
8362         // and we should cast instead. Just use the normal warning message.
8363         EmitFormatDiagnostic(
8364             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8365                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8366                 << E->getSourceRange(),
8367             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8368       }
8369     }
8370   } else {
8371     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8372                                                    SpecifierLen);
8373     // Since the warning for passing non-POD types to variadic functions
8374     // was deferred until now, we emit a warning for non-POD
8375     // arguments here.
8376     switch (S.isValidVarArgType(ExprTy)) {
8377     case Sema::VAK_Valid:
8378     case Sema::VAK_ValidInCXX11: {
8379       unsigned Diag;
8380       switch (Match) {
8381       case ArgType::Match: llvm_unreachable("expected non-matching");
8382       case ArgType::NoMatchPedantic:
8383         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8384         break;
8385       case ArgType::NoMatchTypeConfusion:
8386         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8387         break;
8388       case ArgType::NoMatch:
8389         Diag = diag::warn_format_conversion_argument_type_mismatch;
8390         break;
8391       }
8392 
8393       EmitFormatDiagnostic(
8394           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8395                         << IsEnum << CSR << E->getSourceRange(),
8396           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8397       break;
8398     }
8399     case Sema::VAK_Undefined:
8400     case Sema::VAK_MSVCUndefined:
8401       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8402                                << S.getLangOpts().CPlusPlus11 << ExprTy
8403                                << CallType
8404                                << AT.getRepresentativeTypeName(S.Context) << CSR
8405                                << E->getSourceRange(),
8406                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8407       checkForCStrMembers(AT, E);
8408       break;
8409 
8410     case Sema::VAK_Invalid:
8411       if (ExprTy->isObjCObjectType())
8412         EmitFormatDiagnostic(
8413             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8414                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8415                 << AT.getRepresentativeTypeName(S.Context) << CSR
8416                 << E->getSourceRange(),
8417             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8418       else
8419         // FIXME: If this is an initializer list, suggest removing the braces
8420         // or inserting a cast to the target type.
8421         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8422             << isa<InitListExpr>(E) << ExprTy << CallType
8423             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8424       break;
8425     }
8426 
8427     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8428            "format string specifier index out of range");
8429     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8430   }
8431 
8432   return true;
8433 }
8434 
8435 //===--- CHECK: Scanf format string checking ------------------------------===//
8436 
8437 namespace {
8438 
8439 class CheckScanfHandler : public CheckFormatHandler {
8440 public:
8441   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8442                     const Expr *origFormatExpr, Sema::FormatStringType type,
8443                     unsigned firstDataArg, unsigned numDataArgs,
8444                     const char *beg, bool hasVAListArg,
8445                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8446                     bool inFunctionCall, Sema::VariadicCallType CallType,
8447                     llvm::SmallBitVector &CheckedVarArgs,
8448                     UncoveredArgHandler &UncoveredArg)
8449       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8450                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8451                            inFunctionCall, CallType, CheckedVarArgs,
8452                            UncoveredArg) {}
8453 
8454   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8455                             const char *startSpecifier,
8456                             unsigned specifierLen) override;
8457 
8458   bool HandleInvalidScanfConversionSpecifier(
8459           const analyze_scanf::ScanfSpecifier &FS,
8460           const char *startSpecifier,
8461           unsigned specifierLen) override;
8462 
8463   void HandleIncompleteScanList(const char *start, const char *end) override;
8464 };
8465 
8466 } // namespace
8467 
8468 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8469                                                  const char *end) {
8470   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8471                        getLocationOfByte(end), /*IsStringLocation*/true,
8472                        getSpecifierRange(start, end - start));
8473 }
8474 
8475 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8476                                         const analyze_scanf::ScanfSpecifier &FS,
8477                                         const char *startSpecifier,
8478                                         unsigned specifierLen) {
8479   const analyze_scanf::ScanfConversionSpecifier &CS =
8480     FS.getConversionSpecifier();
8481 
8482   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8483                                           getLocationOfByte(CS.getStart()),
8484                                           startSpecifier, specifierLen,
8485                                           CS.getStart(), CS.getLength());
8486 }
8487 
8488 bool CheckScanfHandler::HandleScanfSpecifier(
8489                                        const analyze_scanf::ScanfSpecifier &FS,
8490                                        const char *startSpecifier,
8491                                        unsigned specifierLen) {
8492   using namespace analyze_scanf;
8493   using namespace analyze_format_string;
8494 
8495   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8496 
8497   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8498   // be used to decide if we are using positional arguments consistently.
8499   if (FS.consumesDataArgument()) {
8500     if (atFirstArg) {
8501       atFirstArg = false;
8502       usesPositionalArgs = FS.usesPositionalArg();
8503     }
8504     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8505       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8506                                         startSpecifier, specifierLen);
8507       return false;
8508     }
8509   }
8510 
8511   // Check if the field with is non-zero.
8512   const OptionalAmount &Amt = FS.getFieldWidth();
8513   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8514     if (Amt.getConstantAmount() == 0) {
8515       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8516                                                    Amt.getConstantLength());
8517       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8518                            getLocationOfByte(Amt.getStart()),
8519                            /*IsStringLocation*/true, R,
8520                            FixItHint::CreateRemoval(R));
8521     }
8522   }
8523 
8524   if (!FS.consumesDataArgument()) {
8525     // FIXME: Technically specifying a precision or field width here
8526     // makes no sense.  Worth issuing a warning at some point.
8527     return true;
8528   }
8529 
8530   // Consume the argument.
8531   unsigned argIndex = FS.getArgIndex();
8532   if (argIndex < NumDataArgs) {
8533       // The check to see if the argIndex is valid will come later.
8534       // We set the bit here because we may exit early from this
8535       // function if we encounter some other error.
8536     CoveredArgs.set(argIndex);
8537   }
8538 
8539   // Check the length modifier is valid with the given conversion specifier.
8540   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8541                                  S.getLangOpts()))
8542     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8543                                 diag::warn_format_nonsensical_length);
8544   else if (!FS.hasStandardLengthModifier())
8545     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8546   else if (!FS.hasStandardLengthConversionCombination())
8547     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8548                                 diag::warn_format_non_standard_conversion_spec);
8549 
8550   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8551     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8552 
8553   // The remaining checks depend on the data arguments.
8554   if (HasVAListArg)
8555     return true;
8556 
8557   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8558     return false;
8559 
8560   // Check that the argument type matches the format specifier.
8561   const Expr *Ex = getDataArg(argIndex);
8562   if (!Ex)
8563     return true;
8564 
8565   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8566 
8567   if (!AT.isValid()) {
8568     return true;
8569   }
8570 
8571   analyze_format_string::ArgType::MatchKind Match =
8572       AT.matchesType(S.Context, Ex->getType());
8573   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8574   if (Match == analyze_format_string::ArgType::Match)
8575     return true;
8576 
8577   ScanfSpecifier fixedFS = FS;
8578   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8579                                  S.getLangOpts(), S.Context);
8580 
8581   unsigned Diag =
8582       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8583                : diag::warn_format_conversion_argument_type_mismatch;
8584 
8585   if (Success) {
8586     // Get the fix string from the fixed format specifier.
8587     SmallString<128> buf;
8588     llvm::raw_svector_ostream os(buf);
8589     fixedFS.toString(os);
8590 
8591     EmitFormatDiagnostic(
8592         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8593                       << Ex->getType() << false << Ex->getSourceRange(),
8594         Ex->getBeginLoc(),
8595         /*IsStringLocation*/ false,
8596         getSpecifierRange(startSpecifier, specifierLen),
8597         FixItHint::CreateReplacement(
8598             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8599   } else {
8600     EmitFormatDiagnostic(S.PDiag(Diag)
8601                              << AT.getRepresentativeTypeName(S.Context)
8602                              << Ex->getType() << false << Ex->getSourceRange(),
8603                          Ex->getBeginLoc(),
8604                          /*IsStringLocation*/ false,
8605                          getSpecifierRange(startSpecifier, specifierLen));
8606   }
8607 
8608   return true;
8609 }
8610 
8611 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8612                               const Expr *OrigFormatExpr,
8613                               ArrayRef<const Expr *> Args,
8614                               bool HasVAListArg, unsigned format_idx,
8615                               unsigned firstDataArg,
8616                               Sema::FormatStringType Type,
8617                               bool inFunctionCall,
8618                               Sema::VariadicCallType CallType,
8619                               llvm::SmallBitVector &CheckedVarArgs,
8620                               UncoveredArgHandler &UncoveredArg,
8621                               bool IgnoreStringsWithoutSpecifiers) {
8622   // CHECK: is the format string a wide literal?
8623   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8624     CheckFormatHandler::EmitFormatDiagnostic(
8625         S, inFunctionCall, Args[format_idx],
8626         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8627         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8628     return;
8629   }
8630 
8631   // Str - The format string.  NOTE: this is NOT null-terminated!
8632   StringRef StrRef = FExpr->getString();
8633   const char *Str = StrRef.data();
8634   // Account for cases where the string literal is truncated in a declaration.
8635   const ConstantArrayType *T =
8636     S.Context.getAsConstantArrayType(FExpr->getType());
8637   assert(T && "String literal not of constant array type!");
8638   size_t TypeSize = T->getSize().getZExtValue();
8639   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8640   const unsigned numDataArgs = Args.size() - firstDataArg;
8641 
8642   if (IgnoreStringsWithoutSpecifiers &&
8643       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8644           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8645     return;
8646 
8647   // Emit a warning if the string literal is truncated and does not contain an
8648   // embedded null character.
8649   if (TypeSize <= StrRef.size() &&
8650       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8651     CheckFormatHandler::EmitFormatDiagnostic(
8652         S, inFunctionCall, Args[format_idx],
8653         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8654         FExpr->getBeginLoc(),
8655         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8656     return;
8657   }
8658 
8659   // CHECK: empty format string?
8660   if (StrLen == 0 && numDataArgs > 0) {
8661     CheckFormatHandler::EmitFormatDiagnostic(
8662         S, inFunctionCall, Args[format_idx],
8663         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8664         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8665     return;
8666   }
8667 
8668   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8669       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8670       Type == Sema::FST_OSTrace) {
8671     CheckPrintfHandler H(
8672         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8673         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8674         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8675         CheckedVarArgs, UncoveredArg);
8676 
8677     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8678                                                   S.getLangOpts(),
8679                                                   S.Context.getTargetInfo(),
8680                                             Type == Sema::FST_FreeBSDKPrintf))
8681       H.DoneProcessing();
8682   } else if (Type == Sema::FST_Scanf) {
8683     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8684                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8685                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8686 
8687     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8688                                                  S.getLangOpts(),
8689                                                  S.Context.getTargetInfo()))
8690       H.DoneProcessing();
8691   } // TODO: handle other formats
8692 }
8693 
8694 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8695   // Str - The format string.  NOTE: this is NOT null-terminated!
8696   StringRef StrRef = FExpr->getString();
8697   const char *Str = StrRef.data();
8698   // Account for cases where the string literal is truncated in a declaration.
8699   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8700   assert(T && "String literal not of constant array type!");
8701   size_t TypeSize = T->getSize().getZExtValue();
8702   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8703   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8704                                                          getLangOpts(),
8705                                                          Context.getTargetInfo());
8706 }
8707 
8708 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8709 
8710 // Returns the related absolute value function that is larger, of 0 if one
8711 // does not exist.
8712 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8713   switch (AbsFunction) {
8714   default:
8715     return 0;
8716 
8717   case Builtin::BI__builtin_abs:
8718     return Builtin::BI__builtin_labs;
8719   case Builtin::BI__builtin_labs:
8720     return Builtin::BI__builtin_llabs;
8721   case Builtin::BI__builtin_llabs:
8722     return 0;
8723 
8724   case Builtin::BI__builtin_fabsf:
8725     return Builtin::BI__builtin_fabs;
8726   case Builtin::BI__builtin_fabs:
8727     return Builtin::BI__builtin_fabsl;
8728   case Builtin::BI__builtin_fabsl:
8729     return 0;
8730 
8731   case Builtin::BI__builtin_cabsf:
8732     return Builtin::BI__builtin_cabs;
8733   case Builtin::BI__builtin_cabs:
8734     return Builtin::BI__builtin_cabsl;
8735   case Builtin::BI__builtin_cabsl:
8736     return 0;
8737 
8738   case Builtin::BIabs:
8739     return Builtin::BIlabs;
8740   case Builtin::BIlabs:
8741     return Builtin::BIllabs;
8742   case Builtin::BIllabs:
8743     return 0;
8744 
8745   case Builtin::BIfabsf:
8746     return Builtin::BIfabs;
8747   case Builtin::BIfabs:
8748     return Builtin::BIfabsl;
8749   case Builtin::BIfabsl:
8750     return 0;
8751 
8752   case Builtin::BIcabsf:
8753    return Builtin::BIcabs;
8754   case Builtin::BIcabs:
8755     return Builtin::BIcabsl;
8756   case Builtin::BIcabsl:
8757     return 0;
8758   }
8759 }
8760 
8761 // Returns the argument type of the absolute value function.
8762 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8763                                              unsigned AbsType) {
8764   if (AbsType == 0)
8765     return QualType();
8766 
8767   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8768   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8769   if (Error != ASTContext::GE_None)
8770     return QualType();
8771 
8772   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8773   if (!FT)
8774     return QualType();
8775 
8776   if (FT->getNumParams() != 1)
8777     return QualType();
8778 
8779   return FT->getParamType(0);
8780 }
8781 
8782 // Returns the best absolute value function, or zero, based on type and
8783 // current absolute value function.
8784 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8785                                    unsigned AbsFunctionKind) {
8786   unsigned BestKind = 0;
8787   uint64_t ArgSize = Context.getTypeSize(ArgType);
8788   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8789        Kind = getLargerAbsoluteValueFunction(Kind)) {
8790     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8791     if (Context.getTypeSize(ParamType) >= ArgSize) {
8792       if (BestKind == 0)
8793         BestKind = Kind;
8794       else if (Context.hasSameType(ParamType, ArgType)) {
8795         BestKind = Kind;
8796         break;
8797       }
8798     }
8799   }
8800   return BestKind;
8801 }
8802 
8803 enum AbsoluteValueKind {
8804   AVK_Integer,
8805   AVK_Floating,
8806   AVK_Complex
8807 };
8808 
8809 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8810   if (T->isIntegralOrEnumerationType())
8811     return AVK_Integer;
8812   if (T->isRealFloatingType())
8813     return AVK_Floating;
8814   if (T->isAnyComplexType())
8815     return AVK_Complex;
8816 
8817   llvm_unreachable("Type not integer, floating, or complex");
8818 }
8819 
8820 // Changes the absolute value function to a different type.  Preserves whether
8821 // the function is a builtin.
8822 static unsigned changeAbsFunction(unsigned AbsKind,
8823                                   AbsoluteValueKind ValueKind) {
8824   switch (ValueKind) {
8825   case AVK_Integer:
8826     switch (AbsKind) {
8827     default:
8828       return 0;
8829     case Builtin::BI__builtin_fabsf:
8830     case Builtin::BI__builtin_fabs:
8831     case Builtin::BI__builtin_fabsl:
8832     case Builtin::BI__builtin_cabsf:
8833     case Builtin::BI__builtin_cabs:
8834     case Builtin::BI__builtin_cabsl:
8835       return Builtin::BI__builtin_abs;
8836     case Builtin::BIfabsf:
8837     case Builtin::BIfabs:
8838     case Builtin::BIfabsl:
8839     case Builtin::BIcabsf:
8840     case Builtin::BIcabs:
8841     case Builtin::BIcabsl:
8842       return Builtin::BIabs;
8843     }
8844   case AVK_Floating:
8845     switch (AbsKind) {
8846     default:
8847       return 0;
8848     case Builtin::BI__builtin_abs:
8849     case Builtin::BI__builtin_labs:
8850     case Builtin::BI__builtin_llabs:
8851     case Builtin::BI__builtin_cabsf:
8852     case Builtin::BI__builtin_cabs:
8853     case Builtin::BI__builtin_cabsl:
8854       return Builtin::BI__builtin_fabsf;
8855     case Builtin::BIabs:
8856     case Builtin::BIlabs:
8857     case Builtin::BIllabs:
8858     case Builtin::BIcabsf:
8859     case Builtin::BIcabs:
8860     case Builtin::BIcabsl:
8861       return Builtin::BIfabsf;
8862     }
8863   case AVK_Complex:
8864     switch (AbsKind) {
8865     default:
8866       return 0;
8867     case Builtin::BI__builtin_abs:
8868     case Builtin::BI__builtin_labs:
8869     case Builtin::BI__builtin_llabs:
8870     case Builtin::BI__builtin_fabsf:
8871     case Builtin::BI__builtin_fabs:
8872     case Builtin::BI__builtin_fabsl:
8873       return Builtin::BI__builtin_cabsf;
8874     case Builtin::BIabs:
8875     case Builtin::BIlabs:
8876     case Builtin::BIllabs:
8877     case Builtin::BIfabsf:
8878     case Builtin::BIfabs:
8879     case Builtin::BIfabsl:
8880       return Builtin::BIcabsf;
8881     }
8882   }
8883   llvm_unreachable("Unable to convert function");
8884 }
8885 
8886 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8887   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8888   if (!FnInfo)
8889     return 0;
8890 
8891   switch (FDecl->getBuiltinID()) {
8892   default:
8893     return 0;
8894   case Builtin::BI__builtin_abs:
8895   case Builtin::BI__builtin_fabs:
8896   case Builtin::BI__builtin_fabsf:
8897   case Builtin::BI__builtin_fabsl:
8898   case Builtin::BI__builtin_labs:
8899   case Builtin::BI__builtin_llabs:
8900   case Builtin::BI__builtin_cabs:
8901   case Builtin::BI__builtin_cabsf:
8902   case Builtin::BI__builtin_cabsl:
8903   case Builtin::BIabs:
8904   case Builtin::BIlabs:
8905   case Builtin::BIllabs:
8906   case Builtin::BIfabs:
8907   case Builtin::BIfabsf:
8908   case Builtin::BIfabsl:
8909   case Builtin::BIcabs:
8910   case Builtin::BIcabsf:
8911   case Builtin::BIcabsl:
8912     return FDecl->getBuiltinID();
8913   }
8914   llvm_unreachable("Unknown Builtin type");
8915 }
8916 
8917 // If the replacement is valid, emit a note with replacement function.
8918 // Additionally, suggest including the proper header if not already included.
8919 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8920                             unsigned AbsKind, QualType ArgType) {
8921   bool EmitHeaderHint = true;
8922   const char *HeaderName = nullptr;
8923   const char *FunctionName = nullptr;
8924   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8925     FunctionName = "std::abs";
8926     if (ArgType->isIntegralOrEnumerationType()) {
8927       HeaderName = "cstdlib";
8928     } else if (ArgType->isRealFloatingType()) {
8929       HeaderName = "cmath";
8930     } else {
8931       llvm_unreachable("Invalid Type");
8932     }
8933 
8934     // Lookup all std::abs
8935     if (NamespaceDecl *Std = S.getStdNamespace()) {
8936       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8937       R.suppressDiagnostics();
8938       S.LookupQualifiedName(R, Std);
8939 
8940       for (const auto *I : R) {
8941         const FunctionDecl *FDecl = nullptr;
8942         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8943           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8944         } else {
8945           FDecl = dyn_cast<FunctionDecl>(I);
8946         }
8947         if (!FDecl)
8948           continue;
8949 
8950         // Found std::abs(), check that they are the right ones.
8951         if (FDecl->getNumParams() != 1)
8952           continue;
8953 
8954         // Check that the parameter type can handle the argument.
8955         QualType ParamType = FDecl->getParamDecl(0)->getType();
8956         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8957             S.Context.getTypeSize(ArgType) <=
8958                 S.Context.getTypeSize(ParamType)) {
8959           // Found a function, don't need the header hint.
8960           EmitHeaderHint = false;
8961           break;
8962         }
8963       }
8964     }
8965   } else {
8966     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8967     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8968 
8969     if (HeaderName) {
8970       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8971       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8972       R.suppressDiagnostics();
8973       S.LookupName(R, S.getCurScope());
8974 
8975       if (R.isSingleResult()) {
8976         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8977         if (FD && FD->getBuiltinID() == AbsKind) {
8978           EmitHeaderHint = false;
8979         } else {
8980           return;
8981         }
8982       } else if (!R.empty()) {
8983         return;
8984       }
8985     }
8986   }
8987 
8988   S.Diag(Loc, diag::note_replace_abs_function)
8989       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8990 
8991   if (!HeaderName)
8992     return;
8993 
8994   if (!EmitHeaderHint)
8995     return;
8996 
8997   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8998                                                     << FunctionName;
8999 }
9000 
9001 template <std::size_t StrLen>
9002 static bool IsStdFunction(const FunctionDecl *FDecl,
9003                           const char (&Str)[StrLen]) {
9004   if (!FDecl)
9005     return false;
9006   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9007     return false;
9008   if (!FDecl->isInStdNamespace())
9009     return false;
9010 
9011   return true;
9012 }
9013 
9014 // Warn when using the wrong abs() function.
9015 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9016                                       const FunctionDecl *FDecl) {
9017   if (Call->getNumArgs() != 1)
9018     return;
9019 
9020   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9021   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9022   if (AbsKind == 0 && !IsStdAbs)
9023     return;
9024 
9025   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9026   QualType ParamType = Call->getArg(0)->getType();
9027 
9028   // Unsigned types cannot be negative.  Suggest removing the absolute value
9029   // function call.
9030   if (ArgType->isUnsignedIntegerType()) {
9031     const char *FunctionName =
9032         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9033     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9034     Diag(Call->getExprLoc(), diag::note_remove_abs)
9035         << FunctionName
9036         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9037     return;
9038   }
9039 
9040   // Taking the absolute value of a pointer is very suspicious, they probably
9041   // wanted to index into an array, dereference a pointer, call a function, etc.
9042   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9043     unsigned DiagType = 0;
9044     if (ArgType->isFunctionType())
9045       DiagType = 1;
9046     else if (ArgType->isArrayType())
9047       DiagType = 2;
9048 
9049     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9050     return;
9051   }
9052 
9053   // std::abs has overloads which prevent most of the absolute value problems
9054   // from occurring.
9055   if (IsStdAbs)
9056     return;
9057 
9058   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9059   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9060 
9061   // The argument and parameter are the same kind.  Check if they are the right
9062   // size.
9063   if (ArgValueKind == ParamValueKind) {
9064     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9065       return;
9066 
9067     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9068     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9069         << FDecl << ArgType << ParamType;
9070 
9071     if (NewAbsKind == 0)
9072       return;
9073 
9074     emitReplacement(*this, Call->getExprLoc(),
9075                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9076     return;
9077   }
9078 
9079   // ArgValueKind != ParamValueKind
9080   // The wrong type of absolute value function was used.  Attempt to find the
9081   // proper one.
9082   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9083   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9084   if (NewAbsKind == 0)
9085     return;
9086 
9087   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9088       << FDecl << ParamValueKind << ArgValueKind;
9089 
9090   emitReplacement(*this, Call->getExprLoc(),
9091                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9092 }
9093 
9094 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9095 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9096                                 const FunctionDecl *FDecl) {
9097   if (!Call || !FDecl) return;
9098 
9099   // Ignore template specializations and macros.
9100   if (inTemplateInstantiation()) return;
9101   if (Call->getExprLoc().isMacroID()) return;
9102 
9103   // Only care about the one template argument, two function parameter std::max
9104   if (Call->getNumArgs() != 2) return;
9105   if (!IsStdFunction(FDecl, "max")) return;
9106   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9107   if (!ArgList) return;
9108   if (ArgList->size() != 1) return;
9109 
9110   // Check that template type argument is unsigned integer.
9111   const auto& TA = ArgList->get(0);
9112   if (TA.getKind() != TemplateArgument::Type) return;
9113   QualType ArgType = TA.getAsType();
9114   if (!ArgType->isUnsignedIntegerType()) return;
9115 
9116   // See if either argument is a literal zero.
9117   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9118     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9119     if (!MTE) return false;
9120     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
9121     if (!Num) return false;
9122     if (Num->getValue() != 0) return false;
9123     return true;
9124   };
9125 
9126   const Expr *FirstArg = Call->getArg(0);
9127   const Expr *SecondArg = Call->getArg(1);
9128   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9129   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9130 
9131   // Only warn when exactly one argument is zero.
9132   if (IsFirstArgZero == IsSecondArgZero) return;
9133 
9134   SourceRange FirstRange = FirstArg->getSourceRange();
9135   SourceRange SecondRange = SecondArg->getSourceRange();
9136 
9137   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9138 
9139   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9140       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9141 
9142   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9143   SourceRange RemovalRange;
9144   if (IsFirstArgZero) {
9145     RemovalRange = SourceRange(FirstRange.getBegin(),
9146                                SecondRange.getBegin().getLocWithOffset(-1));
9147   } else {
9148     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9149                                SecondRange.getEnd());
9150   }
9151 
9152   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9153         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9154         << FixItHint::CreateRemoval(RemovalRange);
9155 }
9156 
9157 //===--- CHECK: Standard memory functions ---------------------------------===//
9158 
9159 /// Takes the expression passed to the size_t parameter of functions
9160 /// such as memcmp, strncat, etc and warns if it's a comparison.
9161 ///
9162 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9163 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9164                                            IdentifierInfo *FnName,
9165                                            SourceLocation FnLoc,
9166                                            SourceLocation RParenLoc) {
9167   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9168   if (!Size)
9169     return false;
9170 
9171   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9172   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9173     return false;
9174 
9175   SourceRange SizeRange = Size->getSourceRange();
9176   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9177       << SizeRange << FnName;
9178   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9179       << FnName
9180       << FixItHint::CreateInsertion(
9181              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9182       << FixItHint::CreateRemoval(RParenLoc);
9183   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9184       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9185       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9186                                     ")");
9187 
9188   return true;
9189 }
9190 
9191 /// Determine whether the given type is or contains a dynamic class type
9192 /// (e.g., whether it has a vtable).
9193 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9194                                                      bool &IsContained) {
9195   // Look through array types while ignoring qualifiers.
9196   const Type *Ty = T->getBaseElementTypeUnsafe();
9197   IsContained = false;
9198 
9199   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9200   RD = RD ? RD->getDefinition() : nullptr;
9201   if (!RD || RD->isInvalidDecl())
9202     return nullptr;
9203 
9204   if (RD->isDynamicClass())
9205     return RD;
9206 
9207   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9208   // It's impossible for a class to transitively contain itself by value, so
9209   // infinite recursion is impossible.
9210   for (auto *FD : RD->fields()) {
9211     bool SubContained;
9212     if (const CXXRecordDecl *ContainedRD =
9213             getContainedDynamicClass(FD->getType(), SubContained)) {
9214       IsContained = true;
9215       return ContainedRD;
9216     }
9217   }
9218 
9219   return nullptr;
9220 }
9221 
9222 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9223   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9224     if (Unary->getKind() == UETT_SizeOf)
9225       return Unary;
9226   return nullptr;
9227 }
9228 
9229 /// If E is a sizeof expression, returns its argument expression,
9230 /// otherwise returns NULL.
9231 static const Expr *getSizeOfExprArg(const Expr *E) {
9232   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9233     if (!SizeOf->isArgumentType())
9234       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9235   return nullptr;
9236 }
9237 
9238 /// If E is a sizeof expression, returns its argument type.
9239 static QualType getSizeOfArgType(const Expr *E) {
9240   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9241     return SizeOf->getTypeOfArgument();
9242   return QualType();
9243 }
9244 
9245 namespace {
9246 
9247 struct SearchNonTrivialToInitializeField
9248     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9249   using Super =
9250       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9251 
9252   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9253 
9254   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9255                      SourceLocation SL) {
9256     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9257       asDerived().visitArray(PDIK, AT, SL);
9258       return;
9259     }
9260 
9261     Super::visitWithKind(PDIK, FT, SL);
9262   }
9263 
9264   void visitARCStrong(QualType FT, SourceLocation SL) {
9265     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9266   }
9267   void visitARCWeak(QualType FT, SourceLocation SL) {
9268     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9269   }
9270   void visitStruct(QualType FT, SourceLocation SL) {
9271     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9272       visit(FD->getType(), FD->getLocation());
9273   }
9274   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9275                   const ArrayType *AT, SourceLocation SL) {
9276     visit(getContext().getBaseElementType(AT), SL);
9277   }
9278   void visitTrivial(QualType FT, SourceLocation SL) {}
9279 
9280   static void diag(QualType RT, const Expr *E, Sema &S) {
9281     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9282   }
9283 
9284   ASTContext &getContext() { return S.getASTContext(); }
9285 
9286   const Expr *E;
9287   Sema &S;
9288 };
9289 
9290 struct SearchNonTrivialToCopyField
9291     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9292   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9293 
9294   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9295 
9296   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9297                      SourceLocation SL) {
9298     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9299       asDerived().visitArray(PCK, AT, SL);
9300       return;
9301     }
9302 
9303     Super::visitWithKind(PCK, FT, SL);
9304   }
9305 
9306   void visitARCStrong(QualType FT, SourceLocation SL) {
9307     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9308   }
9309   void visitARCWeak(QualType FT, SourceLocation SL) {
9310     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9311   }
9312   void visitStruct(QualType FT, SourceLocation SL) {
9313     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9314       visit(FD->getType(), FD->getLocation());
9315   }
9316   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9317                   SourceLocation SL) {
9318     visit(getContext().getBaseElementType(AT), SL);
9319   }
9320   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9321                 SourceLocation SL) {}
9322   void visitTrivial(QualType FT, SourceLocation SL) {}
9323   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9324 
9325   static void diag(QualType RT, const Expr *E, Sema &S) {
9326     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9327   }
9328 
9329   ASTContext &getContext() { return S.getASTContext(); }
9330 
9331   const Expr *E;
9332   Sema &S;
9333 };
9334 
9335 }
9336 
9337 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9338 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9339   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9340 
9341   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9342     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9343       return false;
9344 
9345     return doesExprLikelyComputeSize(BO->getLHS()) ||
9346            doesExprLikelyComputeSize(BO->getRHS());
9347   }
9348 
9349   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9350 }
9351 
9352 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9353 ///
9354 /// \code
9355 ///   #define MACRO 0
9356 ///   foo(MACRO);
9357 ///   foo(0);
9358 /// \endcode
9359 ///
9360 /// This should return true for the first call to foo, but not for the second
9361 /// (regardless of whether foo is a macro or function).
9362 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9363                                         SourceLocation CallLoc,
9364                                         SourceLocation ArgLoc) {
9365   if (!CallLoc.isMacroID())
9366     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9367 
9368   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9369          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9370 }
9371 
9372 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9373 /// last two arguments transposed.
9374 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9375   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9376     return;
9377 
9378   const Expr *SizeArg =
9379     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9380 
9381   auto isLiteralZero = [](const Expr *E) {
9382     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9383   };
9384 
9385   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9386   SourceLocation CallLoc = Call->getRParenLoc();
9387   SourceManager &SM = S.getSourceManager();
9388   if (isLiteralZero(SizeArg) &&
9389       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9390 
9391     SourceLocation DiagLoc = SizeArg->getExprLoc();
9392 
9393     // Some platforms #define bzero to __builtin_memset. See if this is the
9394     // case, and if so, emit a better diagnostic.
9395     if (BId == Builtin::BIbzero ||
9396         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9397                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9398       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9399       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9400     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9401       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9402       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9403     }
9404     return;
9405   }
9406 
9407   // If the second argument to a memset is a sizeof expression and the third
9408   // isn't, this is also likely an error. This should catch
9409   // 'memset(buf, sizeof(buf), 0xff)'.
9410   if (BId == Builtin::BImemset &&
9411       doesExprLikelyComputeSize(Call->getArg(1)) &&
9412       !doesExprLikelyComputeSize(Call->getArg(2))) {
9413     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9414     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9415     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9416     return;
9417   }
9418 }
9419 
9420 /// Check for dangerous or invalid arguments to memset().
9421 ///
9422 /// This issues warnings on known problematic, dangerous or unspecified
9423 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9424 /// function calls.
9425 ///
9426 /// \param Call The call expression to diagnose.
9427 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9428                                    unsigned BId,
9429                                    IdentifierInfo *FnName) {
9430   assert(BId != 0);
9431 
9432   // It is possible to have a non-standard definition of memset.  Validate
9433   // we have enough arguments, and if not, abort further checking.
9434   unsigned ExpectedNumArgs =
9435       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9436   if (Call->getNumArgs() < ExpectedNumArgs)
9437     return;
9438 
9439   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9440                       BId == Builtin::BIstrndup ? 1 : 2);
9441   unsigned LenArg =
9442       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9443   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9444 
9445   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9446                                      Call->getBeginLoc(), Call->getRParenLoc()))
9447     return;
9448 
9449   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9450   CheckMemaccessSize(*this, BId, Call);
9451 
9452   // We have special checking when the length is a sizeof expression.
9453   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9454   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9455   llvm::FoldingSetNodeID SizeOfArgID;
9456 
9457   // Although widely used, 'bzero' is not a standard function. Be more strict
9458   // with the argument types before allowing diagnostics and only allow the
9459   // form bzero(ptr, sizeof(...)).
9460   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9461   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9462     return;
9463 
9464   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9465     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9466     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9467 
9468     QualType DestTy = Dest->getType();
9469     QualType PointeeTy;
9470     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9471       PointeeTy = DestPtrTy->getPointeeType();
9472 
9473       // Never warn about void type pointers. This can be used to suppress
9474       // false positives.
9475       if (PointeeTy->isVoidType())
9476         continue;
9477 
9478       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9479       // actually comparing the expressions for equality. Because computing the
9480       // expression IDs can be expensive, we only do this if the diagnostic is
9481       // enabled.
9482       if (SizeOfArg &&
9483           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9484                            SizeOfArg->getExprLoc())) {
9485         // We only compute IDs for expressions if the warning is enabled, and
9486         // cache the sizeof arg's ID.
9487         if (SizeOfArgID == llvm::FoldingSetNodeID())
9488           SizeOfArg->Profile(SizeOfArgID, Context, true);
9489         llvm::FoldingSetNodeID DestID;
9490         Dest->Profile(DestID, Context, true);
9491         if (DestID == SizeOfArgID) {
9492           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9493           //       over sizeof(src) as well.
9494           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9495           StringRef ReadableName = FnName->getName();
9496 
9497           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9498             if (UnaryOp->getOpcode() == UO_AddrOf)
9499               ActionIdx = 1; // If its an address-of operator, just remove it.
9500           if (!PointeeTy->isIncompleteType() &&
9501               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9502             ActionIdx = 2; // If the pointee's size is sizeof(char),
9503                            // suggest an explicit length.
9504 
9505           // If the function is defined as a builtin macro, do not show macro
9506           // expansion.
9507           SourceLocation SL = SizeOfArg->getExprLoc();
9508           SourceRange DSR = Dest->getSourceRange();
9509           SourceRange SSR = SizeOfArg->getSourceRange();
9510           SourceManager &SM = getSourceManager();
9511 
9512           if (SM.isMacroArgExpansion(SL)) {
9513             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9514             SL = SM.getSpellingLoc(SL);
9515             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9516                              SM.getSpellingLoc(DSR.getEnd()));
9517             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9518                              SM.getSpellingLoc(SSR.getEnd()));
9519           }
9520 
9521           DiagRuntimeBehavior(SL, SizeOfArg,
9522                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9523                                 << ReadableName
9524                                 << PointeeTy
9525                                 << DestTy
9526                                 << DSR
9527                                 << SSR);
9528           DiagRuntimeBehavior(SL, SizeOfArg,
9529                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9530                                 << ActionIdx
9531                                 << SSR);
9532 
9533           break;
9534         }
9535       }
9536 
9537       // Also check for cases where the sizeof argument is the exact same
9538       // type as the memory argument, and where it points to a user-defined
9539       // record type.
9540       if (SizeOfArgTy != QualType()) {
9541         if (PointeeTy->isRecordType() &&
9542             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9543           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9544                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9545                                 << FnName << SizeOfArgTy << ArgIdx
9546                                 << PointeeTy << Dest->getSourceRange()
9547                                 << LenExpr->getSourceRange());
9548           break;
9549         }
9550       }
9551     } else if (DestTy->isArrayType()) {
9552       PointeeTy = DestTy;
9553     }
9554 
9555     if (PointeeTy == QualType())
9556       continue;
9557 
9558     // Always complain about dynamic classes.
9559     bool IsContained;
9560     if (const CXXRecordDecl *ContainedRD =
9561             getContainedDynamicClass(PointeeTy, IsContained)) {
9562 
9563       unsigned OperationType = 0;
9564       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9565       // "overwritten" if we're warning about the destination for any call
9566       // but memcmp; otherwise a verb appropriate to the call.
9567       if (ArgIdx != 0 || IsCmp) {
9568         if (BId == Builtin::BImemcpy)
9569           OperationType = 1;
9570         else if(BId == Builtin::BImemmove)
9571           OperationType = 2;
9572         else if (IsCmp)
9573           OperationType = 3;
9574       }
9575 
9576       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9577                           PDiag(diag::warn_dyn_class_memaccess)
9578                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9579                               << IsContained << ContainedRD << OperationType
9580                               << Call->getCallee()->getSourceRange());
9581     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9582              BId != Builtin::BImemset)
9583       DiagRuntimeBehavior(
9584         Dest->getExprLoc(), Dest,
9585         PDiag(diag::warn_arc_object_memaccess)
9586           << ArgIdx << FnName << PointeeTy
9587           << Call->getCallee()->getSourceRange());
9588     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9589       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9590           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9591         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9592                             PDiag(diag::warn_cstruct_memaccess)
9593                                 << ArgIdx << FnName << PointeeTy << 0);
9594         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9595       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9596                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9597         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9598                             PDiag(diag::warn_cstruct_memaccess)
9599                                 << ArgIdx << FnName << PointeeTy << 1);
9600         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9601       } else {
9602         continue;
9603       }
9604     } else
9605       continue;
9606 
9607     DiagRuntimeBehavior(
9608       Dest->getExprLoc(), Dest,
9609       PDiag(diag::note_bad_memaccess_silence)
9610         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9611     break;
9612   }
9613 }
9614 
9615 // A little helper routine: ignore addition and subtraction of integer literals.
9616 // This intentionally does not ignore all integer constant expressions because
9617 // we don't want to remove sizeof().
9618 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9619   Ex = Ex->IgnoreParenCasts();
9620 
9621   while (true) {
9622     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9623     if (!BO || !BO->isAdditiveOp())
9624       break;
9625 
9626     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9627     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9628 
9629     if (isa<IntegerLiteral>(RHS))
9630       Ex = LHS;
9631     else if (isa<IntegerLiteral>(LHS))
9632       Ex = RHS;
9633     else
9634       break;
9635   }
9636 
9637   return Ex;
9638 }
9639 
9640 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9641                                                       ASTContext &Context) {
9642   // Only handle constant-sized or VLAs, but not flexible members.
9643   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9644     // Only issue the FIXIT for arrays of size > 1.
9645     if (CAT->getSize().getSExtValue() <= 1)
9646       return false;
9647   } else if (!Ty->isVariableArrayType()) {
9648     return false;
9649   }
9650   return true;
9651 }
9652 
9653 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9654 // be the size of the source, instead of the destination.
9655 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9656                                     IdentifierInfo *FnName) {
9657 
9658   // Don't crash if the user has the wrong number of arguments
9659   unsigned NumArgs = Call->getNumArgs();
9660   if ((NumArgs != 3) && (NumArgs != 4))
9661     return;
9662 
9663   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9664   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9665   const Expr *CompareWithSrc = nullptr;
9666 
9667   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9668                                      Call->getBeginLoc(), Call->getRParenLoc()))
9669     return;
9670 
9671   // Look for 'strlcpy(dst, x, sizeof(x))'
9672   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9673     CompareWithSrc = Ex;
9674   else {
9675     // Look for 'strlcpy(dst, x, strlen(x))'
9676     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9677       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9678           SizeCall->getNumArgs() == 1)
9679         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9680     }
9681   }
9682 
9683   if (!CompareWithSrc)
9684     return;
9685 
9686   // Determine if the argument to sizeof/strlen is equal to the source
9687   // argument.  In principle there's all kinds of things you could do
9688   // here, for instance creating an == expression and evaluating it with
9689   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9690   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9691   if (!SrcArgDRE)
9692     return;
9693 
9694   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9695   if (!CompareWithSrcDRE ||
9696       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9697     return;
9698 
9699   const Expr *OriginalSizeArg = Call->getArg(2);
9700   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9701       << OriginalSizeArg->getSourceRange() << FnName;
9702 
9703   // Output a FIXIT hint if the destination is an array (rather than a
9704   // pointer to an array).  This could be enhanced to handle some
9705   // pointers if we know the actual size, like if DstArg is 'array+2'
9706   // we could say 'sizeof(array)-2'.
9707   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9708   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9709     return;
9710 
9711   SmallString<128> sizeString;
9712   llvm::raw_svector_ostream OS(sizeString);
9713   OS << "sizeof(";
9714   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9715   OS << ")";
9716 
9717   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9718       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9719                                       OS.str());
9720 }
9721 
9722 /// Check if two expressions refer to the same declaration.
9723 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9724   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9725     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9726       return D1->getDecl() == D2->getDecl();
9727   return false;
9728 }
9729 
9730 static const Expr *getStrlenExprArg(const Expr *E) {
9731   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9732     const FunctionDecl *FD = CE->getDirectCallee();
9733     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9734       return nullptr;
9735     return CE->getArg(0)->IgnoreParenCasts();
9736   }
9737   return nullptr;
9738 }
9739 
9740 // Warn on anti-patterns as the 'size' argument to strncat.
9741 // The correct size argument should look like following:
9742 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9743 void Sema::CheckStrncatArguments(const CallExpr *CE,
9744                                  IdentifierInfo *FnName) {
9745   // Don't crash if the user has the wrong number of arguments.
9746   if (CE->getNumArgs() < 3)
9747     return;
9748   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9749   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9750   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9751 
9752   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9753                                      CE->getRParenLoc()))
9754     return;
9755 
9756   // Identify common expressions, which are wrongly used as the size argument
9757   // to strncat and may lead to buffer overflows.
9758   unsigned PatternType = 0;
9759   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9760     // - sizeof(dst)
9761     if (referToTheSameDecl(SizeOfArg, DstArg))
9762       PatternType = 1;
9763     // - sizeof(src)
9764     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9765       PatternType = 2;
9766   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9767     if (BE->getOpcode() == BO_Sub) {
9768       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9769       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9770       // - sizeof(dst) - strlen(dst)
9771       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9772           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9773         PatternType = 1;
9774       // - sizeof(src) - (anything)
9775       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9776         PatternType = 2;
9777     }
9778   }
9779 
9780   if (PatternType == 0)
9781     return;
9782 
9783   // Generate the diagnostic.
9784   SourceLocation SL = LenArg->getBeginLoc();
9785   SourceRange SR = LenArg->getSourceRange();
9786   SourceManager &SM = getSourceManager();
9787 
9788   // If the function is defined as a builtin macro, do not show macro expansion.
9789   if (SM.isMacroArgExpansion(SL)) {
9790     SL = SM.getSpellingLoc(SL);
9791     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9792                      SM.getSpellingLoc(SR.getEnd()));
9793   }
9794 
9795   // Check if the destination is an array (rather than a pointer to an array).
9796   QualType DstTy = DstArg->getType();
9797   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9798                                                                     Context);
9799   if (!isKnownSizeArray) {
9800     if (PatternType == 1)
9801       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9802     else
9803       Diag(SL, diag::warn_strncat_src_size) << SR;
9804     return;
9805   }
9806 
9807   if (PatternType == 1)
9808     Diag(SL, diag::warn_strncat_large_size) << SR;
9809   else
9810     Diag(SL, diag::warn_strncat_src_size) << SR;
9811 
9812   SmallString<128> sizeString;
9813   llvm::raw_svector_ostream OS(sizeString);
9814   OS << "sizeof(";
9815   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9816   OS << ") - ";
9817   OS << "strlen(";
9818   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9819   OS << ") - 1";
9820 
9821   Diag(SL, diag::note_strncat_wrong_size)
9822     << FixItHint::CreateReplacement(SR, OS.str());
9823 }
9824 
9825 void
9826 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9827                          SourceLocation ReturnLoc,
9828                          bool isObjCMethod,
9829                          const AttrVec *Attrs,
9830                          const FunctionDecl *FD) {
9831   // Check if the return value is null but should not be.
9832   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9833        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9834       CheckNonNullExpr(*this, RetValExp))
9835     Diag(ReturnLoc, diag::warn_null_ret)
9836       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9837 
9838   // C++11 [basic.stc.dynamic.allocation]p4:
9839   //   If an allocation function declared with a non-throwing
9840   //   exception-specification fails to allocate storage, it shall return
9841   //   a null pointer. Any other allocation function that fails to allocate
9842   //   storage shall indicate failure only by throwing an exception [...]
9843   if (FD) {
9844     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9845     if (Op == OO_New || Op == OO_Array_New) {
9846       const FunctionProtoType *Proto
9847         = FD->getType()->castAs<FunctionProtoType>();
9848       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9849           CheckNonNullExpr(*this, RetValExp))
9850         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9851           << FD << getLangOpts().CPlusPlus11;
9852     }
9853   }
9854 }
9855 
9856 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9857 
9858 /// Check for comparisons of floating point operands using != and ==.
9859 /// Issue a warning if these are no self-comparisons, as they are not likely
9860 /// to do what the programmer intended.
9861 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9862   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9863   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9864 
9865   // Special case: check for x == x (which is OK).
9866   // Do not emit warnings for such cases.
9867   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9868     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9869       if (DRL->getDecl() == DRR->getDecl())
9870         return;
9871 
9872   // Special case: check for comparisons against literals that can be exactly
9873   //  represented by APFloat.  In such cases, do not emit a warning.  This
9874   //  is a heuristic: often comparison against such literals are used to
9875   //  detect if a value in a variable has not changed.  This clearly can
9876   //  lead to false negatives.
9877   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9878     if (FLL->isExact())
9879       return;
9880   } else
9881     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9882       if (FLR->isExact())
9883         return;
9884 
9885   // Check for comparisons with builtin types.
9886   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9887     if (CL->getBuiltinCallee())
9888       return;
9889 
9890   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9891     if (CR->getBuiltinCallee())
9892       return;
9893 
9894   // Emit the diagnostic.
9895   Diag(Loc, diag::warn_floatingpoint_eq)
9896     << LHS->getSourceRange() << RHS->getSourceRange();
9897 }
9898 
9899 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9900 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9901 
9902 namespace {
9903 
9904 /// Structure recording the 'active' range of an integer-valued
9905 /// expression.
9906 struct IntRange {
9907   /// The number of bits active in the int.
9908   unsigned Width;
9909 
9910   /// True if the int is known not to have negative values.
9911   bool NonNegative;
9912 
9913   IntRange(unsigned Width, bool NonNegative)
9914       : Width(Width), NonNegative(NonNegative) {}
9915 
9916   /// Returns the range of the bool type.
9917   static IntRange forBoolType() {
9918     return IntRange(1, true);
9919   }
9920 
9921   /// Returns the range of an opaque value of the given integral type.
9922   static IntRange forValueOfType(ASTContext &C, QualType T) {
9923     return forValueOfCanonicalType(C,
9924                           T->getCanonicalTypeInternal().getTypePtr());
9925   }
9926 
9927   /// Returns the range of an opaque value of a canonical integral type.
9928   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9929     assert(T->isCanonicalUnqualified());
9930 
9931     if (const VectorType *VT = dyn_cast<VectorType>(T))
9932       T = VT->getElementType().getTypePtr();
9933     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9934       T = CT->getElementType().getTypePtr();
9935     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9936       T = AT->getValueType().getTypePtr();
9937 
9938     if (!C.getLangOpts().CPlusPlus) {
9939       // For enum types in C code, use the underlying datatype.
9940       if (const EnumType *ET = dyn_cast<EnumType>(T))
9941         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9942     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9943       // For enum types in C++, use the known bit width of the enumerators.
9944       EnumDecl *Enum = ET->getDecl();
9945       // In C++11, enums can have a fixed underlying type. Use this type to
9946       // compute the range.
9947       if (Enum->isFixed()) {
9948         return IntRange(C.getIntWidth(QualType(T, 0)),
9949                         !ET->isSignedIntegerOrEnumerationType());
9950       }
9951 
9952       unsigned NumPositive = Enum->getNumPositiveBits();
9953       unsigned NumNegative = Enum->getNumNegativeBits();
9954 
9955       if (NumNegative == 0)
9956         return IntRange(NumPositive, true/*NonNegative*/);
9957       else
9958         return IntRange(std::max(NumPositive + 1, NumNegative),
9959                         false/*NonNegative*/);
9960     }
9961 
9962     const BuiltinType *BT = cast<BuiltinType>(T);
9963     assert(BT->isInteger());
9964 
9965     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9966   }
9967 
9968   /// Returns the "target" range of a canonical integral type, i.e.
9969   /// the range of values expressible in the type.
9970   ///
9971   /// This matches forValueOfCanonicalType except that enums have the
9972   /// full range of their type, not the range of their enumerators.
9973   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9974     assert(T->isCanonicalUnqualified());
9975 
9976     if (const VectorType *VT = dyn_cast<VectorType>(T))
9977       T = VT->getElementType().getTypePtr();
9978     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9979       T = CT->getElementType().getTypePtr();
9980     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9981       T = AT->getValueType().getTypePtr();
9982     if (const EnumType *ET = dyn_cast<EnumType>(T))
9983       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9984 
9985     const BuiltinType *BT = cast<BuiltinType>(T);
9986     assert(BT->isInteger());
9987 
9988     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9989   }
9990 
9991   /// Returns the supremum of two ranges: i.e. their conservative merge.
9992   static IntRange join(IntRange L, IntRange R) {
9993     return IntRange(std::max(L.Width, R.Width),
9994                     L.NonNegative && R.NonNegative);
9995   }
9996 
9997   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9998   static IntRange meet(IntRange L, IntRange R) {
9999     return IntRange(std::min(L.Width, R.Width),
10000                     L.NonNegative || R.NonNegative);
10001   }
10002 };
10003 
10004 } // namespace
10005 
10006 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10007                               unsigned MaxWidth) {
10008   if (value.isSigned() && value.isNegative())
10009     return IntRange(value.getMinSignedBits(), false);
10010 
10011   if (value.getBitWidth() > MaxWidth)
10012     value = value.trunc(MaxWidth);
10013 
10014   // isNonNegative() just checks the sign bit without considering
10015   // signedness.
10016   return IntRange(value.getActiveBits(), true);
10017 }
10018 
10019 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10020                               unsigned MaxWidth) {
10021   if (result.isInt())
10022     return GetValueRange(C, result.getInt(), MaxWidth);
10023 
10024   if (result.isVector()) {
10025     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10026     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10027       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10028       R = IntRange::join(R, El);
10029     }
10030     return R;
10031   }
10032 
10033   if (result.isComplexInt()) {
10034     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10035     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10036     return IntRange::join(R, I);
10037   }
10038 
10039   // This can happen with lossless casts to intptr_t of "based" lvalues.
10040   // Assume it might use arbitrary bits.
10041   // FIXME: The only reason we need to pass the type in here is to get
10042   // the sign right on this one case.  It would be nice if APValue
10043   // preserved this.
10044   assert(result.isLValue() || result.isAddrLabelDiff());
10045   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10046 }
10047 
10048 static QualType GetExprType(const Expr *E) {
10049   QualType Ty = E->getType();
10050   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10051     Ty = AtomicRHS->getValueType();
10052   return Ty;
10053 }
10054 
10055 /// Pseudo-evaluate the given integer expression, estimating the
10056 /// range of values it might take.
10057 ///
10058 /// \param MaxWidth - the width to which the value will be truncated
10059 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10060                              bool InConstantContext) {
10061   E = E->IgnoreParens();
10062 
10063   // Try a full evaluation first.
10064   Expr::EvalResult result;
10065   if (E->EvaluateAsRValue(result, C, InConstantContext))
10066     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10067 
10068   // I think we only want to look through implicit casts here; if the
10069   // user has an explicit widening cast, we should treat the value as
10070   // being of the new, wider type.
10071   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10072     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10073       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10074 
10075     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10076 
10077     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10078                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10079 
10080     // Assume that non-integer casts can span the full range of the type.
10081     if (!isIntegerCast)
10082       return OutputTypeRange;
10083 
10084     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10085                                      std::min(MaxWidth, OutputTypeRange.Width),
10086                                      InConstantContext);
10087 
10088     // Bail out if the subexpr's range is as wide as the cast type.
10089     if (SubRange.Width >= OutputTypeRange.Width)
10090       return OutputTypeRange;
10091 
10092     // Otherwise, we take the smaller width, and we're non-negative if
10093     // either the output type or the subexpr is.
10094     return IntRange(SubRange.Width,
10095                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10096   }
10097 
10098   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10099     // If we can fold the condition, just take that operand.
10100     bool CondResult;
10101     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10102       return GetExprRange(C,
10103                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10104                           MaxWidth, InConstantContext);
10105 
10106     // Otherwise, conservatively merge.
10107     IntRange L =
10108         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10109     IntRange R =
10110         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10111     return IntRange::join(L, R);
10112   }
10113 
10114   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10115     switch (BO->getOpcode()) {
10116     case BO_Cmp:
10117       llvm_unreachable("builtin <=> should have class type");
10118 
10119     // Boolean-valued operations are single-bit and positive.
10120     case BO_LAnd:
10121     case BO_LOr:
10122     case BO_LT:
10123     case BO_GT:
10124     case BO_LE:
10125     case BO_GE:
10126     case BO_EQ:
10127     case BO_NE:
10128       return IntRange::forBoolType();
10129 
10130     // The type of the assignments is the type of the LHS, so the RHS
10131     // is not necessarily the same type.
10132     case BO_MulAssign:
10133     case BO_DivAssign:
10134     case BO_RemAssign:
10135     case BO_AddAssign:
10136     case BO_SubAssign:
10137     case BO_XorAssign:
10138     case BO_OrAssign:
10139       // TODO: bitfields?
10140       return IntRange::forValueOfType(C, GetExprType(E));
10141 
10142     // Simple assignments just pass through the RHS, which will have
10143     // been coerced to the LHS type.
10144     case BO_Assign:
10145       // TODO: bitfields?
10146       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10147 
10148     // Operations with opaque sources are black-listed.
10149     case BO_PtrMemD:
10150     case BO_PtrMemI:
10151       return IntRange::forValueOfType(C, GetExprType(E));
10152 
10153     // Bitwise-and uses the *infinum* of the two source ranges.
10154     case BO_And:
10155     case BO_AndAssign:
10156       return IntRange::meet(
10157           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10158           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10159 
10160     // Left shift gets black-listed based on a judgement call.
10161     case BO_Shl:
10162       // ...except that we want to treat '1 << (blah)' as logically
10163       // positive.  It's an important idiom.
10164       if (IntegerLiteral *I
10165             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10166         if (I->getValue() == 1) {
10167           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10168           return IntRange(R.Width, /*NonNegative*/ true);
10169         }
10170       }
10171       LLVM_FALLTHROUGH;
10172 
10173     case BO_ShlAssign:
10174       return IntRange::forValueOfType(C, GetExprType(E));
10175 
10176     // Right shift by a constant can narrow its left argument.
10177     case BO_Shr:
10178     case BO_ShrAssign: {
10179       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10180 
10181       // If the shift amount is a positive constant, drop the width by
10182       // that much.
10183       llvm::APSInt shift;
10184       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10185           shift.isNonNegative()) {
10186         unsigned zext = shift.getZExtValue();
10187         if (zext >= L.Width)
10188           L.Width = (L.NonNegative ? 0 : 1);
10189         else
10190           L.Width -= zext;
10191       }
10192 
10193       return L;
10194     }
10195 
10196     // Comma acts as its right operand.
10197     case BO_Comma:
10198       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10199 
10200     // Black-list pointer subtractions.
10201     case BO_Sub:
10202       if (BO->getLHS()->getType()->isPointerType())
10203         return IntRange::forValueOfType(C, GetExprType(E));
10204       break;
10205 
10206     // The width of a division result is mostly determined by the size
10207     // of the LHS.
10208     case BO_Div: {
10209       // Don't 'pre-truncate' the operands.
10210       unsigned opWidth = C.getIntWidth(GetExprType(E));
10211       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10212 
10213       // If the divisor is constant, use that.
10214       llvm::APSInt divisor;
10215       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10216         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10217         if (log2 >= L.Width)
10218           L.Width = (L.NonNegative ? 0 : 1);
10219         else
10220           L.Width = std::min(L.Width - log2, MaxWidth);
10221         return L;
10222       }
10223 
10224       // Otherwise, just use the LHS's width.
10225       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10226       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10227     }
10228 
10229     // The result of a remainder can't be larger than the result of
10230     // either side.
10231     case BO_Rem: {
10232       // Don't 'pre-truncate' the operands.
10233       unsigned opWidth = C.getIntWidth(GetExprType(E));
10234       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10235       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10236 
10237       IntRange meet = IntRange::meet(L, R);
10238       meet.Width = std::min(meet.Width, MaxWidth);
10239       return meet;
10240     }
10241 
10242     // The default behavior is okay for these.
10243     case BO_Mul:
10244     case BO_Add:
10245     case BO_Xor:
10246     case BO_Or:
10247       break;
10248     }
10249 
10250     // The default case is to treat the operation as if it were closed
10251     // on the narrowest type that encompasses both operands.
10252     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10253     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10254     return IntRange::join(L, R);
10255   }
10256 
10257   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10258     switch (UO->getOpcode()) {
10259     // Boolean-valued operations are white-listed.
10260     case UO_LNot:
10261       return IntRange::forBoolType();
10262 
10263     // Operations with opaque sources are black-listed.
10264     case UO_Deref:
10265     case UO_AddrOf: // should be impossible
10266       return IntRange::forValueOfType(C, GetExprType(E));
10267 
10268     default:
10269       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10270     }
10271   }
10272 
10273   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10274     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10275 
10276   if (const auto *BitField = E->getSourceBitField())
10277     return IntRange(BitField->getBitWidthValue(C),
10278                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10279 
10280   return IntRange::forValueOfType(C, GetExprType(E));
10281 }
10282 
10283 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10284                              bool InConstantContext) {
10285   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10286 }
10287 
10288 /// Checks whether the given value, which currently has the given
10289 /// source semantics, has the same value when coerced through the
10290 /// target semantics.
10291 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10292                                  const llvm::fltSemantics &Src,
10293                                  const llvm::fltSemantics &Tgt) {
10294   llvm::APFloat truncated = value;
10295 
10296   bool ignored;
10297   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10298   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10299 
10300   return truncated.bitwiseIsEqual(value);
10301 }
10302 
10303 /// Checks whether the given value, which currently has the given
10304 /// source semantics, has the same value when coerced through the
10305 /// target semantics.
10306 ///
10307 /// The value might be a vector of floats (or a complex number).
10308 static bool IsSameFloatAfterCast(const APValue &value,
10309                                  const llvm::fltSemantics &Src,
10310                                  const llvm::fltSemantics &Tgt) {
10311   if (value.isFloat())
10312     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10313 
10314   if (value.isVector()) {
10315     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10316       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10317         return false;
10318     return true;
10319   }
10320 
10321   assert(value.isComplexFloat());
10322   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10323           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10324 }
10325 
10326 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10327                                        bool IsListInit = false);
10328 
10329 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10330   // Suppress cases where we are comparing against an enum constant.
10331   if (const DeclRefExpr *DR =
10332       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10333     if (isa<EnumConstantDecl>(DR->getDecl()))
10334       return true;
10335 
10336   // Suppress cases where the value is expanded from a macro, unless that macro
10337   // is how a language represents a boolean literal. This is the case in both C
10338   // and Objective-C.
10339   SourceLocation BeginLoc = E->getBeginLoc();
10340   if (BeginLoc.isMacroID()) {
10341     StringRef MacroName = Lexer::getImmediateMacroName(
10342         BeginLoc, S.getSourceManager(), S.getLangOpts());
10343     return MacroName != "YES" && MacroName != "NO" &&
10344            MacroName != "true" && MacroName != "false";
10345   }
10346 
10347   return false;
10348 }
10349 
10350 static bool isKnownToHaveUnsignedValue(Expr *E) {
10351   return E->getType()->isIntegerType() &&
10352          (!E->getType()->isSignedIntegerType() ||
10353           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10354 }
10355 
10356 namespace {
10357 /// The promoted range of values of a type. In general this has the
10358 /// following structure:
10359 ///
10360 ///     |-----------| . . . |-----------|
10361 ///     ^           ^       ^           ^
10362 ///    Min       HoleMin  HoleMax      Max
10363 ///
10364 /// ... where there is only a hole if a signed type is promoted to unsigned
10365 /// (in which case Min and Max are the smallest and largest representable
10366 /// values).
10367 struct PromotedRange {
10368   // Min, or HoleMax if there is a hole.
10369   llvm::APSInt PromotedMin;
10370   // Max, or HoleMin if there is a hole.
10371   llvm::APSInt PromotedMax;
10372 
10373   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10374     if (R.Width == 0)
10375       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10376     else if (R.Width >= BitWidth && !Unsigned) {
10377       // Promotion made the type *narrower*. This happens when promoting
10378       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10379       // Treat all values of 'signed int' as being in range for now.
10380       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10381       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10382     } else {
10383       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10384                         .extOrTrunc(BitWidth);
10385       PromotedMin.setIsUnsigned(Unsigned);
10386 
10387       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10388                         .extOrTrunc(BitWidth);
10389       PromotedMax.setIsUnsigned(Unsigned);
10390     }
10391   }
10392 
10393   // Determine whether this range is contiguous (has no hole).
10394   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10395 
10396   // Where a constant value is within the range.
10397   enum ComparisonResult {
10398     LT = 0x1,
10399     LE = 0x2,
10400     GT = 0x4,
10401     GE = 0x8,
10402     EQ = 0x10,
10403     NE = 0x20,
10404     InRangeFlag = 0x40,
10405 
10406     Less = LE | LT | NE,
10407     Min = LE | InRangeFlag,
10408     InRange = InRangeFlag,
10409     Max = GE | InRangeFlag,
10410     Greater = GE | GT | NE,
10411 
10412     OnlyValue = LE | GE | EQ | InRangeFlag,
10413     InHole = NE
10414   };
10415 
10416   ComparisonResult compare(const llvm::APSInt &Value) const {
10417     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10418            Value.isUnsigned() == PromotedMin.isUnsigned());
10419     if (!isContiguous()) {
10420       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10421       if (Value.isMinValue()) return Min;
10422       if (Value.isMaxValue()) return Max;
10423       if (Value >= PromotedMin) return InRange;
10424       if (Value <= PromotedMax) return InRange;
10425       return InHole;
10426     }
10427 
10428     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10429     case -1: return Less;
10430     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10431     case 1:
10432       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10433       case -1: return InRange;
10434       case 0: return Max;
10435       case 1: return Greater;
10436       }
10437     }
10438 
10439     llvm_unreachable("impossible compare result");
10440   }
10441 
10442   static llvm::Optional<StringRef>
10443   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10444     if (Op == BO_Cmp) {
10445       ComparisonResult LTFlag = LT, GTFlag = GT;
10446       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10447 
10448       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10449       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10450       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10451       return llvm::None;
10452     }
10453 
10454     ComparisonResult TrueFlag, FalseFlag;
10455     if (Op == BO_EQ) {
10456       TrueFlag = EQ;
10457       FalseFlag = NE;
10458     } else if (Op == BO_NE) {
10459       TrueFlag = NE;
10460       FalseFlag = EQ;
10461     } else {
10462       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10463         TrueFlag = LT;
10464         FalseFlag = GE;
10465       } else {
10466         TrueFlag = GT;
10467         FalseFlag = LE;
10468       }
10469       if (Op == BO_GE || Op == BO_LE)
10470         std::swap(TrueFlag, FalseFlag);
10471     }
10472     if (R & TrueFlag)
10473       return StringRef("true");
10474     if (R & FalseFlag)
10475       return StringRef("false");
10476     return llvm::None;
10477   }
10478 };
10479 }
10480 
10481 static bool HasEnumType(Expr *E) {
10482   // Strip off implicit integral promotions.
10483   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10484     if (ICE->getCastKind() != CK_IntegralCast &&
10485         ICE->getCastKind() != CK_NoOp)
10486       break;
10487     E = ICE->getSubExpr();
10488   }
10489 
10490   return E->getType()->isEnumeralType();
10491 }
10492 
10493 static int classifyConstantValue(Expr *Constant) {
10494   // The values of this enumeration are used in the diagnostics
10495   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10496   enum ConstantValueKind {
10497     Miscellaneous = 0,
10498     LiteralTrue,
10499     LiteralFalse
10500   };
10501   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10502     return BL->getValue() ? ConstantValueKind::LiteralTrue
10503                           : ConstantValueKind::LiteralFalse;
10504   return ConstantValueKind::Miscellaneous;
10505 }
10506 
10507 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10508                                         Expr *Constant, Expr *Other,
10509                                         const llvm::APSInt &Value,
10510                                         bool RhsConstant) {
10511   if (S.inTemplateInstantiation())
10512     return false;
10513 
10514   Expr *OriginalOther = Other;
10515 
10516   Constant = Constant->IgnoreParenImpCasts();
10517   Other = Other->IgnoreParenImpCasts();
10518 
10519   // Suppress warnings on tautological comparisons between values of the same
10520   // enumeration type. There are only two ways we could warn on this:
10521   //  - If the constant is outside the range of representable values of
10522   //    the enumeration. In such a case, we should warn about the cast
10523   //    to enumeration type, not about the comparison.
10524   //  - If the constant is the maximum / minimum in-range value. For an
10525   //    enumeratin type, such comparisons can be meaningful and useful.
10526   if (Constant->getType()->isEnumeralType() &&
10527       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10528     return false;
10529 
10530   // TODO: Investigate using GetExprRange() to get tighter bounds
10531   // on the bit ranges.
10532   QualType OtherT = Other->getType();
10533   if (const auto *AT = OtherT->getAs<AtomicType>())
10534     OtherT = AT->getValueType();
10535   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10536 
10537   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10538   // (Namely, macOS).
10539   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10540                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10541                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10542 
10543   // Whether we're treating Other as being a bool because of the form of
10544   // expression despite it having another type (typically 'int' in C).
10545   bool OtherIsBooleanDespiteType =
10546       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10547   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10548     OtherRange = IntRange::forBoolType();
10549 
10550   // Determine the promoted range of the other type and see if a comparison of
10551   // the constant against that range is tautological.
10552   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10553                                    Value.isUnsigned());
10554   auto Cmp = OtherPromotedRange.compare(Value);
10555   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10556   if (!Result)
10557     return false;
10558 
10559   // Suppress the diagnostic for an in-range comparison if the constant comes
10560   // from a macro or enumerator. We don't want to diagnose
10561   //
10562   //   some_long_value <= INT_MAX
10563   //
10564   // when sizeof(int) == sizeof(long).
10565   bool InRange = Cmp & PromotedRange::InRangeFlag;
10566   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10567     return false;
10568 
10569   // If this is a comparison to an enum constant, include that
10570   // constant in the diagnostic.
10571   const EnumConstantDecl *ED = nullptr;
10572   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10573     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10574 
10575   // Should be enough for uint128 (39 decimal digits)
10576   SmallString<64> PrettySourceValue;
10577   llvm::raw_svector_ostream OS(PrettySourceValue);
10578   if (ED) {
10579     OS << '\'' << *ED << "' (" << Value << ")";
10580   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10581                Constant->IgnoreParenImpCasts())) {
10582     OS << (BL->getValue() ? "YES" : "NO");
10583   } else {
10584     OS << Value;
10585   }
10586 
10587   if (IsObjCSignedCharBool) {
10588     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10589                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10590                               << OS.str() << *Result);
10591     return true;
10592   }
10593 
10594   // FIXME: We use a somewhat different formatting for the in-range cases and
10595   // cases involving boolean values for historical reasons. We should pick a
10596   // consistent way of presenting these diagnostics.
10597   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10598 
10599     S.DiagRuntimeBehavior(
10600         E->getOperatorLoc(), E,
10601         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10602                          : diag::warn_tautological_bool_compare)
10603             << OS.str() << classifyConstantValue(Constant) << OtherT
10604             << OtherIsBooleanDespiteType << *Result
10605             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10606   } else {
10607     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10608                         ? (HasEnumType(OriginalOther)
10609                                ? diag::warn_unsigned_enum_always_true_comparison
10610                                : diag::warn_unsigned_always_true_comparison)
10611                         : diag::warn_tautological_constant_compare;
10612 
10613     S.Diag(E->getOperatorLoc(), Diag)
10614         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10615         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10616   }
10617 
10618   return true;
10619 }
10620 
10621 /// Analyze the operands of the given comparison.  Implements the
10622 /// fallback case from AnalyzeComparison.
10623 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10624   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10625   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10626 }
10627 
10628 /// Implements -Wsign-compare.
10629 ///
10630 /// \param E the binary operator to check for warnings
10631 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10632   // The type the comparison is being performed in.
10633   QualType T = E->getLHS()->getType();
10634 
10635   // Only analyze comparison operators where both sides have been converted to
10636   // the same type.
10637   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10638     return AnalyzeImpConvsInComparison(S, E);
10639 
10640   // Don't analyze value-dependent comparisons directly.
10641   if (E->isValueDependent())
10642     return AnalyzeImpConvsInComparison(S, E);
10643 
10644   Expr *LHS = E->getLHS();
10645   Expr *RHS = E->getRHS();
10646 
10647   if (T->isIntegralType(S.Context)) {
10648     llvm::APSInt RHSValue;
10649     llvm::APSInt LHSValue;
10650 
10651     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10652     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10653 
10654     // We don't care about expressions whose result is a constant.
10655     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10656       return AnalyzeImpConvsInComparison(S, E);
10657 
10658     // We only care about expressions where just one side is literal
10659     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10660       // Is the constant on the RHS or LHS?
10661       const bool RhsConstant = IsRHSIntegralLiteral;
10662       Expr *Const = RhsConstant ? RHS : LHS;
10663       Expr *Other = RhsConstant ? LHS : RHS;
10664       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10665 
10666       // Check whether an integer constant comparison results in a value
10667       // of 'true' or 'false'.
10668       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10669         return AnalyzeImpConvsInComparison(S, E);
10670     }
10671   }
10672 
10673   if (!T->hasUnsignedIntegerRepresentation()) {
10674     // We don't do anything special if this isn't an unsigned integral
10675     // comparison:  we're only interested in integral comparisons, and
10676     // signed comparisons only happen in cases we don't care to warn about.
10677     return AnalyzeImpConvsInComparison(S, E);
10678   }
10679 
10680   LHS = LHS->IgnoreParenImpCasts();
10681   RHS = RHS->IgnoreParenImpCasts();
10682 
10683   if (!S.getLangOpts().CPlusPlus) {
10684     // Avoid warning about comparison of integers with different signs when
10685     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10686     // the type of `E`.
10687     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10688       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10689     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10690       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10691   }
10692 
10693   // Check to see if one of the (unmodified) operands is of different
10694   // signedness.
10695   Expr *signedOperand, *unsignedOperand;
10696   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10697     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10698            "unsigned comparison between two signed integer expressions?");
10699     signedOperand = LHS;
10700     unsignedOperand = RHS;
10701   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10702     signedOperand = RHS;
10703     unsignedOperand = LHS;
10704   } else {
10705     return AnalyzeImpConvsInComparison(S, E);
10706   }
10707 
10708   // Otherwise, calculate the effective range of the signed operand.
10709   IntRange signedRange =
10710       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10711 
10712   // Go ahead and analyze implicit conversions in the operands.  Note
10713   // that we skip the implicit conversions on both sides.
10714   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10715   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10716 
10717   // If the signed range is non-negative, -Wsign-compare won't fire.
10718   if (signedRange.NonNegative)
10719     return;
10720 
10721   // For (in)equality comparisons, if the unsigned operand is a
10722   // constant which cannot collide with a overflowed signed operand,
10723   // then reinterpreting the signed operand as unsigned will not
10724   // change the result of the comparison.
10725   if (E->isEqualityOp()) {
10726     unsigned comparisonWidth = S.Context.getIntWidth(T);
10727     IntRange unsignedRange =
10728         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10729 
10730     // We should never be unable to prove that the unsigned operand is
10731     // non-negative.
10732     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10733 
10734     if (unsignedRange.Width < comparisonWidth)
10735       return;
10736   }
10737 
10738   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10739                         S.PDiag(diag::warn_mixed_sign_comparison)
10740                             << LHS->getType() << RHS->getType()
10741                             << LHS->getSourceRange() << RHS->getSourceRange());
10742 }
10743 
10744 /// Analyzes an attempt to assign the given value to a bitfield.
10745 ///
10746 /// Returns true if there was something fishy about the attempt.
10747 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10748                                       SourceLocation InitLoc) {
10749   assert(Bitfield->isBitField());
10750   if (Bitfield->isInvalidDecl())
10751     return false;
10752 
10753   // White-list bool bitfields.
10754   QualType BitfieldType = Bitfield->getType();
10755   if (BitfieldType->isBooleanType())
10756      return false;
10757 
10758   if (BitfieldType->isEnumeralType()) {
10759     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10760     // If the underlying enum type was not explicitly specified as an unsigned
10761     // type and the enum contain only positive values, MSVC++ will cause an
10762     // inconsistency by storing this as a signed type.
10763     if (S.getLangOpts().CPlusPlus11 &&
10764         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10765         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10766         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10767       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10768         << BitfieldEnumDecl->getNameAsString();
10769     }
10770   }
10771 
10772   if (Bitfield->getType()->isBooleanType())
10773     return false;
10774 
10775   // Ignore value- or type-dependent expressions.
10776   if (Bitfield->getBitWidth()->isValueDependent() ||
10777       Bitfield->getBitWidth()->isTypeDependent() ||
10778       Init->isValueDependent() ||
10779       Init->isTypeDependent())
10780     return false;
10781 
10782   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10783   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10784 
10785   Expr::EvalResult Result;
10786   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10787                                    Expr::SE_AllowSideEffects)) {
10788     // The RHS is not constant.  If the RHS has an enum type, make sure the
10789     // bitfield is wide enough to hold all the values of the enum without
10790     // truncation.
10791     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10792       EnumDecl *ED = EnumTy->getDecl();
10793       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10794 
10795       // Enum types are implicitly signed on Windows, so check if there are any
10796       // negative enumerators to see if the enum was intended to be signed or
10797       // not.
10798       bool SignedEnum = ED->getNumNegativeBits() > 0;
10799 
10800       // Check for surprising sign changes when assigning enum values to a
10801       // bitfield of different signedness.  If the bitfield is signed and we
10802       // have exactly the right number of bits to store this unsigned enum,
10803       // suggest changing the enum to an unsigned type. This typically happens
10804       // on Windows where unfixed enums always use an underlying type of 'int'.
10805       unsigned DiagID = 0;
10806       if (SignedEnum && !SignedBitfield) {
10807         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10808       } else if (SignedBitfield && !SignedEnum &&
10809                  ED->getNumPositiveBits() == FieldWidth) {
10810         DiagID = diag::warn_signed_bitfield_enum_conversion;
10811       }
10812 
10813       if (DiagID) {
10814         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10815         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10816         SourceRange TypeRange =
10817             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10818         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10819             << SignedEnum << TypeRange;
10820       }
10821 
10822       // Compute the required bitwidth. If the enum has negative values, we need
10823       // one more bit than the normal number of positive bits to represent the
10824       // sign bit.
10825       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10826                                                   ED->getNumNegativeBits())
10827                                        : ED->getNumPositiveBits();
10828 
10829       // Check the bitwidth.
10830       if (BitsNeeded > FieldWidth) {
10831         Expr *WidthExpr = Bitfield->getBitWidth();
10832         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10833             << Bitfield << ED;
10834         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10835             << BitsNeeded << ED << WidthExpr->getSourceRange();
10836       }
10837     }
10838 
10839     return false;
10840   }
10841 
10842   llvm::APSInt Value = Result.Val.getInt();
10843 
10844   unsigned OriginalWidth = Value.getBitWidth();
10845 
10846   if (!Value.isSigned() || Value.isNegative())
10847     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10848       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10849         OriginalWidth = Value.getMinSignedBits();
10850 
10851   if (OriginalWidth <= FieldWidth)
10852     return false;
10853 
10854   // Compute the value which the bitfield will contain.
10855   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10856   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10857 
10858   // Check whether the stored value is equal to the original value.
10859   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10860   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10861     return false;
10862 
10863   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10864   // therefore don't strictly fit into a signed bitfield of width 1.
10865   if (FieldWidth == 1 && Value == 1)
10866     return false;
10867 
10868   std::string PrettyValue = Value.toString(10);
10869   std::string PrettyTrunc = TruncatedValue.toString(10);
10870 
10871   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10872     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10873     << Init->getSourceRange();
10874 
10875   return true;
10876 }
10877 
10878 /// Analyze the given simple or compound assignment for warning-worthy
10879 /// operations.
10880 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10881   // Just recurse on the LHS.
10882   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10883 
10884   // We want to recurse on the RHS as normal unless we're assigning to
10885   // a bitfield.
10886   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10887     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10888                                   E->getOperatorLoc())) {
10889       // Recurse, ignoring any implicit conversions on the RHS.
10890       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10891                                         E->getOperatorLoc());
10892     }
10893   }
10894 
10895   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10896 
10897   // Diagnose implicitly sequentially-consistent atomic assignment.
10898   if (E->getLHS()->getType()->isAtomicType())
10899     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10900 }
10901 
10902 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10903 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10904                             SourceLocation CContext, unsigned diag,
10905                             bool pruneControlFlow = false) {
10906   if (pruneControlFlow) {
10907     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10908                           S.PDiag(diag)
10909                               << SourceType << T << E->getSourceRange()
10910                               << SourceRange(CContext));
10911     return;
10912   }
10913   S.Diag(E->getExprLoc(), diag)
10914     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10915 }
10916 
10917 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10918 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10919                             SourceLocation CContext,
10920                             unsigned diag, bool pruneControlFlow = false) {
10921   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10922 }
10923 
10924 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10925   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10926       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10927 }
10928 
10929 static void adornObjCBoolConversionDiagWithTernaryFixit(
10930     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10931   Expr *Ignored = SourceExpr->IgnoreImplicit();
10932   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10933     Ignored = OVE->getSourceExpr();
10934   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10935                      isa<BinaryOperator>(Ignored) ||
10936                      isa<CXXOperatorCallExpr>(Ignored);
10937   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10938   if (NeedsParens)
10939     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10940             << FixItHint::CreateInsertion(EndLoc, ")");
10941   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10942 }
10943 
10944 /// Diagnose an implicit cast from a floating point value to an integer value.
10945 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10946                                     SourceLocation CContext) {
10947   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10948   const bool PruneWarnings = S.inTemplateInstantiation();
10949 
10950   Expr *InnerE = E->IgnoreParenImpCasts();
10951   // We also want to warn on, e.g., "int i = -1.234"
10952   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10953     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10954       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10955 
10956   const bool IsLiteral =
10957       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10958 
10959   llvm::APFloat Value(0.0);
10960   bool IsConstant =
10961     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10962   if (!IsConstant) {
10963     if (isObjCSignedCharBool(S, T)) {
10964       return adornObjCBoolConversionDiagWithTernaryFixit(
10965           S, E,
10966           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
10967               << E->getType());
10968     }
10969 
10970     return DiagnoseImpCast(S, E, T, CContext,
10971                            diag::warn_impcast_float_integer, PruneWarnings);
10972   }
10973 
10974   bool isExact = false;
10975 
10976   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10977                             T->hasUnsignedIntegerRepresentation());
10978   llvm::APFloat::opStatus Result = Value.convertToInteger(
10979       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10980 
10981   // FIXME: Force the precision of the source value down so we don't print
10982   // digits which are usually useless (we don't really care here if we
10983   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10984   // would automatically print the shortest representation, but it's a bit
10985   // tricky to implement.
10986   SmallString<16> PrettySourceValue;
10987   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10988   precision = (precision * 59 + 195) / 196;
10989   Value.toString(PrettySourceValue, precision);
10990 
10991   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
10992     return adornObjCBoolConversionDiagWithTernaryFixit(
10993         S, E,
10994         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
10995             << PrettySourceValue);
10996   }
10997 
10998   if (Result == llvm::APFloat::opOK && isExact) {
10999     if (IsLiteral) return;
11000     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11001                            PruneWarnings);
11002   }
11003 
11004   // Conversion of a floating-point value to a non-bool integer where the
11005   // integral part cannot be represented by the integer type is undefined.
11006   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11007     return DiagnoseImpCast(
11008         S, E, T, CContext,
11009         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11010                   : diag::warn_impcast_float_to_integer_out_of_range,
11011         PruneWarnings);
11012 
11013   unsigned DiagID = 0;
11014   if (IsLiteral) {
11015     // Warn on floating point literal to integer.
11016     DiagID = diag::warn_impcast_literal_float_to_integer;
11017   } else if (IntegerValue == 0) {
11018     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11019       return DiagnoseImpCast(S, E, T, CContext,
11020                              diag::warn_impcast_float_integer, PruneWarnings);
11021     }
11022     // Warn on non-zero to zero conversion.
11023     DiagID = diag::warn_impcast_float_to_integer_zero;
11024   } else {
11025     if (IntegerValue.isUnsigned()) {
11026       if (!IntegerValue.isMaxValue()) {
11027         return DiagnoseImpCast(S, E, T, CContext,
11028                                diag::warn_impcast_float_integer, PruneWarnings);
11029       }
11030     } else {  // IntegerValue.isSigned()
11031       if (!IntegerValue.isMaxSignedValue() &&
11032           !IntegerValue.isMinSignedValue()) {
11033         return DiagnoseImpCast(S, E, T, CContext,
11034                                diag::warn_impcast_float_integer, PruneWarnings);
11035       }
11036     }
11037     // Warn on evaluatable floating point expression to integer conversion.
11038     DiagID = diag::warn_impcast_float_to_integer;
11039   }
11040 
11041   SmallString<16> PrettyTargetValue;
11042   if (IsBool)
11043     PrettyTargetValue = Value.isZero() ? "false" : "true";
11044   else
11045     IntegerValue.toString(PrettyTargetValue);
11046 
11047   if (PruneWarnings) {
11048     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11049                           S.PDiag(DiagID)
11050                               << E->getType() << T.getUnqualifiedType()
11051                               << PrettySourceValue << PrettyTargetValue
11052                               << E->getSourceRange() << SourceRange(CContext));
11053   } else {
11054     S.Diag(E->getExprLoc(), DiagID)
11055         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11056         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11057   }
11058 }
11059 
11060 /// Analyze the given compound assignment for the possible losing of
11061 /// floating-point precision.
11062 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11063   assert(isa<CompoundAssignOperator>(E) &&
11064          "Must be compound assignment operation");
11065   // Recurse on the LHS and RHS in here
11066   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11067   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11068 
11069   if (E->getLHS()->getType()->isAtomicType())
11070     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11071 
11072   // Now check the outermost expression
11073   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11074   const auto *RBT = cast<CompoundAssignOperator>(E)
11075                         ->getComputationResultType()
11076                         ->getAs<BuiltinType>();
11077 
11078   // The below checks assume source is floating point.
11079   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11080 
11081   // If source is floating point but target is an integer.
11082   if (ResultBT->isInteger())
11083     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11084                            E->getExprLoc(), diag::warn_impcast_float_integer);
11085 
11086   if (!ResultBT->isFloatingPoint())
11087     return;
11088 
11089   // If both source and target are floating points, warn about losing precision.
11090   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11091       QualType(ResultBT, 0), QualType(RBT, 0));
11092   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11093     // warn about dropping FP rank.
11094     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11095                     diag::warn_impcast_float_result_precision);
11096 }
11097 
11098 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11099                                       IntRange Range) {
11100   if (!Range.Width) return "0";
11101 
11102   llvm::APSInt ValueInRange = Value;
11103   ValueInRange.setIsSigned(!Range.NonNegative);
11104   ValueInRange = ValueInRange.trunc(Range.Width);
11105   return ValueInRange.toString(10);
11106 }
11107 
11108 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11109   if (!isa<ImplicitCastExpr>(Ex))
11110     return false;
11111 
11112   Expr *InnerE = Ex->IgnoreParenImpCasts();
11113   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11114   const Type *Source =
11115     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11116   if (Target->isDependentType())
11117     return false;
11118 
11119   const BuiltinType *FloatCandidateBT =
11120     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11121   const Type *BoolCandidateType = ToBool ? Target : Source;
11122 
11123   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11124           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11125 }
11126 
11127 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11128                                              SourceLocation CC) {
11129   unsigned NumArgs = TheCall->getNumArgs();
11130   for (unsigned i = 0; i < NumArgs; ++i) {
11131     Expr *CurrA = TheCall->getArg(i);
11132     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11133       continue;
11134 
11135     bool IsSwapped = ((i > 0) &&
11136         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11137     IsSwapped |= ((i < (NumArgs - 1)) &&
11138         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11139     if (IsSwapped) {
11140       // Warn on this floating-point to bool conversion.
11141       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11142                       CurrA->getType(), CC,
11143                       diag::warn_impcast_floating_point_to_bool);
11144     }
11145   }
11146 }
11147 
11148 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11149                                    SourceLocation CC) {
11150   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11151                         E->getExprLoc()))
11152     return;
11153 
11154   // Don't warn on functions which have return type nullptr_t.
11155   if (isa<CallExpr>(E))
11156     return;
11157 
11158   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11159   const Expr::NullPointerConstantKind NullKind =
11160       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11161   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11162     return;
11163 
11164   // Return if target type is a safe conversion.
11165   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11166       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11167     return;
11168 
11169   SourceLocation Loc = E->getSourceRange().getBegin();
11170 
11171   // Venture through the macro stacks to get to the source of macro arguments.
11172   // The new location is a better location than the complete location that was
11173   // passed in.
11174   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11175   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11176 
11177   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11178   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11179     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11180         Loc, S.SourceMgr, S.getLangOpts());
11181     if (MacroName == "NULL")
11182       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11183   }
11184 
11185   // Only warn if the null and context location are in the same macro expansion.
11186   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11187     return;
11188 
11189   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11190       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11191       << FixItHint::CreateReplacement(Loc,
11192                                       S.getFixItZeroLiteralForType(T, Loc));
11193 }
11194 
11195 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11196                                   ObjCArrayLiteral *ArrayLiteral);
11197 
11198 static void
11199 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11200                            ObjCDictionaryLiteral *DictionaryLiteral);
11201 
11202 /// Check a single element within a collection literal against the
11203 /// target element type.
11204 static void checkObjCCollectionLiteralElement(Sema &S,
11205                                               QualType TargetElementType,
11206                                               Expr *Element,
11207                                               unsigned ElementKind) {
11208   // Skip a bitcast to 'id' or qualified 'id'.
11209   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11210     if (ICE->getCastKind() == CK_BitCast &&
11211         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11212       Element = ICE->getSubExpr();
11213   }
11214 
11215   QualType ElementType = Element->getType();
11216   ExprResult ElementResult(Element);
11217   if (ElementType->getAs<ObjCObjectPointerType>() &&
11218       S.CheckSingleAssignmentConstraints(TargetElementType,
11219                                          ElementResult,
11220                                          false, false)
11221         != Sema::Compatible) {
11222     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11223         << ElementType << ElementKind << TargetElementType
11224         << Element->getSourceRange();
11225   }
11226 
11227   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11228     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11229   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11230     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11231 }
11232 
11233 /// Check an Objective-C array literal being converted to the given
11234 /// target type.
11235 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11236                                   ObjCArrayLiteral *ArrayLiteral) {
11237   if (!S.NSArrayDecl)
11238     return;
11239 
11240   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11241   if (!TargetObjCPtr)
11242     return;
11243 
11244   if (TargetObjCPtr->isUnspecialized() ||
11245       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11246         != S.NSArrayDecl->getCanonicalDecl())
11247     return;
11248 
11249   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11250   if (TypeArgs.size() != 1)
11251     return;
11252 
11253   QualType TargetElementType = TypeArgs[0];
11254   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11255     checkObjCCollectionLiteralElement(S, TargetElementType,
11256                                       ArrayLiteral->getElement(I),
11257                                       0);
11258   }
11259 }
11260 
11261 /// Check an Objective-C dictionary literal being converted to the given
11262 /// target type.
11263 static void
11264 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11265                            ObjCDictionaryLiteral *DictionaryLiteral) {
11266   if (!S.NSDictionaryDecl)
11267     return;
11268 
11269   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11270   if (!TargetObjCPtr)
11271     return;
11272 
11273   if (TargetObjCPtr->isUnspecialized() ||
11274       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11275         != S.NSDictionaryDecl->getCanonicalDecl())
11276     return;
11277 
11278   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11279   if (TypeArgs.size() != 2)
11280     return;
11281 
11282   QualType TargetKeyType = TypeArgs[0];
11283   QualType TargetObjectType = TypeArgs[1];
11284   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11285     auto Element = DictionaryLiteral->getKeyValueElement(I);
11286     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11287     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11288   }
11289 }
11290 
11291 // Helper function to filter out cases for constant width constant conversion.
11292 // Don't warn on char array initialization or for non-decimal values.
11293 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11294                                           SourceLocation CC) {
11295   // If initializing from a constant, and the constant starts with '0',
11296   // then it is a binary, octal, or hexadecimal.  Allow these constants
11297   // to fill all the bits, even if there is a sign change.
11298   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11299     const char FirstLiteralCharacter =
11300         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11301     if (FirstLiteralCharacter == '0')
11302       return false;
11303   }
11304 
11305   // If the CC location points to a '{', and the type is char, then assume
11306   // assume it is an array initialization.
11307   if (CC.isValid() && T->isCharType()) {
11308     const char FirstContextCharacter =
11309         S.getSourceManager().getCharacterData(CC)[0];
11310     if (FirstContextCharacter == '{')
11311       return false;
11312   }
11313 
11314   return true;
11315 }
11316 
11317 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11318   const auto *IL = dyn_cast<IntegerLiteral>(E);
11319   if (!IL) {
11320     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11321       if (UO->getOpcode() == UO_Minus)
11322         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11323     }
11324   }
11325 
11326   return IL;
11327 }
11328 
11329 static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
11330                                           Expr *LHS, Expr *RHS) {
11331   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
11332   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
11333 
11334   const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
11335   if (!LHSEnumType)
11336     return;
11337   const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
11338   if (!RHSEnumType)
11339     return;
11340 
11341   // Ignore anonymous enums.
11342   if (!LHSEnumType->getDecl()->hasNameForLinkage())
11343     return;
11344   if (!RHSEnumType->getDecl()->hasNameForLinkage())
11345     return;
11346 
11347   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
11348     return;
11349 
11350   S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
11351       << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
11352       << RHS->getSourceRange();
11353 }
11354 
11355 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11356   E = E->IgnoreParenImpCasts();
11357   SourceLocation ExprLoc = E->getExprLoc();
11358 
11359   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11360     BinaryOperator::Opcode Opc = BO->getOpcode();
11361     Expr::EvalResult Result;
11362     // Do not diagnose unsigned shifts.
11363     if (Opc == BO_Shl) {
11364       const auto *LHS = getIntegerLiteral(BO->getLHS());
11365       const auto *RHS = getIntegerLiteral(BO->getRHS());
11366       if (LHS && LHS->getValue() == 0)
11367         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11368       else if (!E->isValueDependent() && LHS && RHS &&
11369                RHS->getValue().isNonNegative() &&
11370                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11371         S.Diag(ExprLoc, diag::warn_left_shift_always)
11372             << (Result.Val.getInt() != 0);
11373       else if (E->getType()->isSignedIntegerType())
11374         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11375     }
11376   }
11377 
11378   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11379     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11380     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11381     if (!LHS || !RHS)
11382       return;
11383     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11384         (RHS->getValue() == 0 || RHS->getValue() == 1))
11385       // Do not diagnose common idioms.
11386       return;
11387     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11388       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11389   }
11390 }
11391 
11392 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11393                                     SourceLocation CC,
11394                                     bool *ICContext = nullptr,
11395                                     bool IsListInit = false) {
11396   if (E->isTypeDependent() || E->isValueDependent()) return;
11397 
11398   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11399   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11400   if (Source == Target) return;
11401   if (Target->isDependentType()) return;
11402 
11403   // If the conversion context location is invalid don't complain. We also
11404   // don't want to emit a warning if the issue occurs from the expansion of
11405   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11406   // delay this check as long as possible. Once we detect we are in that
11407   // scenario, we just return.
11408   if (CC.isInvalid())
11409     return;
11410 
11411   if (Source->isAtomicType())
11412     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11413 
11414   // Diagnose implicit casts to bool.
11415   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11416     if (isa<StringLiteral>(E))
11417       // Warn on string literal to bool.  Checks for string literals in logical
11418       // and expressions, for instance, assert(0 && "error here"), are
11419       // prevented by a check in AnalyzeImplicitConversions().
11420       return DiagnoseImpCast(S, E, T, CC,
11421                              diag::warn_impcast_string_literal_to_bool);
11422     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11423         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11424       // This covers the literal expressions that evaluate to Objective-C
11425       // objects.
11426       return DiagnoseImpCast(S, E, T, CC,
11427                              diag::warn_impcast_objective_c_literal_to_bool);
11428     }
11429     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11430       // Warn on pointer to bool conversion that is always true.
11431       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11432                                      SourceRange(CC));
11433     }
11434   }
11435 
11436   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11437   // is a typedef for signed char (macOS), then that constant value has to be 1
11438   // or 0.
11439   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11440     Expr::EvalResult Result;
11441     if (E->EvaluateAsInt(Result, S.getASTContext(),
11442                          Expr::SE_AllowSideEffects)) {
11443       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11444         adornObjCBoolConversionDiagWithTernaryFixit(
11445             S, E,
11446             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11447                 << Result.Val.getInt().toString(10));
11448       }
11449       return;
11450     }
11451   }
11452 
11453   // Check implicit casts from Objective-C collection literals to specialized
11454   // collection types, e.g., NSArray<NSString *> *.
11455   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11456     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11457   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11458     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11459 
11460   // Strip vector types.
11461   if (isa<VectorType>(Source)) {
11462     if (!isa<VectorType>(Target)) {
11463       if (S.SourceMgr.isInSystemMacro(CC))
11464         return;
11465       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11466     }
11467 
11468     // If the vector cast is cast between two vectors of the same size, it is
11469     // a bitcast, not a conversion.
11470     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11471       return;
11472 
11473     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11474     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11475   }
11476   if (auto VecTy = dyn_cast<VectorType>(Target))
11477     Target = VecTy->getElementType().getTypePtr();
11478 
11479   // Strip complex types.
11480   if (isa<ComplexType>(Source)) {
11481     if (!isa<ComplexType>(Target)) {
11482       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11483         return;
11484 
11485       return DiagnoseImpCast(S, E, T, CC,
11486                              S.getLangOpts().CPlusPlus
11487                                  ? diag::err_impcast_complex_scalar
11488                                  : diag::warn_impcast_complex_scalar);
11489     }
11490 
11491     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11492     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11493   }
11494 
11495   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11496   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11497 
11498   // If the source is floating point...
11499   if (SourceBT && SourceBT->isFloatingPoint()) {
11500     // ...and the target is floating point...
11501     if (TargetBT && TargetBT->isFloatingPoint()) {
11502       // ...then warn if we're dropping FP rank.
11503 
11504       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11505           QualType(SourceBT, 0), QualType(TargetBT, 0));
11506       if (Order > 0) {
11507         // Don't warn about float constants that are precisely
11508         // representable in the target type.
11509         Expr::EvalResult result;
11510         if (E->EvaluateAsRValue(result, S.Context)) {
11511           // Value might be a float, a float vector, or a float complex.
11512           if (IsSameFloatAfterCast(result.Val,
11513                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11514                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11515             return;
11516         }
11517 
11518         if (S.SourceMgr.isInSystemMacro(CC))
11519           return;
11520 
11521         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11522       }
11523       // ... or possibly if we're increasing rank, too
11524       else if (Order < 0) {
11525         if (S.SourceMgr.isInSystemMacro(CC))
11526           return;
11527 
11528         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11529       }
11530       return;
11531     }
11532 
11533     // If the target is integral, always warn.
11534     if (TargetBT && TargetBT->isInteger()) {
11535       if (S.SourceMgr.isInSystemMacro(CC))
11536         return;
11537 
11538       DiagnoseFloatingImpCast(S, E, T, CC);
11539     }
11540 
11541     // Detect the case where a call result is converted from floating-point to
11542     // to bool, and the final argument to the call is converted from bool, to
11543     // discover this typo:
11544     //
11545     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11546     //
11547     // FIXME: This is an incredibly special case; is there some more general
11548     // way to detect this class of misplaced-parentheses bug?
11549     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11550       // Check last argument of function call to see if it is an
11551       // implicit cast from a type matching the type the result
11552       // is being cast to.
11553       CallExpr *CEx = cast<CallExpr>(E);
11554       if (unsigned NumArgs = CEx->getNumArgs()) {
11555         Expr *LastA = CEx->getArg(NumArgs - 1);
11556         Expr *InnerE = LastA->IgnoreParenImpCasts();
11557         if (isa<ImplicitCastExpr>(LastA) &&
11558             InnerE->getType()->isBooleanType()) {
11559           // Warn on this floating-point to bool conversion
11560           DiagnoseImpCast(S, E, T, CC,
11561                           diag::warn_impcast_floating_point_to_bool);
11562         }
11563       }
11564     }
11565     return;
11566   }
11567 
11568   // Valid casts involving fixed point types should be accounted for here.
11569   if (Source->isFixedPointType()) {
11570     if (Target->isUnsaturatedFixedPointType()) {
11571       Expr::EvalResult Result;
11572       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11573                                   S.isConstantEvaluated())) {
11574         APFixedPoint Value = Result.Val.getFixedPoint();
11575         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11576         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11577         if (Value > MaxVal || Value < MinVal) {
11578           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11579                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11580                                     << Value.toString() << T
11581                                     << E->getSourceRange()
11582                                     << clang::SourceRange(CC));
11583           return;
11584         }
11585       }
11586     } else if (Target->isIntegerType()) {
11587       Expr::EvalResult Result;
11588       if (!S.isConstantEvaluated() &&
11589           E->EvaluateAsFixedPoint(Result, S.Context,
11590                                   Expr::SE_AllowSideEffects)) {
11591         APFixedPoint FXResult = Result.Val.getFixedPoint();
11592 
11593         bool Overflowed;
11594         llvm::APSInt IntResult = FXResult.convertToInt(
11595             S.Context.getIntWidth(T),
11596             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11597 
11598         if (Overflowed) {
11599           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11600                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11601                                     << FXResult.toString() << T
11602                                     << E->getSourceRange()
11603                                     << clang::SourceRange(CC));
11604           return;
11605         }
11606       }
11607     }
11608   } else if (Target->isUnsaturatedFixedPointType()) {
11609     if (Source->isIntegerType()) {
11610       Expr::EvalResult Result;
11611       if (!S.isConstantEvaluated() &&
11612           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11613         llvm::APSInt Value = Result.Val.getInt();
11614 
11615         bool Overflowed;
11616         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11617             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11618 
11619         if (Overflowed) {
11620           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11621                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11622                                     << Value.toString(/*Radix=*/10) << T
11623                                     << E->getSourceRange()
11624                                     << clang::SourceRange(CC));
11625           return;
11626         }
11627       }
11628     }
11629   }
11630 
11631   // If we are casting an integer type to a floating point type without
11632   // initialization-list syntax, we might lose accuracy if the floating
11633   // point type has a narrower significand than the integer type.
11634   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11635       TargetBT->isFloatingType() && !IsListInit) {
11636     // Determine the number of precision bits in the source integer type.
11637     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11638     unsigned int SourcePrecision = SourceRange.Width;
11639 
11640     // Determine the number of precision bits in the
11641     // target floating point type.
11642     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11643         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11644 
11645     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11646         SourcePrecision > TargetPrecision) {
11647 
11648       llvm::APSInt SourceInt;
11649       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11650         // If the source integer is a constant, convert it to the target
11651         // floating point type. Issue a warning if the value changes
11652         // during the whole conversion.
11653         llvm::APFloat TargetFloatValue(
11654             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11655         llvm::APFloat::opStatus ConversionStatus =
11656             TargetFloatValue.convertFromAPInt(
11657                 SourceInt, SourceBT->isSignedInteger(),
11658                 llvm::APFloat::rmNearestTiesToEven);
11659 
11660         if (ConversionStatus != llvm::APFloat::opOK) {
11661           std::string PrettySourceValue = SourceInt.toString(10);
11662           SmallString<32> PrettyTargetValue;
11663           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11664 
11665           S.DiagRuntimeBehavior(
11666               E->getExprLoc(), E,
11667               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11668                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11669                   << E->getSourceRange() << clang::SourceRange(CC));
11670         }
11671       } else {
11672         // Otherwise, the implicit conversion may lose precision.
11673         DiagnoseImpCast(S, E, T, CC,
11674                         diag::warn_impcast_integer_float_precision);
11675       }
11676     }
11677   }
11678 
11679   DiagnoseNullConversion(S, E, T, CC);
11680 
11681   S.DiscardMisalignedMemberAddress(Target, E);
11682 
11683   if (Target->isBooleanType())
11684     DiagnoseIntInBoolContext(S, E);
11685 
11686   if (!Source->isIntegerType() || !Target->isIntegerType())
11687     return;
11688 
11689   // TODO: remove this early return once the false positives for constant->bool
11690   // in templates, macros, etc, are reduced or removed.
11691   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11692     return;
11693 
11694   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11695       !E->isKnownToHaveBooleanValue()) {
11696     return adornObjCBoolConversionDiagWithTernaryFixit(
11697         S, E,
11698         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11699             << E->getType());
11700   }
11701 
11702   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11703   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11704 
11705   if (SourceRange.Width > TargetRange.Width) {
11706     // If the source is a constant, use a default-on diagnostic.
11707     // TODO: this should happen for bitfield stores, too.
11708     Expr::EvalResult Result;
11709     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11710                          S.isConstantEvaluated())) {
11711       llvm::APSInt Value(32);
11712       Value = Result.Val.getInt();
11713 
11714       if (S.SourceMgr.isInSystemMacro(CC))
11715         return;
11716 
11717       std::string PrettySourceValue = Value.toString(10);
11718       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11719 
11720       S.DiagRuntimeBehavior(
11721           E->getExprLoc(), E,
11722           S.PDiag(diag::warn_impcast_integer_precision_constant)
11723               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11724               << E->getSourceRange() << clang::SourceRange(CC));
11725       return;
11726     }
11727 
11728     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11729     if (S.SourceMgr.isInSystemMacro(CC))
11730       return;
11731 
11732     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11733       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11734                              /* pruneControlFlow */ true);
11735     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11736   }
11737 
11738   if (TargetRange.Width > SourceRange.Width) {
11739     if (auto *UO = dyn_cast<UnaryOperator>(E))
11740       if (UO->getOpcode() == UO_Minus)
11741         if (Source->isUnsignedIntegerType()) {
11742           if (Target->isUnsignedIntegerType())
11743             return DiagnoseImpCast(S, E, T, CC,
11744                                    diag::warn_impcast_high_order_zero_bits);
11745           if (Target->isSignedIntegerType())
11746             return DiagnoseImpCast(S, E, T, CC,
11747                                    diag::warn_impcast_nonnegative_result);
11748         }
11749   }
11750 
11751   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11752       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11753     // Warn when doing a signed to signed conversion, warn if the positive
11754     // source value is exactly the width of the target type, which will
11755     // cause a negative value to be stored.
11756 
11757     Expr::EvalResult Result;
11758     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11759         !S.SourceMgr.isInSystemMacro(CC)) {
11760       llvm::APSInt Value = Result.Val.getInt();
11761       if (isSameWidthConstantConversion(S, E, T, CC)) {
11762         std::string PrettySourceValue = Value.toString(10);
11763         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11764 
11765         S.DiagRuntimeBehavior(
11766             E->getExprLoc(), E,
11767             S.PDiag(diag::warn_impcast_integer_precision_constant)
11768                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11769                 << E->getSourceRange() << clang::SourceRange(CC));
11770         return;
11771       }
11772     }
11773 
11774     // Fall through for non-constants to give a sign conversion warning.
11775   }
11776 
11777   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11778       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11779        SourceRange.Width == TargetRange.Width)) {
11780     if (S.SourceMgr.isInSystemMacro(CC))
11781       return;
11782 
11783     unsigned DiagID = diag::warn_impcast_integer_sign;
11784 
11785     // Traditionally, gcc has warned about this under -Wsign-compare.
11786     // We also want to warn about it in -Wconversion.
11787     // So if -Wconversion is off, use a completely identical diagnostic
11788     // in the sign-compare group.
11789     // The conditional-checking code will
11790     if (ICContext) {
11791       DiagID = diag::warn_impcast_integer_sign_conditional;
11792       *ICContext = true;
11793     }
11794 
11795     return DiagnoseImpCast(S, E, T, CC, DiagID);
11796   }
11797 
11798   // Diagnose conversions between different enumeration types.
11799   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11800   // type, to give us better diagnostics.
11801   QualType SourceType = E->getType();
11802   if (!S.getLangOpts().CPlusPlus) {
11803     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11804       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11805         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11806         SourceType = S.Context.getTypeDeclType(Enum);
11807         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11808       }
11809   }
11810 
11811   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11812     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11813       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11814           TargetEnum->getDecl()->hasNameForLinkage() &&
11815           SourceEnum != TargetEnum) {
11816         if (S.SourceMgr.isInSystemMacro(CC))
11817           return;
11818 
11819         return DiagnoseImpCast(S, E, SourceType, T, CC,
11820                                diag::warn_impcast_different_enum_types);
11821       }
11822 }
11823 
11824 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11825                                      SourceLocation CC, QualType T);
11826 
11827 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11828                                     SourceLocation CC, bool &ICContext) {
11829   E = E->IgnoreParenImpCasts();
11830 
11831   if (isa<ConditionalOperator>(E))
11832     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11833 
11834   AnalyzeImplicitConversions(S, E, CC);
11835   if (E->getType() != T)
11836     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11837 }
11838 
11839 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11840                                      SourceLocation CC, QualType T) {
11841   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11842 
11843   bool Suspicious = false;
11844   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11845   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11846   CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
11847                                 E->getFalseExpr());
11848 
11849   if (T->isBooleanType())
11850     DiagnoseIntInBoolContext(S, E);
11851 
11852   // If -Wconversion would have warned about either of the candidates
11853   // for a signedness conversion to the context type...
11854   if (!Suspicious) return;
11855 
11856   // ...but it's currently ignored...
11857   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11858     return;
11859 
11860   // ...then check whether it would have warned about either of the
11861   // candidates for a signedness conversion to the condition type.
11862   if (E->getType() == T) return;
11863 
11864   Suspicious = false;
11865   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11866                           E->getType(), CC, &Suspicious);
11867   if (!Suspicious)
11868     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11869                             E->getType(), CC, &Suspicious);
11870 }
11871 
11872 /// Check conversion of given expression to boolean.
11873 /// Input argument E is a logical expression.
11874 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11875   if (S.getLangOpts().Bool)
11876     return;
11877   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11878     return;
11879   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11880 }
11881 
11882 /// AnalyzeImplicitConversions - Find and report any interesting
11883 /// implicit conversions in the given expression.  There are a couple
11884 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11885 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11886                                        bool IsListInit/*= false*/) {
11887   QualType T = OrigE->getType();
11888   Expr *E = OrigE->IgnoreParenImpCasts();
11889 
11890   // Propagate whether we are in a C++ list initialization expression.
11891   // If so, we do not issue warnings for implicit int-float conversion
11892   // precision loss, because C++11 narrowing already handles it.
11893   IsListInit =
11894       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11895 
11896   if (E->isTypeDependent() || E->isValueDependent())
11897     return;
11898 
11899   // For conditional operators, we analyze the arguments as if they
11900   // were being fed directly into the output.
11901   if (isa<ConditionalOperator>(E)) {
11902     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11903     CheckConditionalOperator(S, CO, CC, T);
11904     return;
11905   }
11906 
11907   // Check implicit argument conversions for function calls.
11908   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11909     CheckImplicitArgumentConversions(S, Call, CC);
11910 
11911   // Go ahead and check any implicit conversions we might have skipped.
11912   // The non-canonical typecheck is just an optimization;
11913   // CheckImplicitConversion will filter out dead implicit conversions.
11914   if (E->getType() != T)
11915     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
11916 
11917   // Now continue drilling into this expression.
11918 
11919   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11920     // The bound subexpressions in a PseudoObjectExpr are not reachable
11921     // as transitive children.
11922     // FIXME: Use a more uniform representation for this.
11923     for (auto *SE : POE->semantics())
11924       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11925         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
11926   }
11927 
11928   // Skip past explicit casts.
11929   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11930     E = CE->getSubExpr()->IgnoreParenImpCasts();
11931     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11932       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11933     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
11934   }
11935 
11936   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11937     // Do a somewhat different check with comparison operators.
11938     if (BO->isComparisonOp())
11939       return AnalyzeComparison(S, BO);
11940 
11941     // And with simple assignments.
11942     if (BO->getOpcode() == BO_Assign)
11943       return AnalyzeAssignment(S, BO);
11944     // And with compound assignments.
11945     if (BO->isAssignmentOp())
11946       return AnalyzeCompoundAssignment(S, BO);
11947   }
11948 
11949   // These break the otherwise-useful invariant below.  Fortunately,
11950   // we don't really need to recurse into them, because any internal
11951   // expressions should have been analyzed already when they were
11952   // built into statements.
11953   if (isa<StmtExpr>(E)) return;
11954 
11955   // Don't descend into unevaluated contexts.
11956   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11957 
11958   // Now just recurse over the expression's children.
11959   CC = E->getExprLoc();
11960   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11961   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11962   for (Stmt *SubStmt : E->children()) {
11963     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11964     if (!ChildExpr)
11965       continue;
11966 
11967     if (IsLogicalAndOperator &&
11968         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11969       // Ignore checking string literals that are in logical and operators.
11970       // This is a common pattern for asserts.
11971       continue;
11972     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
11973   }
11974 
11975   if (BO && BO->isLogicalOp()) {
11976     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11977     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11978       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11979 
11980     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11981     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11982       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11983   }
11984 
11985   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11986     if (U->getOpcode() == UO_LNot) {
11987       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11988     } else if (U->getOpcode() != UO_AddrOf) {
11989       if (U->getSubExpr()->getType()->isAtomicType())
11990         S.Diag(U->getSubExpr()->getBeginLoc(),
11991                diag::warn_atomic_implicit_seq_cst);
11992     }
11993   }
11994 }
11995 
11996 /// Diagnose integer type and any valid implicit conversion to it.
11997 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11998   // Taking into account implicit conversions,
11999   // allow any integer.
12000   if (!E->getType()->isIntegerType()) {
12001     S.Diag(E->getBeginLoc(),
12002            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12003     return true;
12004   }
12005   // Potentially emit standard warnings for implicit conversions if enabled
12006   // using -Wconversion.
12007   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12008   return false;
12009 }
12010 
12011 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12012 // Returns true when emitting a warning about taking the address of a reference.
12013 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12014                               const PartialDiagnostic &PD) {
12015   E = E->IgnoreParenImpCasts();
12016 
12017   const FunctionDecl *FD = nullptr;
12018 
12019   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12020     if (!DRE->getDecl()->getType()->isReferenceType())
12021       return false;
12022   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12023     if (!M->getMemberDecl()->getType()->isReferenceType())
12024       return false;
12025   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12026     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12027       return false;
12028     FD = Call->getDirectCallee();
12029   } else {
12030     return false;
12031   }
12032 
12033   SemaRef.Diag(E->getExprLoc(), PD);
12034 
12035   // If possible, point to location of function.
12036   if (FD) {
12037     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12038   }
12039 
12040   return true;
12041 }
12042 
12043 // Returns true if the SourceLocation is expanded from any macro body.
12044 // Returns false if the SourceLocation is invalid, is from not in a macro
12045 // expansion, or is from expanded from a top-level macro argument.
12046 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12047   if (Loc.isInvalid())
12048     return false;
12049 
12050   while (Loc.isMacroID()) {
12051     if (SM.isMacroBodyExpansion(Loc))
12052       return true;
12053     Loc = SM.getImmediateMacroCallerLoc(Loc);
12054   }
12055 
12056   return false;
12057 }
12058 
12059 /// Diagnose pointers that are always non-null.
12060 /// \param E the expression containing the pointer
12061 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12062 /// compared to a null pointer
12063 /// \param IsEqual True when the comparison is equal to a null pointer
12064 /// \param Range Extra SourceRange to highlight in the diagnostic
12065 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12066                                         Expr::NullPointerConstantKind NullKind,
12067                                         bool IsEqual, SourceRange Range) {
12068   if (!E)
12069     return;
12070 
12071   // Don't warn inside macros.
12072   if (E->getExprLoc().isMacroID()) {
12073     const SourceManager &SM = getSourceManager();
12074     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12075         IsInAnyMacroBody(SM, Range.getBegin()))
12076       return;
12077   }
12078   E = E->IgnoreImpCasts();
12079 
12080   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12081 
12082   if (isa<CXXThisExpr>(E)) {
12083     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12084                                 : diag::warn_this_bool_conversion;
12085     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12086     return;
12087   }
12088 
12089   bool IsAddressOf = false;
12090 
12091   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12092     if (UO->getOpcode() != UO_AddrOf)
12093       return;
12094     IsAddressOf = true;
12095     E = UO->getSubExpr();
12096   }
12097 
12098   if (IsAddressOf) {
12099     unsigned DiagID = IsCompare
12100                           ? diag::warn_address_of_reference_null_compare
12101                           : diag::warn_address_of_reference_bool_conversion;
12102     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12103                                          << IsEqual;
12104     if (CheckForReference(*this, E, PD)) {
12105       return;
12106     }
12107   }
12108 
12109   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12110     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12111     std::string Str;
12112     llvm::raw_string_ostream S(Str);
12113     E->printPretty(S, nullptr, getPrintingPolicy());
12114     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12115                                 : diag::warn_cast_nonnull_to_bool;
12116     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12117       << E->getSourceRange() << Range << IsEqual;
12118     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12119   };
12120 
12121   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12122   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12123     if (auto *Callee = Call->getDirectCallee()) {
12124       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12125         ComplainAboutNonnullParamOrCall(A);
12126         return;
12127       }
12128     }
12129   }
12130 
12131   // Expect to find a single Decl.  Skip anything more complicated.
12132   ValueDecl *D = nullptr;
12133   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12134     D = R->getDecl();
12135   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12136     D = M->getMemberDecl();
12137   }
12138 
12139   // Weak Decls can be null.
12140   if (!D || D->isWeak())
12141     return;
12142 
12143   // Check for parameter decl with nonnull attribute
12144   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12145     if (getCurFunction() &&
12146         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12147       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12148         ComplainAboutNonnullParamOrCall(A);
12149         return;
12150       }
12151 
12152       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12153         // Skip function template not specialized yet.
12154         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12155           return;
12156         auto ParamIter = llvm::find(FD->parameters(), PV);
12157         assert(ParamIter != FD->param_end());
12158         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12159 
12160         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12161           if (!NonNull->args_size()) {
12162               ComplainAboutNonnullParamOrCall(NonNull);
12163               return;
12164           }
12165 
12166           for (const ParamIdx &ArgNo : NonNull->args()) {
12167             if (ArgNo.getASTIndex() == ParamNo) {
12168               ComplainAboutNonnullParamOrCall(NonNull);
12169               return;
12170             }
12171           }
12172         }
12173       }
12174     }
12175   }
12176 
12177   QualType T = D->getType();
12178   const bool IsArray = T->isArrayType();
12179   const bool IsFunction = T->isFunctionType();
12180 
12181   // Address of function is used to silence the function warning.
12182   if (IsAddressOf && IsFunction) {
12183     return;
12184   }
12185 
12186   // Found nothing.
12187   if (!IsAddressOf && !IsFunction && !IsArray)
12188     return;
12189 
12190   // Pretty print the expression for the diagnostic.
12191   std::string Str;
12192   llvm::raw_string_ostream S(Str);
12193   E->printPretty(S, nullptr, getPrintingPolicy());
12194 
12195   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12196                               : diag::warn_impcast_pointer_to_bool;
12197   enum {
12198     AddressOf,
12199     FunctionPointer,
12200     ArrayPointer
12201   } DiagType;
12202   if (IsAddressOf)
12203     DiagType = AddressOf;
12204   else if (IsFunction)
12205     DiagType = FunctionPointer;
12206   else if (IsArray)
12207     DiagType = ArrayPointer;
12208   else
12209     llvm_unreachable("Could not determine diagnostic.");
12210   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12211                                 << Range << IsEqual;
12212 
12213   if (!IsFunction)
12214     return;
12215 
12216   // Suggest '&' to silence the function warning.
12217   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12218       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12219 
12220   // Check to see if '()' fixit should be emitted.
12221   QualType ReturnType;
12222   UnresolvedSet<4> NonTemplateOverloads;
12223   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12224   if (ReturnType.isNull())
12225     return;
12226 
12227   if (IsCompare) {
12228     // There are two cases here.  If there is null constant, the only suggest
12229     // for a pointer return type.  If the null is 0, then suggest if the return
12230     // type is a pointer or an integer type.
12231     if (!ReturnType->isPointerType()) {
12232       if (NullKind == Expr::NPCK_ZeroExpression ||
12233           NullKind == Expr::NPCK_ZeroLiteral) {
12234         if (!ReturnType->isIntegerType())
12235           return;
12236       } else {
12237         return;
12238       }
12239     }
12240   } else { // !IsCompare
12241     // For function to bool, only suggest if the function pointer has bool
12242     // return type.
12243     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12244       return;
12245   }
12246   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12247       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12248 }
12249 
12250 /// Diagnoses "dangerous" implicit conversions within the given
12251 /// expression (which is a full expression).  Implements -Wconversion
12252 /// and -Wsign-compare.
12253 ///
12254 /// \param CC the "context" location of the implicit conversion, i.e.
12255 ///   the most location of the syntactic entity requiring the implicit
12256 ///   conversion
12257 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12258   // Don't diagnose in unevaluated contexts.
12259   if (isUnevaluatedContext())
12260     return;
12261 
12262   // Don't diagnose for value- or type-dependent expressions.
12263   if (E->isTypeDependent() || E->isValueDependent())
12264     return;
12265 
12266   // Check for array bounds violations in cases where the check isn't triggered
12267   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12268   // ArraySubscriptExpr is on the RHS of a variable initialization.
12269   CheckArrayAccess(E);
12270 
12271   // This is not the right CC for (e.g.) a variable initialization.
12272   AnalyzeImplicitConversions(*this, E, CC);
12273 }
12274 
12275 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12276 /// Input argument E is a logical expression.
12277 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12278   ::CheckBoolLikeConversion(*this, E, CC);
12279 }
12280 
12281 /// Diagnose when expression is an integer constant expression and its evaluation
12282 /// results in integer overflow
12283 void Sema::CheckForIntOverflow (Expr *E) {
12284   // Use a work list to deal with nested struct initializers.
12285   SmallVector<Expr *, 2> Exprs(1, E);
12286 
12287   do {
12288     Expr *OriginalE = Exprs.pop_back_val();
12289     Expr *E = OriginalE->IgnoreParenCasts();
12290 
12291     if (isa<BinaryOperator>(E)) {
12292       E->EvaluateForOverflow(Context);
12293       continue;
12294     }
12295 
12296     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12297       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12298     else if (isa<ObjCBoxedExpr>(OriginalE))
12299       E->EvaluateForOverflow(Context);
12300     else if (auto Call = dyn_cast<CallExpr>(E))
12301       Exprs.append(Call->arg_begin(), Call->arg_end());
12302     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12303       Exprs.append(Message->arg_begin(), Message->arg_end());
12304   } while (!Exprs.empty());
12305 }
12306 
12307 namespace {
12308 
12309 /// Visitor for expressions which looks for unsequenced operations on the
12310 /// same object.
12311 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
12312   using Base = EvaluatedExprVisitor<SequenceChecker>;
12313 
12314   /// A tree of sequenced regions within an expression. Two regions are
12315   /// unsequenced if one is an ancestor or a descendent of the other. When we
12316   /// finish processing an expression with sequencing, such as a comma
12317   /// expression, we fold its tree nodes into its parent, since they are
12318   /// unsequenced with respect to nodes we will visit later.
12319   class SequenceTree {
12320     struct Value {
12321       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12322       unsigned Parent : 31;
12323       unsigned Merged : 1;
12324     };
12325     SmallVector<Value, 8> Values;
12326 
12327   public:
12328     /// A region within an expression which may be sequenced with respect
12329     /// to some other region.
12330     class Seq {
12331       friend class SequenceTree;
12332 
12333       unsigned Index;
12334 
12335       explicit Seq(unsigned N) : Index(N) {}
12336 
12337     public:
12338       Seq() : Index(0) {}
12339     };
12340 
12341     SequenceTree() { Values.push_back(Value(0)); }
12342     Seq root() const { return Seq(0); }
12343 
12344     /// Create a new sequence of operations, which is an unsequenced
12345     /// subset of \p Parent. This sequence of operations is sequenced with
12346     /// respect to other children of \p Parent.
12347     Seq allocate(Seq Parent) {
12348       Values.push_back(Value(Parent.Index));
12349       return Seq(Values.size() - 1);
12350     }
12351 
12352     /// Merge a sequence of operations into its parent.
12353     void merge(Seq S) {
12354       Values[S.Index].Merged = true;
12355     }
12356 
12357     /// Determine whether two operations are unsequenced. This operation
12358     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12359     /// should have been merged into its parent as appropriate.
12360     bool isUnsequenced(Seq Cur, Seq Old) {
12361       unsigned C = representative(Cur.Index);
12362       unsigned Target = representative(Old.Index);
12363       while (C >= Target) {
12364         if (C == Target)
12365           return true;
12366         C = Values[C].Parent;
12367       }
12368       return false;
12369     }
12370 
12371   private:
12372     /// Pick a representative for a sequence.
12373     unsigned representative(unsigned K) {
12374       if (Values[K].Merged)
12375         // Perform path compression as we go.
12376         return Values[K].Parent = representative(Values[K].Parent);
12377       return K;
12378     }
12379   };
12380 
12381   /// An object for which we can track unsequenced uses.
12382   using Object = NamedDecl *;
12383 
12384   /// Different flavors of object usage which we track. We only track the
12385   /// least-sequenced usage of each kind.
12386   enum UsageKind {
12387     /// A read of an object. Multiple unsequenced reads are OK.
12388     UK_Use,
12389 
12390     /// A modification of an object which is sequenced before the value
12391     /// computation of the expression, such as ++n in C++.
12392     UK_ModAsValue,
12393 
12394     /// A modification of an object which is not sequenced before the value
12395     /// computation of the expression, such as n++.
12396     UK_ModAsSideEffect,
12397 
12398     UK_Count = UK_ModAsSideEffect + 1
12399   };
12400 
12401   struct Usage {
12402     Expr *Use;
12403     SequenceTree::Seq Seq;
12404 
12405     Usage() : Use(nullptr), Seq() {}
12406   };
12407 
12408   struct UsageInfo {
12409     Usage Uses[UK_Count];
12410 
12411     /// Have we issued a diagnostic for this variable already?
12412     bool Diagnosed;
12413 
12414     UsageInfo() : Uses(), Diagnosed(false) {}
12415   };
12416   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12417 
12418   Sema &SemaRef;
12419 
12420   /// Sequenced regions within the expression.
12421   SequenceTree Tree;
12422 
12423   /// Declaration modifications and references which we have seen.
12424   UsageInfoMap UsageMap;
12425 
12426   /// The region we are currently within.
12427   SequenceTree::Seq Region;
12428 
12429   /// Filled in with declarations which were modified as a side-effect
12430   /// (that is, post-increment operations).
12431   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12432 
12433   /// Expressions to check later. We defer checking these to reduce
12434   /// stack usage.
12435   SmallVectorImpl<Expr *> &WorkList;
12436 
12437   /// RAII object wrapping the visitation of a sequenced subexpression of an
12438   /// expression. At the end of this process, the side-effects of the evaluation
12439   /// become sequenced with respect to the value computation of the result, so
12440   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12441   /// UK_ModAsValue.
12442   struct SequencedSubexpression {
12443     SequencedSubexpression(SequenceChecker &Self)
12444       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12445       Self.ModAsSideEffect = &ModAsSideEffect;
12446     }
12447 
12448     ~SequencedSubexpression() {
12449       for (auto &M : llvm::reverse(ModAsSideEffect)) {
12450         UsageInfo &U = Self.UsageMap[M.first];
12451         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12452         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12453         SideEffectUsage = M.second;
12454       }
12455       Self.ModAsSideEffect = OldModAsSideEffect;
12456     }
12457 
12458     SequenceChecker &Self;
12459     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12460     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12461   };
12462 
12463   /// RAII object wrapping the visitation of a subexpression which we might
12464   /// choose to evaluate as a constant. If any subexpression is evaluated and
12465   /// found to be non-constant, this allows us to suppress the evaluation of
12466   /// the outer expression.
12467   class EvaluationTracker {
12468   public:
12469     EvaluationTracker(SequenceChecker &Self)
12470         : Self(Self), Prev(Self.EvalTracker) {
12471       Self.EvalTracker = this;
12472     }
12473 
12474     ~EvaluationTracker() {
12475       Self.EvalTracker = Prev;
12476       if (Prev)
12477         Prev->EvalOK &= EvalOK;
12478     }
12479 
12480     bool evaluate(const Expr *E, bool &Result) {
12481       if (!EvalOK || E->isValueDependent())
12482         return false;
12483       EvalOK = E->EvaluateAsBooleanCondition(
12484           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12485       return EvalOK;
12486     }
12487 
12488   private:
12489     SequenceChecker &Self;
12490     EvaluationTracker *Prev;
12491     bool EvalOK = true;
12492   } *EvalTracker = nullptr;
12493 
12494   /// Find the object which is produced by the specified expression,
12495   /// if any.
12496   Object getObject(Expr *E, bool Mod) const {
12497     E = E->IgnoreParenCasts();
12498     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12499       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12500         return getObject(UO->getSubExpr(), Mod);
12501     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12502       if (BO->getOpcode() == BO_Comma)
12503         return getObject(BO->getRHS(), Mod);
12504       if (Mod && BO->isAssignmentOp())
12505         return getObject(BO->getLHS(), Mod);
12506     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12507       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12508       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12509         return ME->getMemberDecl();
12510     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12511       // FIXME: If this is a reference, map through to its value.
12512       return DRE->getDecl();
12513     return nullptr;
12514   }
12515 
12516   /// Note that an object was modified or used by an expression.
12517   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12518     Usage &U = UI.Uses[UK];
12519     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12520       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12521         ModAsSideEffect->push_back(std::make_pair(O, U));
12522       U.Use = Ref;
12523       U.Seq = Region;
12524     }
12525   }
12526 
12527   /// Check whether a modification or use conflicts with a prior usage.
12528   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12529                   bool IsModMod) {
12530     if (UI.Diagnosed)
12531       return;
12532 
12533     const Usage &U = UI.Uses[OtherKind];
12534     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12535       return;
12536 
12537     Expr *Mod = U.Use;
12538     Expr *ModOrUse = Ref;
12539     if (OtherKind == UK_Use)
12540       std::swap(Mod, ModOrUse);
12541 
12542     SemaRef.DiagRuntimeBehavior(
12543         Mod->getExprLoc(), {Mod, ModOrUse},
12544         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12545                                : diag::warn_unsequenced_mod_use)
12546             << O << SourceRange(ModOrUse->getExprLoc()));
12547     UI.Diagnosed = true;
12548   }
12549 
12550   void notePreUse(Object O, Expr *Use) {
12551     UsageInfo &U = UsageMap[O];
12552     // Uses conflict with other modifications.
12553     checkUsage(O, U, Use, UK_ModAsValue, false);
12554   }
12555 
12556   void notePostUse(Object O, Expr *Use) {
12557     UsageInfo &U = UsageMap[O];
12558     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12559     addUsage(U, O, Use, UK_Use);
12560   }
12561 
12562   void notePreMod(Object O, Expr *Mod) {
12563     UsageInfo &U = UsageMap[O];
12564     // Modifications conflict with other modifications and with uses.
12565     checkUsage(O, U, Mod, UK_ModAsValue, true);
12566     checkUsage(O, U, Mod, UK_Use, false);
12567   }
12568 
12569   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12570     UsageInfo &U = UsageMap[O];
12571     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12572     addUsage(U, O, Use, UK);
12573   }
12574 
12575 public:
12576   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12577       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12578     Visit(E);
12579   }
12580 
12581   void VisitStmt(Stmt *S) {
12582     // Skip all statements which aren't expressions for now.
12583   }
12584 
12585   void VisitExpr(Expr *E) {
12586     // By default, just recurse to evaluated subexpressions.
12587     Base::VisitStmt(E);
12588   }
12589 
12590   void VisitCastExpr(CastExpr *E) {
12591     Object O = Object();
12592     if (E->getCastKind() == CK_LValueToRValue)
12593       O = getObject(E->getSubExpr(), false);
12594 
12595     if (O)
12596       notePreUse(O, E);
12597     VisitExpr(E);
12598     if (O)
12599       notePostUse(O, E);
12600   }
12601 
12602   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12603     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12604     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12605     SequenceTree::Seq OldRegion = Region;
12606 
12607     {
12608       SequencedSubexpression SeqBefore(*this);
12609       Region = BeforeRegion;
12610       Visit(SequencedBefore);
12611     }
12612 
12613     Region = AfterRegion;
12614     Visit(SequencedAfter);
12615 
12616     Region = OldRegion;
12617 
12618     Tree.merge(BeforeRegion);
12619     Tree.merge(AfterRegion);
12620   }
12621 
12622   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12623     // C++17 [expr.sub]p1:
12624     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12625     //   expression E1 is sequenced before the expression E2.
12626     if (SemaRef.getLangOpts().CPlusPlus17)
12627       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12628     else
12629       Base::VisitStmt(ASE);
12630   }
12631 
12632   void VisitBinComma(BinaryOperator *BO) {
12633     // C++11 [expr.comma]p1:
12634     //   Every value computation and side effect associated with the left
12635     //   expression is sequenced before every value computation and side
12636     //   effect associated with the right expression.
12637     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12638   }
12639 
12640   void VisitBinAssign(BinaryOperator *BO) {
12641     // The modification is sequenced after the value computation of the LHS
12642     // and RHS, so check it before inspecting the operands and update the
12643     // map afterwards.
12644     Object O = getObject(BO->getLHS(), true);
12645     if (!O)
12646       return VisitExpr(BO);
12647 
12648     notePreMod(O, BO);
12649 
12650     // C++11 [expr.ass]p7:
12651     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12652     //   only once.
12653     //
12654     // Therefore, for a compound assignment operator, O is considered used
12655     // everywhere except within the evaluation of E1 itself.
12656     if (isa<CompoundAssignOperator>(BO))
12657       notePreUse(O, BO);
12658 
12659     Visit(BO->getLHS());
12660 
12661     if (isa<CompoundAssignOperator>(BO))
12662       notePostUse(O, BO);
12663 
12664     Visit(BO->getRHS());
12665 
12666     // C++11 [expr.ass]p1:
12667     //   the assignment is sequenced [...] before the value computation of the
12668     //   assignment expression.
12669     // C11 6.5.16/3 has no such rule.
12670     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12671                                                        : UK_ModAsSideEffect);
12672   }
12673 
12674   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12675     VisitBinAssign(CAO);
12676   }
12677 
12678   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12679   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12680   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12681     Object O = getObject(UO->getSubExpr(), true);
12682     if (!O)
12683       return VisitExpr(UO);
12684 
12685     notePreMod(O, UO);
12686     Visit(UO->getSubExpr());
12687     // C++11 [expr.pre.incr]p1:
12688     //   the expression ++x is equivalent to x+=1
12689     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12690                                                        : UK_ModAsSideEffect);
12691   }
12692 
12693   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12694   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12695   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12696     Object O = getObject(UO->getSubExpr(), true);
12697     if (!O)
12698       return VisitExpr(UO);
12699 
12700     notePreMod(O, UO);
12701     Visit(UO->getSubExpr());
12702     notePostMod(O, UO, UK_ModAsSideEffect);
12703   }
12704 
12705   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12706   void VisitBinLOr(BinaryOperator *BO) {
12707     // The side-effects of the LHS of an '&&' are sequenced before the
12708     // value computation of the RHS, and hence before the value computation
12709     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12710     // as if they were unconditionally sequenced.
12711     EvaluationTracker Eval(*this);
12712     {
12713       SequencedSubexpression Sequenced(*this);
12714       Visit(BO->getLHS());
12715     }
12716 
12717     bool Result;
12718     if (Eval.evaluate(BO->getLHS(), Result)) {
12719       if (!Result)
12720         Visit(BO->getRHS());
12721     } else {
12722       // Check for unsequenced operations in the RHS, treating it as an
12723       // entirely separate evaluation.
12724       //
12725       // FIXME: If there are operations in the RHS which are unsequenced
12726       // with respect to operations outside the RHS, and those operations
12727       // are unconditionally evaluated, diagnose them.
12728       WorkList.push_back(BO->getRHS());
12729     }
12730   }
12731   void VisitBinLAnd(BinaryOperator *BO) {
12732     EvaluationTracker Eval(*this);
12733     {
12734       SequencedSubexpression Sequenced(*this);
12735       Visit(BO->getLHS());
12736     }
12737 
12738     bool Result;
12739     if (Eval.evaluate(BO->getLHS(), Result)) {
12740       if (Result)
12741         Visit(BO->getRHS());
12742     } else {
12743       WorkList.push_back(BO->getRHS());
12744     }
12745   }
12746 
12747   // Only visit the condition, unless we can be sure which subexpression will
12748   // be chosen.
12749   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12750     EvaluationTracker Eval(*this);
12751     {
12752       SequencedSubexpression Sequenced(*this);
12753       Visit(CO->getCond());
12754     }
12755 
12756     bool Result;
12757     if (Eval.evaluate(CO->getCond(), Result))
12758       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12759     else {
12760       WorkList.push_back(CO->getTrueExpr());
12761       WorkList.push_back(CO->getFalseExpr());
12762     }
12763   }
12764 
12765   void VisitCallExpr(CallExpr *CE) {
12766     // C++11 [intro.execution]p15:
12767     //   When calling a function [...], every value computation and side effect
12768     //   associated with any argument expression, or with the postfix expression
12769     //   designating the called function, is sequenced before execution of every
12770     //   expression or statement in the body of the function [and thus before
12771     //   the value computation of its result].
12772     SequencedSubexpression Sequenced(*this);
12773     Base::VisitCallExpr(CE);
12774 
12775     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12776   }
12777 
12778   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12779     // This is a call, so all subexpressions are sequenced before the result.
12780     SequencedSubexpression Sequenced(*this);
12781 
12782     if (!CCE->isListInitialization())
12783       return VisitExpr(CCE);
12784 
12785     // In C++11, list initializations are sequenced.
12786     SmallVector<SequenceTree::Seq, 32> Elts;
12787     SequenceTree::Seq Parent = Region;
12788     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12789                                         E = CCE->arg_end();
12790          I != E; ++I) {
12791       Region = Tree.allocate(Parent);
12792       Elts.push_back(Region);
12793       Visit(*I);
12794     }
12795 
12796     // Forget that the initializers are sequenced.
12797     Region = Parent;
12798     for (unsigned I = 0; I < Elts.size(); ++I)
12799       Tree.merge(Elts[I]);
12800   }
12801 
12802   void VisitInitListExpr(InitListExpr *ILE) {
12803     if (!SemaRef.getLangOpts().CPlusPlus11)
12804       return VisitExpr(ILE);
12805 
12806     // In C++11, list initializations are sequenced.
12807     SmallVector<SequenceTree::Seq, 32> Elts;
12808     SequenceTree::Seq Parent = Region;
12809     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12810       Expr *E = ILE->getInit(I);
12811       if (!E) continue;
12812       Region = Tree.allocate(Parent);
12813       Elts.push_back(Region);
12814       Visit(E);
12815     }
12816 
12817     // Forget that the initializers are sequenced.
12818     Region = Parent;
12819     for (unsigned I = 0; I < Elts.size(); ++I)
12820       Tree.merge(Elts[I]);
12821   }
12822 };
12823 
12824 } // namespace
12825 
12826 void Sema::CheckUnsequencedOperations(Expr *E) {
12827   SmallVector<Expr *, 8> WorkList;
12828   WorkList.push_back(E);
12829   while (!WorkList.empty()) {
12830     Expr *Item = WorkList.pop_back_val();
12831     SequenceChecker(*this, Item, WorkList);
12832   }
12833 }
12834 
12835 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12836                               bool IsConstexpr) {
12837   llvm::SaveAndRestore<bool> ConstantContext(
12838       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12839   CheckImplicitConversions(E, CheckLoc);
12840   if (!E->isInstantiationDependent())
12841     CheckUnsequencedOperations(E);
12842   if (!IsConstexpr && !E->isValueDependent())
12843     CheckForIntOverflow(E);
12844   DiagnoseMisalignedMembers();
12845 }
12846 
12847 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12848                                        FieldDecl *BitField,
12849                                        Expr *Init) {
12850   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12851 }
12852 
12853 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12854                                          SourceLocation Loc) {
12855   if (!PType->isVariablyModifiedType())
12856     return;
12857   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12858     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12859     return;
12860   }
12861   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12862     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12863     return;
12864   }
12865   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12866     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12867     return;
12868   }
12869 
12870   const ArrayType *AT = S.Context.getAsArrayType(PType);
12871   if (!AT)
12872     return;
12873 
12874   if (AT->getSizeModifier() != ArrayType::Star) {
12875     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12876     return;
12877   }
12878 
12879   S.Diag(Loc, diag::err_array_star_in_function_definition);
12880 }
12881 
12882 /// CheckParmsForFunctionDef - Check that the parameters of the given
12883 /// function are appropriate for the definition of a function. This
12884 /// takes care of any checks that cannot be performed on the
12885 /// declaration itself, e.g., that the types of each of the function
12886 /// parameters are complete.
12887 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12888                                     bool CheckParameterNames) {
12889   bool HasInvalidParm = false;
12890   for (ParmVarDecl *Param : Parameters) {
12891     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12892     // function declarator that is part of a function definition of
12893     // that function shall not have incomplete type.
12894     //
12895     // This is also C++ [dcl.fct]p6.
12896     if (!Param->isInvalidDecl() &&
12897         RequireCompleteType(Param->getLocation(), Param->getType(),
12898                             diag::err_typecheck_decl_incomplete_type)) {
12899       Param->setInvalidDecl();
12900       HasInvalidParm = true;
12901     }
12902 
12903     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12904     // declaration of each parameter shall include an identifier.
12905     if (CheckParameterNames &&
12906         Param->getIdentifier() == nullptr &&
12907         !Param->isImplicit() &&
12908         !getLangOpts().CPlusPlus)
12909       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12910 
12911     // C99 6.7.5.3p12:
12912     //   If the function declarator is not part of a definition of that
12913     //   function, parameters may have incomplete type and may use the [*]
12914     //   notation in their sequences of declarator specifiers to specify
12915     //   variable length array types.
12916     QualType PType = Param->getOriginalType();
12917     // FIXME: This diagnostic should point the '[*]' if source-location
12918     // information is added for it.
12919     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12920 
12921     // If the parameter is a c++ class type and it has to be destructed in the
12922     // callee function, declare the destructor so that it can be called by the
12923     // callee function. Do not perform any direct access check on the dtor here.
12924     if (!Param->isInvalidDecl()) {
12925       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12926         if (!ClassDecl->isInvalidDecl() &&
12927             !ClassDecl->hasIrrelevantDestructor() &&
12928             !ClassDecl->isDependentContext() &&
12929             ClassDecl->isParamDestroyedInCallee()) {
12930           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12931           MarkFunctionReferenced(Param->getLocation(), Destructor);
12932           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12933         }
12934       }
12935     }
12936 
12937     // Parameters with the pass_object_size attribute only need to be marked
12938     // constant at function definitions. Because we lack information about
12939     // whether we're on a declaration or definition when we're instantiating the
12940     // attribute, we need to check for constness here.
12941     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12942       if (!Param->getType().isConstQualified())
12943         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12944             << Attr->getSpelling() << 1;
12945 
12946     // Check for parameter names shadowing fields from the class.
12947     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12948       // The owning context for the parameter should be the function, but we
12949       // want to see if this function's declaration context is a record.
12950       DeclContext *DC = Param->getDeclContext();
12951       if (DC && DC->isFunctionOrMethod()) {
12952         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12953           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12954                                      RD, /*DeclIsField*/ false);
12955       }
12956     }
12957   }
12958 
12959   return HasInvalidParm;
12960 }
12961 
12962 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12963 /// or MemberExpr.
12964 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12965                               ASTContext &Context) {
12966   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12967     return Context.getDeclAlign(DRE->getDecl());
12968 
12969   if (const auto *ME = dyn_cast<MemberExpr>(E))
12970     return Context.getDeclAlign(ME->getMemberDecl());
12971 
12972   return TypeAlign;
12973 }
12974 
12975 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12976 /// pointer cast increases the alignment requirements.
12977 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12978   // This is actually a lot of work to potentially be doing on every
12979   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12980   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12981     return;
12982 
12983   // Ignore dependent types.
12984   if (T->isDependentType() || Op->getType()->isDependentType())
12985     return;
12986 
12987   // Require that the destination be a pointer type.
12988   const PointerType *DestPtr = T->getAs<PointerType>();
12989   if (!DestPtr) return;
12990 
12991   // If the destination has alignment 1, we're done.
12992   QualType DestPointee = DestPtr->getPointeeType();
12993   if (DestPointee->isIncompleteType()) return;
12994   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12995   if (DestAlign.isOne()) return;
12996 
12997   // Require that the source be a pointer type.
12998   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12999   if (!SrcPtr) return;
13000   QualType SrcPointee = SrcPtr->getPointeeType();
13001 
13002   // Whitelist casts from cv void*.  We already implicitly
13003   // whitelisted casts to cv void*, since they have alignment 1.
13004   // Also whitelist casts involving incomplete types, which implicitly
13005   // includes 'void'.
13006   if (SrcPointee->isIncompleteType()) return;
13007 
13008   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13009 
13010   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13011     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13012       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13013   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13014     if (UO->getOpcode() == UO_AddrOf)
13015       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13016   }
13017 
13018   if (SrcAlign >= DestAlign) return;
13019 
13020   Diag(TRange.getBegin(), diag::warn_cast_align)
13021     << Op->getType() << T
13022     << static_cast<unsigned>(SrcAlign.getQuantity())
13023     << static_cast<unsigned>(DestAlign.getQuantity())
13024     << TRange << Op->getSourceRange();
13025 }
13026 
13027 /// Check whether this array fits the idiom of a size-one tail padded
13028 /// array member of a struct.
13029 ///
13030 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13031 /// commonly used to emulate flexible arrays in C89 code.
13032 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13033                                     const NamedDecl *ND) {
13034   if (Size != 1 || !ND) return false;
13035 
13036   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13037   if (!FD) return false;
13038 
13039   // Don't consider sizes resulting from macro expansions or template argument
13040   // substitution to form C89 tail-padded arrays.
13041 
13042   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13043   while (TInfo) {
13044     TypeLoc TL = TInfo->getTypeLoc();
13045     // Look through typedefs.
13046     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13047       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13048       TInfo = TDL->getTypeSourceInfo();
13049       continue;
13050     }
13051     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13052       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13053       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13054         return false;
13055     }
13056     break;
13057   }
13058 
13059   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13060   if (!RD) return false;
13061   if (RD->isUnion()) return false;
13062   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13063     if (!CRD->isStandardLayout()) return false;
13064   }
13065 
13066   // See if this is the last field decl in the record.
13067   const Decl *D = FD;
13068   while ((D = D->getNextDeclInContext()))
13069     if (isa<FieldDecl>(D))
13070       return false;
13071   return true;
13072 }
13073 
13074 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13075                             const ArraySubscriptExpr *ASE,
13076                             bool AllowOnePastEnd, bool IndexNegated) {
13077   // Already diagnosed by the constant evaluator.
13078   if (isConstantEvaluated())
13079     return;
13080 
13081   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13082   if (IndexExpr->isValueDependent())
13083     return;
13084 
13085   const Type *EffectiveType =
13086       BaseExpr->getType()->getPointeeOrArrayElementType();
13087   BaseExpr = BaseExpr->IgnoreParenCasts();
13088   const ConstantArrayType *ArrayTy =
13089       Context.getAsConstantArrayType(BaseExpr->getType());
13090 
13091   if (!ArrayTy)
13092     return;
13093 
13094   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13095   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13096     return;
13097 
13098   Expr::EvalResult Result;
13099   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13100     return;
13101 
13102   llvm::APSInt index = Result.Val.getInt();
13103   if (IndexNegated)
13104     index = -index;
13105 
13106   const NamedDecl *ND = nullptr;
13107   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13108     ND = DRE->getDecl();
13109   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13110     ND = ME->getMemberDecl();
13111 
13112   if (index.isUnsigned() || !index.isNegative()) {
13113     // It is possible that the type of the base expression after
13114     // IgnoreParenCasts is incomplete, even though the type of the base
13115     // expression before IgnoreParenCasts is complete (see PR39746 for an
13116     // example). In this case we have no information about whether the array
13117     // access exceeds the array bounds. However we can still diagnose an array
13118     // access which precedes the array bounds.
13119     if (BaseType->isIncompleteType())
13120       return;
13121 
13122     llvm::APInt size = ArrayTy->getSize();
13123     if (!size.isStrictlyPositive())
13124       return;
13125 
13126     if (BaseType != EffectiveType) {
13127       // Make sure we're comparing apples to apples when comparing index to size
13128       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13129       uint64_t array_typesize = Context.getTypeSize(BaseType);
13130       // Handle ptrarith_typesize being zero, such as when casting to void*
13131       if (!ptrarith_typesize) ptrarith_typesize = 1;
13132       if (ptrarith_typesize != array_typesize) {
13133         // There's a cast to a different size type involved
13134         uint64_t ratio = array_typesize / ptrarith_typesize;
13135         // TODO: Be smarter about handling cases where array_typesize is not a
13136         // multiple of ptrarith_typesize
13137         if (ptrarith_typesize * ratio == array_typesize)
13138           size *= llvm::APInt(size.getBitWidth(), ratio);
13139       }
13140     }
13141 
13142     if (size.getBitWidth() > index.getBitWidth())
13143       index = index.zext(size.getBitWidth());
13144     else if (size.getBitWidth() < index.getBitWidth())
13145       size = size.zext(index.getBitWidth());
13146 
13147     // For array subscripting the index must be less than size, but for pointer
13148     // arithmetic also allow the index (offset) to be equal to size since
13149     // computing the next address after the end of the array is legal and
13150     // commonly done e.g. in C++ iterators and range-based for loops.
13151     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13152       return;
13153 
13154     // Also don't warn for arrays of size 1 which are members of some
13155     // structure. These are often used to approximate flexible arrays in C89
13156     // code.
13157     if (IsTailPaddedMemberArray(*this, size, ND))
13158       return;
13159 
13160     // Suppress the warning if the subscript expression (as identified by the
13161     // ']' location) and the index expression are both from macro expansions
13162     // within a system header.
13163     if (ASE) {
13164       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13165           ASE->getRBracketLoc());
13166       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13167         SourceLocation IndexLoc =
13168             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13169         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13170           return;
13171       }
13172     }
13173 
13174     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13175     if (ASE)
13176       DiagID = diag::warn_array_index_exceeds_bounds;
13177 
13178     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13179                         PDiag(DiagID) << index.toString(10, true)
13180                                       << size.toString(10, true)
13181                                       << (unsigned)size.getLimitedValue(~0U)
13182                                       << IndexExpr->getSourceRange());
13183   } else {
13184     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13185     if (!ASE) {
13186       DiagID = diag::warn_ptr_arith_precedes_bounds;
13187       if (index.isNegative()) index = -index;
13188     }
13189 
13190     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13191                         PDiag(DiagID) << index.toString(10, true)
13192                                       << IndexExpr->getSourceRange());
13193   }
13194 
13195   if (!ND) {
13196     // Try harder to find a NamedDecl to point at in the note.
13197     while (const ArraySubscriptExpr *ASE =
13198            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13199       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13200     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13201       ND = DRE->getDecl();
13202     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13203       ND = ME->getMemberDecl();
13204   }
13205 
13206   if (ND)
13207     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13208                         PDiag(diag::note_array_declared_here)
13209                             << ND->getDeclName());
13210 }
13211 
13212 void Sema::CheckArrayAccess(const Expr *expr) {
13213   int AllowOnePastEnd = 0;
13214   while (expr) {
13215     expr = expr->IgnoreParenImpCasts();
13216     switch (expr->getStmtClass()) {
13217       case Stmt::ArraySubscriptExprClass: {
13218         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13219         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13220                          AllowOnePastEnd > 0);
13221         expr = ASE->getBase();
13222         break;
13223       }
13224       case Stmt::MemberExprClass: {
13225         expr = cast<MemberExpr>(expr)->getBase();
13226         break;
13227       }
13228       case Stmt::OMPArraySectionExprClass: {
13229         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13230         if (ASE->getLowerBound())
13231           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13232                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13233         return;
13234       }
13235       case Stmt::UnaryOperatorClass: {
13236         // Only unwrap the * and & unary operators
13237         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13238         expr = UO->getSubExpr();
13239         switch (UO->getOpcode()) {
13240           case UO_AddrOf:
13241             AllowOnePastEnd++;
13242             break;
13243           case UO_Deref:
13244             AllowOnePastEnd--;
13245             break;
13246           default:
13247             return;
13248         }
13249         break;
13250       }
13251       case Stmt::ConditionalOperatorClass: {
13252         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13253         if (const Expr *lhs = cond->getLHS())
13254           CheckArrayAccess(lhs);
13255         if (const Expr *rhs = cond->getRHS())
13256           CheckArrayAccess(rhs);
13257         return;
13258       }
13259       case Stmt::CXXOperatorCallExprClass: {
13260         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13261         for (const auto *Arg : OCE->arguments())
13262           CheckArrayAccess(Arg);
13263         return;
13264       }
13265       default:
13266         return;
13267     }
13268   }
13269 }
13270 
13271 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13272 
13273 namespace {
13274 
13275 struct RetainCycleOwner {
13276   VarDecl *Variable = nullptr;
13277   SourceRange Range;
13278   SourceLocation Loc;
13279   bool Indirect = false;
13280 
13281   RetainCycleOwner() = default;
13282 
13283   void setLocsFrom(Expr *e) {
13284     Loc = e->getExprLoc();
13285     Range = e->getSourceRange();
13286   }
13287 };
13288 
13289 } // namespace
13290 
13291 /// Consider whether capturing the given variable can possibly lead to
13292 /// a retain cycle.
13293 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13294   // In ARC, it's captured strongly iff the variable has __strong
13295   // lifetime.  In MRR, it's captured strongly if the variable is
13296   // __block and has an appropriate type.
13297   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13298     return false;
13299 
13300   owner.Variable = var;
13301   if (ref)
13302     owner.setLocsFrom(ref);
13303   return true;
13304 }
13305 
13306 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13307   while (true) {
13308     e = e->IgnoreParens();
13309     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13310       switch (cast->getCastKind()) {
13311       case CK_BitCast:
13312       case CK_LValueBitCast:
13313       case CK_LValueToRValue:
13314       case CK_ARCReclaimReturnedObject:
13315         e = cast->getSubExpr();
13316         continue;
13317 
13318       default:
13319         return false;
13320       }
13321     }
13322 
13323     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13324       ObjCIvarDecl *ivar = ref->getDecl();
13325       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13326         return false;
13327 
13328       // Try to find a retain cycle in the base.
13329       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13330         return false;
13331 
13332       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13333       owner.Indirect = true;
13334       return true;
13335     }
13336 
13337     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13338       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13339       if (!var) return false;
13340       return considerVariable(var, ref, owner);
13341     }
13342 
13343     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13344       if (member->isArrow()) return false;
13345 
13346       // Don't count this as an indirect ownership.
13347       e = member->getBase();
13348       continue;
13349     }
13350 
13351     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13352       // Only pay attention to pseudo-objects on property references.
13353       ObjCPropertyRefExpr *pre
13354         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13355                                               ->IgnoreParens());
13356       if (!pre) return false;
13357       if (pre->isImplicitProperty()) return false;
13358       ObjCPropertyDecl *property = pre->getExplicitProperty();
13359       if (!property->isRetaining() &&
13360           !(property->getPropertyIvarDecl() &&
13361             property->getPropertyIvarDecl()->getType()
13362               .getObjCLifetime() == Qualifiers::OCL_Strong))
13363           return false;
13364 
13365       owner.Indirect = true;
13366       if (pre->isSuperReceiver()) {
13367         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13368         if (!owner.Variable)
13369           return false;
13370         owner.Loc = pre->getLocation();
13371         owner.Range = pre->getSourceRange();
13372         return true;
13373       }
13374       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13375                               ->getSourceExpr());
13376       continue;
13377     }
13378 
13379     // Array ivars?
13380 
13381     return false;
13382   }
13383 }
13384 
13385 namespace {
13386 
13387   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13388     ASTContext &Context;
13389     VarDecl *Variable;
13390     Expr *Capturer = nullptr;
13391     bool VarWillBeReased = false;
13392 
13393     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13394         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13395           Context(Context), Variable(variable) {}
13396 
13397     void VisitDeclRefExpr(DeclRefExpr *ref) {
13398       if (ref->getDecl() == Variable && !Capturer)
13399         Capturer = ref;
13400     }
13401 
13402     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13403       if (Capturer) return;
13404       Visit(ref->getBase());
13405       if (Capturer && ref->isFreeIvar())
13406         Capturer = ref;
13407     }
13408 
13409     void VisitBlockExpr(BlockExpr *block) {
13410       // Look inside nested blocks
13411       if (block->getBlockDecl()->capturesVariable(Variable))
13412         Visit(block->getBlockDecl()->getBody());
13413     }
13414 
13415     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13416       if (Capturer) return;
13417       if (OVE->getSourceExpr())
13418         Visit(OVE->getSourceExpr());
13419     }
13420 
13421     void VisitBinaryOperator(BinaryOperator *BinOp) {
13422       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13423         return;
13424       Expr *LHS = BinOp->getLHS();
13425       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13426         if (DRE->getDecl() != Variable)
13427           return;
13428         if (Expr *RHS = BinOp->getRHS()) {
13429           RHS = RHS->IgnoreParenCasts();
13430           llvm::APSInt Value;
13431           VarWillBeReased =
13432             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13433         }
13434       }
13435     }
13436   };
13437 
13438 } // namespace
13439 
13440 /// Check whether the given argument is a block which captures a
13441 /// variable.
13442 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13443   assert(owner.Variable && owner.Loc.isValid());
13444 
13445   e = e->IgnoreParenCasts();
13446 
13447   // Look through [^{...} copy] and Block_copy(^{...}).
13448   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13449     Selector Cmd = ME->getSelector();
13450     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13451       e = ME->getInstanceReceiver();
13452       if (!e)
13453         return nullptr;
13454       e = e->IgnoreParenCasts();
13455     }
13456   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13457     if (CE->getNumArgs() == 1) {
13458       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13459       if (Fn) {
13460         const IdentifierInfo *FnI = Fn->getIdentifier();
13461         if (FnI && FnI->isStr("_Block_copy")) {
13462           e = CE->getArg(0)->IgnoreParenCasts();
13463         }
13464       }
13465     }
13466   }
13467 
13468   BlockExpr *block = dyn_cast<BlockExpr>(e);
13469   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13470     return nullptr;
13471 
13472   FindCaptureVisitor visitor(S.Context, owner.Variable);
13473   visitor.Visit(block->getBlockDecl()->getBody());
13474   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13475 }
13476 
13477 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13478                                 RetainCycleOwner &owner) {
13479   assert(capturer);
13480   assert(owner.Variable && owner.Loc.isValid());
13481 
13482   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13483     << owner.Variable << capturer->getSourceRange();
13484   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13485     << owner.Indirect << owner.Range;
13486 }
13487 
13488 /// Check for a keyword selector that starts with the word 'add' or
13489 /// 'set'.
13490 static bool isSetterLikeSelector(Selector sel) {
13491   if (sel.isUnarySelector()) return false;
13492 
13493   StringRef str = sel.getNameForSlot(0);
13494   while (!str.empty() && str.front() == '_') str = str.substr(1);
13495   if (str.startswith("set"))
13496     str = str.substr(3);
13497   else if (str.startswith("add")) {
13498     // Specially whitelist 'addOperationWithBlock:'.
13499     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13500       return false;
13501     str = str.substr(3);
13502   }
13503   else
13504     return false;
13505 
13506   if (str.empty()) return true;
13507   return !isLowercase(str.front());
13508 }
13509 
13510 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13511                                                     ObjCMessageExpr *Message) {
13512   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13513                                                 Message->getReceiverInterface(),
13514                                                 NSAPI::ClassId_NSMutableArray);
13515   if (!IsMutableArray) {
13516     return None;
13517   }
13518 
13519   Selector Sel = Message->getSelector();
13520 
13521   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13522     S.NSAPIObj->getNSArrayMethodKind(Sel);
13523   if (!MKOpt) {
13524     return None;
13525   }
13526 
13527   NSAPI::NSArrayMethodKind MK = *MKOpt;
13528 
13529   switch (MK) {
13530     case NSAPI::NSMutableArr_addObject:
13531     case NSAPI::NSMutableArr_insertObjectAtIndex:
13532     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13533       return 0;
13534     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13535       return 1;
13536 
13537     default:
13538       return None;
13539   }
13540 
13541   return None;
13542 }
13543 
13544 static
13545 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13546                                                   ObjCMessageExpr *Message) {
13547   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13548                                             Message->getReceiverInterface(),
13549                                             NSAPI::ClassId_NSMutableDictionary);
13550   if (!IsMutableDictionary) {
13551     return None;
13552   }
13553 
13554   Selector Sel = Message->getSelector();
13555 
13556   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13557     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13558   if (!MKOpt) {
13559     return None;
13560   }
13561 
13562   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13563 
13564   switch (MK) {
13565     case NSAPI::NSMutableDict_setObjectForKey:
13566     case NSAPI::NSMutableDict_setValueForKey:
13567     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13568       return 0;
13569 
13570     default:
13571       return None;
13572   }
13573 
13574   return None;
13575 }
13576 
13577 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13578   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13579                                                 Message->getReceiverInterface(),
13580                                                 NSAPI::ClassId_NSMutableSet);
13581 
13582   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13583                                             Message->getReceiverInterface(),
13584                                             NSAPI::ClassId_NSMutableOrderedSet);
13585   if (!IsMutableSet && !IsMutableOrderedSet) {
13586     return None;
13587   }
13588 
13589   Selector Sel = Message->getSelector();
13590 
13591   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13592   if (!MKOpt) {
13593     return None;
13594   }
13595 
13596   NSAPI::NSSetMethodKind MK = *MKOpt;
13597 
13598   switch (MK) {
13599     case NSAPI::NSMutableSet_addObject:
13600     case NSAPI::NSOrderedSet_setObjectAtIndex:
13601     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13602     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13603       return 0;
13604     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13605       return 1;
13606   }
13607 
13608   return None;
13609 }
13610 
13611 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13612   if (!Message->isInstanceMessage()) {
13613     return;
13614   }
13615 
13616   Optional<int> ArgOpt;
13617 
13618   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13619       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13620       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13621     return;
13622   }
13623 
13624   int ArgIndex = *ArgOpt;
13625 
13626   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13627   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13628     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13629   }
13630 
13631   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13632     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13633       if (ArgRE->isObjCSelfExpr()) {
13634         Diag(Message->getSourceRange().getBegin(),
13635              diag::warn_objc_circular_container)
13636           << ArgRE->getDecl() << StringRef("'super'");
13637       }
13638     }
13639   } else {
13640     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13641 
13642     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13643       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13644     }
13645 
13646     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13647       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13648         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13649           ValueDecl *Decl = ReceiverRE->getDecl();
13650           Diag(Message->getSourceRange().getBegin(),
13651                diag::warn_objc_circular_container)
13652             << Decl << Decl;
13653           if (!ArgRE->isObjCSelfExpr()) {
13654             Diag(Decl->getLocation(),
13655                  diag::note_objc_circular_container_declared_here)
13656               << Decl;
13657           }
13658         }
13659       }
13660     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13661       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13662         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13663           ObjCIvarDecl *Decl = IvarRE->getDecl();
13664           Diag(Message->getSourceRange().getBegin(),
13665                diag::warn_objc_circular_container)
13666             << Decl << Decl;
13667           Diag(Decl->getLocation(),
13668                diag::note_objc_circular_container_declared_here)
13669             << Decl;
13670         }
13671       }
13672     }
13673   }
13674 }
13675 
13676 /// Check a message send to see if it's likely to cause a retain cycle.
13677 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13678   // Only check instance methods whose selector looks like a setter.
13679   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13680     return;
13681 
13682   // Try to find a variable that the receiver is strongly owned by.
13683   RetainCycleOwner owner;
13684   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13685     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13686       return;
13687   } else {
13688     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13689     owner.Variable = getCurMethodDecl()->getSelfDecl();
13690     owner.Loc = msg->getSuperLoc();
13691     owner.Range = msg->getSuperLoc();
13692   }
13693 
13694   // Check whether the receiver is captured by any of the arguments.
13695   const ObjCMethodDecl *MD = msg->getMethodDecl();
13696   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13697     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13698       // noescape blocks should not be retained by the method.
13699       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13700         continue;
13701       return diagnoseRetainCycle(*this, capturer, owner);
13702     }
13703   }
13704 }
13705 
13706 /// Check a property assign to see if it's likely to cause a retain cycle.
13707 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13708   RetainCycleOwner owner;
13709   if (!findRetainCycleOwner(*this, receiver, owner))
13710     return;
13711 
13712   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13713     diagnoseRetainCycle(*this, capturer, owner);
13714 }
13715 
13716 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13717   RetainCycleOwner Owner;
13718   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13719     return;
13720 
13721   // Because we don't have an expression for the variable, we have to set the
13722   // location explicitly here.
13723   Owner.Loc = Var->getLocation();
13724   Owner.Range = Var->getSourceRange();
13725 
13726   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13727     diagnoseRetainCycle(*this, Capturer, Owner);
13728 }
13729 
13730 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13731                                      Expr *RHS, bool isProperty) {
13732   // Check if RHS is an Objective-C object literal, which also can get
13733   // immediately zapped in a weak reference.  Note that we explicitly
13734   // allow ObjCStringLiterals, since those are designed to never really die.
13735   RHS = RHS->IgnoreParenImpCasts();
13736 
13737   // This enum needs to match with the 'select' in
13738   // warn_objc_arc_literal_assign (off-by-1).
13739   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13740   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13741     return false;
13742 
13743   S.Diag(Loc, diag::warn_arc_literal_assign)
13744     << (unsigned) Kind
13745     << (isProperty ? 0 : 1)
13746     << RHS->getSourceRange();
13747 
13748   return true;
13749 }
13750 
13751 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13752                                     Qualifiers::ObjCLifetime LT,
13753                                     Expr *RHS, bool isProperty) {
13754   // Strip off any implicit cast added to get to the one ARC-specific.
13755   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13756     if (cast->getCastKind() == CK_ARCConsumeObject) {
13757       S.Diag(Loc, diag::warn_arc_retained_assign)
13758         << (LT == Qualifiers::OCL_ExplicitNone)
13759         << (isProperty ? 0 : 1)
13760         << RHS->getSourceRange();
13761       return true;
13762     }
13763     RHS = cast->getSubExpr();
13764   }
13765 
13766   if (LT == Qualifiers::OCL_Weak &&
13767       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13768     return true;
13769 
13770   return false;
13771 }
13772 
13773 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13774                               QualType LHS, Expr *RHS) {
13775   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13776 
13777   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13778     return false;
13779 
13780   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13781     return true;
13782 
13783   return false;
13784 }
13785 
13786 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13787                               Expr *LHS, Expr *RHS) {
13788   QualType LHSType;
13789   // PropertyRef on LHS type need be directly obtained from
13790   // its declaration as it has a PseudoType.
13791   ObjCPropertyRefExpr *PRE
13792     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13793   if (PRE && !PRE->isImplicitProperty()) {
13794     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13795     if (PD)
13796       LHSType = PD->getType();
13797   }
13798 
13799   if (LHSType.isNull())
13800     LHSType = LHS->getType();
13801 
13802   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13803 
13804   if (LT == Qualifiers::OCL_Weak) {
13805     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13806       getCurFunction()->markSafeWeakUse(LHS);
13807   }
13808 
13809   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13810     return;
13811 
13812   // FIXME. Check for other life times.
13813   if (LT != Qualifiers::OCL_None)
13814     return;
13815 
13816   if (PRE) {
13817     if (PRE->isImplicitProperty())
13818       return;
13819     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13820     if (!PD)
13821       return;
13822 
13823     unsigned Attributes = PD->getPropertyAttributes();
13824     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13825       // when 'assign' attribute was not explicitly specified
13826       // by user, ignore it and rely on property type itself
13827       // for lifetime info.
13828       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13829       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13830           LHSType->isObjCRetainableType())
13831         return;
13832 
13833       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13834         if (cast->getCastKind() == CK_ARCConsumeObject) {
13835           Diag(Loc, diag::warn_arc_retained_property_assign)
13836           << RHS->getSourceRange();
13837           return;
13838         }
13839         RHS = cast->getSubExpr();
13840       }
13841     }
13842     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13843       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13844         return;
13845     }
13846   }
13847 }
13848 
13849 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13850 
13851 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13852                                         SourceLocation StmtLoc,
13853                                         const NullStmt *Body) {
13854   // Do not warn if the body is a macro that expands to nothing, e.g:
13855   //
13856   // #define CALL(x)
13857   // if (condition)
13858   //   CALL(0);
13859   if (Body->hasLeadingEmptyMacro())
13860     return false;
13861 
13862   // Get line numbers of statement and body.
13863   bool StmtLineInvalid;
13864   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13865                                                       &StmtLineInvalid);
13866   if (StmtLineInvalid)
13867     return false;
13868 
13869   bool BodyLineInvalid;
13870   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13871                                                       &BodyLineInvalid);
13872   if (BodyLineInvalid)
13873     return false;
13874 
13875   // Warn if null statement and body are on the same line.
13876   if (StmtLine != BodyLine)
13877     return false;
13878 
13879   return true;
13880 }
13881 
13882 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13883                                  const Stmt *Body,
13884                                  unsigned DiagID) {
13885   // Since this is a syntactic check, don't emit diagnostic for template
13886   // instantiations, this just adds noise.
13887   if (CurrentInstantiationScope)
13888     return;
13889 
13890   // The body should be a null statement.
13891   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13892   if (!NBody)
13893     return;
13894 
13895   // Do the usual checks.
13896   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13897     return;
13898 
13899   Diag(NBody->getSemiLoc(), DiagID);
13900   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13901 }
13902 
13903 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13904                                  const Stmt *PossibleBody) {
13905   assert(!CurrentInstantiationScope); // Ensured by caller
13906 
13907   SourceLocation StmtLoc;
13908   const Stmt *Body;
13909   unsigned DiagID;
13910   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13911     StmtLoc = FS->getRParenLoc();
13912     Body = FS->getBody();
13913     DiagID = diag::warn_empty_for_body;
13914   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13915     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13916     Body = WS->getBody();
13917     DiagID = diag::warn_empty_while_body;
13918   } else
13919     return; // Neither `for' nor `while'.
13920 
13921   // The body should be a null statement.
13922   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13923   if (!NBody)
13924     return;
13925 
13926   // Skip expensive checks if diagnostic is disabled.
13927   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13928     return;
13929 
13930   // Do the usual checks.
13931   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13932     return;
13933 
13934   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13935   // noise level low, emit diagnostics only if for/while is followed by a
13936   // CompoundStmt, e.g.:
13937   //    for (int i = 0; i < n; i++);
13938   //    {
13939   //      a(i);
13940   //    }
13941   // or if for/while is followed by a statement with more indentation
13942   // than for/while itself:
13943   //    for (int i = 0; i < n; i++);
13944   //      a(i);
13945   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13946   if (!ProbableTypo) {
13947     bool BodyColInvalid;
13948     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13949         PossibleBody->getBeginLoc(), &BodyColInvalid);
13950     if (BodyColInvalid)
13951       return;
13952 
13953     bool StmtColInvalid;
13954     unsigned StmtCol =
13955         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13956     if (StmtColInvalid)
13957       return;
13958 
13959     if (BodyCol > StmtCol)
13960       ProbableTypo = true;
13961   }
13962 
13963   if (ProbableTypo) {
13964     Diag(NBody->getSemiLoc(), DiagID);
13965     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13966   }
13967 }
13968 
13969 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13970 
13971 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13972 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13973                              SourceLocation OpLoc) {
13974   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13975     return;
13976 
13977   if (inTemplateInstantiation())
13978     return;
13979 
13980   // Strip parens and casts away.
13981   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13982   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13983 
13984   // Check for a call expression
13985   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13986   if (!CE || CE->getNumArgs() != 1)
13987     return;
13988 
13989   // Check for a call to std::move
13990   if (!CE->isCallToStdMove())
13991     return;
13992 
13993   // Get argument from std::move
13994   RHSExpr = CE->getArg(0);
13995 
13996   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13997   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13998 
13999   // Two DeclRefExpr's, check that the decls are the same.
14000   if (LHSDeclRef && RHSDeclRef) {
14001     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14002       return;
14003     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14004         RHSDeclRef->getDecl()->getCanonicalDecl())
14005       return;
14006 
14007     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14008                                         << LHSExpr->getSourceRange()
14009                                         << RHSExpr->getSourceRange();
14010     return;
14011   }
14012 
14013   // Member variables require a different approach to check for self moves.
14014   // MemberExpr's are the same if every nested MemberExpr refers to the same
14015   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14016   // the base Expr's are CXXThisExpr's.
14017   const Expr *LHSBase = LHSExpr;
14018   const Expr *RHSBase = RHSExpr;
14019   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14020   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14021   if (!LHSME || !RHSME)
14022     return;
14023 
14024   while (LHSME && RHSME) {
14025     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14026         RHSME->getMemberDecl()->getCanonicalDecl())
14027       return;
14028 
14029     LHSBase = LHSME->getBase();
14030     RHSBase = RHSME->getBase();
14031     LHSME = dyn_cast<MemberExpr>(LHSBase);
14032     RHSME = dyn_cast<MemberExpr>(RHSBase);
14033   }
14034 
14035   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14036   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14037   if (LHSDeclRef && RHSDeclRef) {
14038     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14039       return;
14040     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14041         RHSDeclRef->getDecl()->getCanonicalDecl())
14042       return;
14043 
14044     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14045                                         << LHSExpr->getSourceRange()
14046                                         << RHSExpr->getSourceRange();
14047     return;
14048   }
14049 
14050   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14051     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14052                                         << LHSExpr->getSourceRange()
14053                                         << RHSExpr->getSourceRange();
14054 }
14055 
14056 //===--- Layout compatibility ----------------------------------------------//
14057 
14058 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14059 
14060 /// Check if two enumeration types are layout-compatible.
14061 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14062   // C++11 [dcl.enum] p8:
14063   // Two enumeration types are layout-compatible if they have the same
14064   // underlying type.
14065   return ED1->isComplete() && ED2->isComplete() &&
14066          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14067 }
14068 
14069 /// Check if two fields are layout-compatible.
14070 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14071                                FieldDecl *Field2) {
14072   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14073     return false;
14074 
14075   if (Field1->isBitField() != Field2->isBitField())
14076     return false;
14077 
14078   if (Field1->isBitField()) {
14079     // Make sure that the bit-fields are the same length.
14080     unsigned Bits1 = Field1->getBitWidthValue(C);
14081     unsigned Bits2 = Field2->getBitWidthValue(C);
14082 
14083     if (Bits1 != Bits2)
14084       return false;
14085   }
14086 
14087   return true;
14088 }
14089 
14090 /// Check if two standard-layout structs are layout-compatible.
14091 /// (C++11 [class.mem] p17)
14092 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14093                                      RecordDecl *RD2) {
14094   // If both records are C++ classes, check that base classes match.
14095   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14096     // If one of records is a CXXRecordDecl we are in C++ mode,
14097     // thus the other one is a CXXRecordDecl, too.
14098     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14099     // Check number of base classes.
14100     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14101       return false;
14102 
14103     // Check the base classes.
14104     for (CXXRecordDecl::base_class_const_iterator
14105                Base1 = D1CXX->bases_begin(),
14106            BaseEnd1 = D1CXX->bases_end(),
14107               Base2 = D2CXX->bases_begin();
14108          Base1 != BaseEnd1;
14109          ++Base1, ++Base2) {
14110       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14111         return false;
14112     }
14113   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14114     // If only RD2 is a C++ class, it should have zero base classes.
14115     if (D2CXX->getNumBases() > 0)
14116       return false;
14117   }
14118 
14119   // Check the fields.
14120   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14121                              Field2End = RD2->field_end(),
14122                              Field1 = RD1->field_begin(),
14123                              Field1End = RD1->field_end();
14124   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14125     if (!isLayoutCompatible(C, *Field1, *Field2))
14126       return false;
14127   }
14128   if (Field1 != Field1End || Field2 != Field2End)
14129     return false;
14130 
14131   return true;
14132 }
14133 
14134 /// Check if two standard-layout unions are layout-compatible.
14135 /// (C++11 [class.mem] p18)
14136 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14137                                     RecordDecl *RD2) {
14138   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14139   for (auto *Field2 : RD2->fields())
14140     UnmatchedFields.insert(Field2);
14141 
14142   for (auto *Field1 : RD1->fields()) {
14143     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14144         I = UnmatchedFields.begin(),
14145         E = UnmatchedFields.end();
14146 
14147     for ( ; I != E; ++I) {
14148       if (isLayoutCompatible(C, Field1, *I)) {
14149         bool Result = UnmatchedFields.erase(*I);
14150         (void) Result;
14151         assert(Result);
14152         break;
14153       }
14154     }
14155     if (I == E)
14156       return false;
14157   }
14158 
14159   return UnmatchedFields.empty();
14160 }
14161 
14162 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14163                                RecordDecl *RD2) {
14164   if (RD1->isUnion() != RD2->isUnion())
14165     return false;
14166 
14167   if (RD1->isUnion())
14168     return isLayoutCompatibleUnion(C, RD1, RD2);
14169   else
14170     return isLayoutCompatibleStruct(C, RD1, RD2);
14171 }
14172 
14173 /// Check if two types are layout-compatible in C++11 sense.
14174 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14175   if (T1.isNull() || T2.isNull())
14176     return false;
14177 
14178   // C++11 [basic.types] p11:
14179   // If two types T1 and T2 are the same type, then T1 and T2 are
14180   // layout-compatible types.
14181   if (C.hasSameType(T1, T2))
14182     return true;
14183 
14184   T1 = T1.getCanonicalType().getUnqualifiedType();
14185   T2 = T2.getCanonicalType().getUnqualifiedType();
14186 
14187   const Type::TypeClass TC1 = T1->getTypeClass();
14188   const Type::TypeClass TC2 = T2->getTypeClass();
14189 
14190   if (TC1 != TC2)
14191     return false;
14192 
14193   if (TC1 == Type::Enum) {
14194     return isLayoutCompatible(C,
14195                               cast<EnumType>(T1)->getDecl(),
14196                               cast<EnumType>(T2)->getDecl());
14197   } else if (TC1 == Type::Record) {
14198     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14199       return false;
14200 
14201     return isLayoutCompatible(C,
14202                               cast<RecordType>(T1)->getDecl(),
14203                               cast<RecordType>(T2)->getDecl());
14204   }
14205 
14206   return false;
14207 }
14208 
14209 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14210 
14211 /// Given a type tag expression find the type tag itself.
14212 ///
14213 /// \param TypeExpr Type tag expression, as it appears in user's code.
14214 ///
14215 /// \param VD Declaration of an identifier that appears in a type tag.
14216 ///
14217 /// \param MagicValue Type tag magic value.
14218 ///
14219 /// \param isConstantEvaluated wether the evalaution should be performed in
14220 
14221 /// constant context.
14222 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14223                             const ValueDecl **VD, uint64_t *MagicValue,
14224                             bool isConstantEvaluated) {
14225   while(true) {
14226     if (!TypeExpr)
14227       return false;
14228 
14229     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14230 
14231     switch (TypeExpr->getStmtClass()) {
14232     case Stmt::UnaryOperatorClass: {
14233       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14234       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14235         TypeExpr = UO->getSubExpr();
14236         continue;
14237       }
14238       return false;
14239     }
14240 
14241     case Stmt::DeclRefExprClass: {
14242       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14243       *VD = DRE->getDecl();
14244       return true;
14245     }
14246 
14247     case Stmt::IntegerLiteralClass: {
14248       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14249       llvm::APInt MagicValueAPInt = IL->getValue();
14250       if (MagicValueAPInt.getActiveBits() <= 64) {
14251         *MagicValue = MagicValueAPInt.getZExtValue();
14252         return true;
14253       } else
14254         return false;
14255     }
14256 
14257     case Stmt::BinaryConditionalOperatorClass:
14258     case Stmt::ConditionalOperatorClass: {
14259       const AbstractConditionalOperator *ACO =
14260           cast<AbstractConditionalOperator>(TypeExpr);
14261       bool Result;
14262       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14263                                                      isConstantEvaluated)) {
14264         if (Result)
14265           TypeExpr = ACO->getTrueExpr();
14266         else
14267           TypeExpr = ACO->getFalseExpr();
14268         continue;
14269       }
14270       return false;
14271     }
14272 
14273     case Stmt::BinaryOperatorClass: {
14274       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14275       if (BO->getOpcode() == BO_Comma) {
14276         TypeExpr = BO->getRHS();
14277         continue;
14278       }
14279       return false;
14280     }
14281 
14282     default:
14283       return false;
14284     }
14285   }
14286 }
14287 
14288 /// Retrieve the C type corresponding to type tag TypeExpr.
14289 ///
14290 /// \param TypeExpr Expression that specifies a type tag.
14291 ///
14292 /// \param MagicValues Registered magic values.
14293 ///
14294 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14295 ///        kind.
14296 ///
14297 /// \param TypeInfo Information about the corresponding C type.
14298 ///
14299 /// \param isConstantEvaluated wether the evalaution should be performed in
14300 /// constant context.
14301 ///
14302 /// \returns true if the corresponding C type was found.
14303 static bool GetMatchingCType(
14304     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14305     const ASTContext &Ctx,
14306     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14307         *MagicValues,
14308     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14309     bool isConstantEvaluated) {
14310   FoundWrongKind = false;
14311 
14312   // Variable declaration that has type_tag_for_datatype attribute.
14313   const ValueDecl *VD = nullptr;
14314 
14315   uint64_t MagicValue;
14316 
14317   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14318     return false;
14319 
14320   if (VD) {
14321     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14322       if (I->getArgumentKind() != ArgumentKind) {
14323         FoundWrongKind = true;
14324         return false;
14325       }
14326       TypeInfo.Type = I->getMatchingCType();
14327       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14328       TypeInfo.MustBeNull = I->getMustBeNull();
14329       return true;
14330     }
14331     return false;
14332   }
14333 
14334   if (!MagicValues)
14335     return false;
14336 
14337   llvm::DenseMap<Sema::TypeTagMagicValue,
14338                  Sema::TypeTagData>::const_iterator I =
14339       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14340   if (I == MagicValues->end())
14341     return false;
14342 
14343   TypeInfo = I->second;
14344   return true;
14345 }
14346 
14347 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14348                                       uint64_t MagicValue, QualType Type,
14349                                       bool LayoutCompatible,
14350                                       bool MustBeNull) {
14351   if (!TypeTagForDatatypeMagicValues)
14352     TypeTagForDatatypeMagicValues.reset(
14353         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14354 
14355   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14356   (*TypeTagForDatatypeMagicValues)[Magic] =
14357       TypeTagData(Type, LayoutCompatible, MustBeNull);
14358 }
14359 
14360 static bool IsSameCharType(QualType T1, QualType T2) {
14361   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14362   if (!BT1)
14363     return false;
14364 
14365   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14366   if (!BT2)
14367     return false;
14368 
14369   BuiltinType::Kind T1Kind = BT1->getKind();
14370   BuiltinType::Kind T2Kind = BT2->getKind();
14371 
14372   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14373          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14374          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14375          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14376 }
14377 
14378 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14379                                     const ArrayRef<const Expr *> ExprArgs,
14380                                     SourceLocation CallSiteLoc) {
14381   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14382   bool IsPointerAttr = Attr->getIsPointer();
14383 
14384   // Retrieve the argument representing the 'type_tag'.
14385   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14386   if (TypeTagIdxAST >= ExprArgs.size()) {
14387     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14388         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14389     return;
14390   }
14391   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14392   bool FoundWrongKind;
14393   TypeTagData TypeInfo;
14394   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14395                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14396                         TypeInfo, isConstantEvaluated())) {
14397     if (FoundWrongKind)
14398       Diag(TypeTagExpr->getExprLoc(),
14399            diag::warn_type_tag_for_datatype_wrong_kind)
14400         << TypeTagExpr->getSourceRange();
14401     return;
14402   }
14403 
14404   // Retrieve the argument representing the 'arg_idx'.
14405   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14406   if (ArgumentIdxAST >= ExprArgs.size()) {
14407     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14408         << 1 << Attr->getArgumentIdx().getSourceIndex();
14409     return;
14410   }
14411   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14412   if (IsPointerAttr) {
14413     // Skip implicit cast of pointer to `void *' (as a function argument).
14414     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14415       if (ICE->getType()->isVoidPointerType() &&
14416           ICE->getCastKind() == CK_BitCast)
14417         ArgumentExpr = ICE->getSubExpr();
14418   }
14419   QualType ArgumentType = ArgumentExpr->getType();
14420 
14421   // Passing a `void*' pointer shouldn't trigger a warning.
14422   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14423     return;
14424 
14425   if (TypeInfo.MustBeNull) {
14426     // Type tag with matching void type requires a null pointer.
14427     if (!ArgumentExpr->isNullPointerConstant(Context,
14428                                              Expr::NPC_ValueDependentIsNotNull)) {
14429       Diag(ArgumentExpr->getExprLoc(),
14430            diag::warn_type_safety_null_pointer_required)
14431           << ArgumentKind->getName()
14432           << ArgumentExpr->getSourceRange()
14433           << TypeTagExpr->getSourceRange();
14434     }
14435     return;
14436   }
14437 
14438   QualType RequiredType = TypeInfo.Type;
14439   if (IsPointerAttr)
14440     RequiredType = Context.getPointerType(RequiredType);
14441 
14442   bool mismatch = false;
14443   if (!TypeInfo.LayoutCompatible) {
14444     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14445 
14446     // C++11 [basic.fundamental] p1:
14447     // Plain char, signed char, and unsigned char are three distinct types.
14448     //
14449     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14450     // char' depending on the current char signedness mode.
14451     if (mismatch)
14452       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14453                                            RequiredType->getPointeeType())) ||
14454           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14455         mismatch = false;
14456   } else
14457     if (IsPointerAttr)
14458       mismatch = !isLayoutCompatible(Context,
14459                                      ArgumentType->getPointeeType(),
14460                                      RequiredType->getPointeeType());
14461     else
14462       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14463 
14464   if (mismatch)
14465     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14466         << ArgumentType << ArgumentKind
14467         << TypeInfo.LayoutCompatible << RequiredType
14468         << ArgumentExpr->getSourceRange()
14469         << TypeTagExpr->getSourceRange();
14470 }
14471 
14472 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14473                                          CharUnits Alignment) {
14474   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14475 }
14476 
14477 void Sema::DiagnoseMisalignedMembers() {
14478   for (MisalignedMember &m : MisalignedMembers) {
14479     const NamedDecl *ND = m.RD;
14480     if (ND->getName().empty()) {
14481       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14482         ND = TD;
14483     }
14484     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14485         << m.MD << ND << m.E->getSourceRange();
14486   }
14487   MisalignedMembers.clear();
14488 }
14489 
14490 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14491   E = E->IgnoreParens();
14492   if (!T->isPointerType() && !T->isIntegerType())
14493     return;
14494   if (isa<UnaryOperator>(E) &&
14495       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14496     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14497     if (isa<MemberExpr>(Op)) {
14498       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14499       if (MA != MisalignedMembers.end() &&
14500           (T->isIntegerType() ||
14501            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14502                                    Context.getTypeAlignInChars(
14503                                        T->getPointeeType()) <= MA->Alignment))))
14504         MisalignedMembers.erase(MA);
14505     }
14506   }
14507 }
14508 
14509 void Sema::RefersToMemberWithReducedAlignment(
14510     Expr *E,
14511     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14512         Action) {
14513   const auto *ME = dyn_cast<MemberExpr>(E);
14514   if (!ME)
14515     return;
14516 
14517   // No need to check expressions with an __unaligned-qualified type.
14518   if (E->getType().getQualifiers().hasUnaligned())
14519     return;
14520 
14521   // For a chain of MemberExpr like "a.b.c.d" this list
14522   // will keep FieldDecl's like [d, c, b].
14523   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14524   const MemberExpr *TopME = nullptr;
14525   bool AnyIsPacked = false;
14526   do {
14527     QualType BaseType = ME->getBase()->getType();
14528     if (ME->isArrow())
14529       BaseType = BaseType->getPointeeType();
14530     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14531     if (RD->isInvalidDecl())
14532       return;
14533 
14534     ValueDecl *MD = ME->getMemberDecl();
14535     auto *FD = dyn_cast<FieldDecl>(MD);
14536     // We do not care about non-data members.
14537     if (!FD || FD->isInvalidDecl())
14538       return;
14539 
14540     AnyIsPacked =
14541         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14542     ReverseMemberChain.push_back(FD);
14543 
14544     TopME = ME;
14545     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14546   } while (ME);
14547   assert(TopME && "We did not compute a topmost MemberExpr!");
14548 
14549   // Not the scope of this diagnostic.
14550   if (!AnyIsPacked)
14551     return;
14552 
14553   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14554   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14555   // TODO: The innermost base of the member expression may be too complicated.
14556   // For now, just disregard these cases. This is left for future
14557   // improvement.
14558   if (!DRE && !isa<CXXThisExpr>(TopBase))
14559       return;
14560 
14561   // Alignment expected by the whole expression.
14562   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14563 
14564   // No need to do anything else with this case.
14565   if (ExpectedAlignment.isOne())
14566     return;
14567 
14568   // Synthesize offset of the whole access.
14569   CharUnits Offset;
14570   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14571        I++) {
14572     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14573   }
14574 
14575   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14576   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14577       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14578 
14579   // The base expression of the innermost MemberExpr may give
14580   // stronger guarantees than the class containing the member.
14581   if (DRE && !TopME->isArrow()) {
14582     const ValueDecl *VD = DRE->getDecl();
14583     if (!VD->getType()->isReferenceType())
14584       CompleteObjectAlignment =
14585           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14586   }
14587 
14588   // Check if the synthesized offset fulfills the alignment.
14589   if (Offset % ExpectedAlignment != 0 ||
14590       // It may fulfill the offset it but the effective alignment may still be
14591       // lower than the expected expression alignment.
14592       CompleteObjectAlignment < ExpectedAlignment) {
14593     // If this happens, we want to determine a sensible culprit of this.
14594     // Intuitively, watching the chain of member expressions from right to
14595     // left, we start with the required alignment (as required by the field
14596     // type) but some packed attribute in that chain has reduced the alignment.
14597     // It may happen that another packed structure increases it again. But if
14598     // we are here such increase has not been enough. So pointing the first
14599     // FieldDecl that either is packed or else its RecordDecl is,
14600     // seems reasonable.
14601     FieldDecl *FD = nullptr;
14602     CharUnits Alignment;
14603     for (FieldDecl *FDI : ReverseMemberChain) {
14604       if (FDI->hasAttr<PackedAttr>() ||
14605           FDI->getParent()->hasAttr<PackedAttr>()) {
14606         FD = FDI;
14607         Alignment = std::min(
14608             Context.getTypeAlignInChars(FD->getType()),
14609             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14610         break;
14611       }
14612     }
14613     assert(FD && "We did not find a packed FieldDecl!");
14614     Action(E, FD->getParent(), FD, Alignment);
14615   }
14616 }
14617 
14618 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14619   using namespace std::placeholders;
14620 
14621   RefersToMemberWithReducedAlignment(
14622       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14623                      _2, _3, _4));
14624 }
14625