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/raw_ostream.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstddef>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 
98 using namespace clang;
99 using namespace sema;
100 
101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102                                                     unsigned ByteNo) const {
103   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104                                Context.getTargetInfo());
105 }
106 
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking.  Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110   unsigned argCount = call->getNumArgs();
111   if (argCount == desiredArgCount) return false;
112 
113   if (argCount < desiredArgCount)
114     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
115            << 0 /*function call*/ << desiredArgCount << argCount
116            << call->getSourceRange();
117 
118   // Highlight all the excess arguments.
119   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
120                     call->getArg(argCount - 1)->getEndLoc());
121 
122   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123     << 0 /*function call*/ << desiredArgCount << argCount
124     << call->getArg(1)->getSourceRange();
125 }
126 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130   if (checkArgCount(S, TheCall, 2))
131     return true;
132 
133   // First argument should be an integer.
134   Expr *ValArg = TheCall->getArg(0);
135   QualType Ty = ValArg->getType();
136   if (!Ty->isIntegerType()) {
137     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
138         << ValArg->getSourceRange();
139     return true;
140   }
141 
142   // Second argument should be a constant string.
143   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145   if (!Literal || !Literal->isAscii()) {
146     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
147         << StrArg->getSourceRange();
148     return true;
149   }
150 
151   TheCall->setType(Ty);
152   return false;
153 }
154 
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156   // We need at least one argument.
157   if (TheCall->getNumArgs() < 1) {
158     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
159         << 0 << 1 << TheCall->getNumArgs()
160         << TheCall->getCallee()->getSourceRange();
161     return true;
162   }
163 
164   // All arguments should be wide string literals.
165   for (Expr *Arg : TheCall->arguments()) {
166     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167     if (!Literal || !Literal->isWide()) {
168       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
169           << Arg->getSourceRange();
170       return true;
171     }
172   }
173 
174   return false;
175 }
176 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180   if (checkArgCount(S, TheCall, 1))
181     return true;
182 
183   ExprResult Arg(TheCall->getArg(0));
184   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
185   if (ResultType.isNull())
186     return true;
187 
188   TheCall->setArg(0, Arg.get());
189   TheCall->setType(ResultType);
190   return false;
191 }
192 
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194   if (checkArgCount(S, TheCall, 3))
195     return true;
196 
197   // First two arguments should be integers.
198   for (unsigned I = 0; I < 2; ++I) {
199     ExprResult Arg = TheCall->getArg(I);
200     QualType Ty = Arg.get()->getType();
201     if (!Ty->isIntegerType()) {
202       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
203           << Ty << Arg.get()->getSourceRange();
204       return true;
205     }
206     InitializedEntity Entity = InitializedEntity::InitializeParameter(
207         S.getASTContext(), Ty, /*consume*/ false);
208     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
209     if (Arg.isInvalid())
210       return true;
211     TheCall->setArg(I, Arg.get());
212   }
213 
214   // Third argument should be a pointer to a non-const integer.
215   // IRGen correctly handles volatile, restrict, and address spaces, and
216   // the other qualifiers aren't possible.
217   {
218     ExprResult Arg = TheCall->getArg(2);
219     QualType Ty = Arg.get()->getType();
220     const auto *PtrTy = Ty->getAs<PointerType>();
221     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
222           !PtrTy->getPointeeType().isConstQualified())) {
223       S.Diag(Arg.get()->getBeginLoc(),
224              diag::err_overflow_builtin_must_be_ptr_int)
225           << Ty << Arg.get()->getSourceRange();
226       return true;
227     }
228     InitializedEntity Entity = InitializedEntity::InitializeParameter(
229         S.getASTContext(), Ty, /*consume*/ false);
230     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
231     if (Arg.isInvalid())
232       return true;
233     TheCall->setArg(2, Arg.get());
234   }
235   return false;
236 }
237 
238 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
239                                   CallExpr *TheCall, unsigned SizeIdx,
240                                   unsigned DstSizeIdx,
241                                   StringRef LikelyMacroName) {
242   if (TheCall->getNumArgs() <= SizeIdx ||
243       TheCall->getNumArgs() <= DstSizeIdx)
244     return;
245 
246   const Expr *SizeArg = TheCall->getArg(SizeIdx);
247   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248 
249   Expr::EvalResult SizeResult, DstSizeResult;
250 
251   // find out if both sizes are known at compile time
252   if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) ||
253       !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context))
254     return;
255 
256   llvm::APSInt Size = SizeResult.Val.getInt();
257   llvm::APSInt DstSize = DstSizeResult.Val.getInt();
258 
259   if (Size.ule(DstSize))
260     return;
261 
262   // Confirmed overflow, so generate the diagnostic.
263   StringRef FunctionName = FDecl->getName();
264   SourceLocation SL = TheCall->getBeginLoc();
265   SourceManager &SM = S.getSourceManager();
266   // If we're in an expansion of a macro whose name corresponds to this builtin,
267   // use the simple macro name and location.
268   if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
269                             LikelyMacroName) {
270     FunctionName = LikelyMacroName;
271     SL = SM.getImmediateMacroCallerLoc(SL);
272   }
273 
274   S.Diag(SL, diag::warn_memcpy_chk_overflow)
275       << FunctionName << DstSize.toString(/*Radix=*/10)
276       << Size.toString(/*Radix=*/10);
277 }
278 
279 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
280   if (checkArgCount(S, BuiltinCall, 2))
281     return true;
282 
283   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
284   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
285   Expr *Call = BuiltinCall->getArg(0);
286   Expr *Chain = BuiltinCall->getArg(1);
287 
288   if (Call->getStmtClass() != Stmt::CallExprClass) {
289     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
290         << Call->getSourceRange();
291     return true;
292   }
293 
294   auto CE = cast<CallExpr>(Call);
295   if (CE->getCallee()->getType()->isBlockPointerType()) {
296     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
297         << Call->getSourceRange();
298     return true;
299   }
300 
301   const Decl *TargetDecl = CE->getCalleeDecl();
302   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
303     if (FD->getBuiltinID()) {
304       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
305           << Call->getSourceRange();
306       return true;
307     }
308 
309   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
310     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
311         << Call->getSourceRange();
312     return true;
313   }
314 
315   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
316   if (ChainResult.isInvalid())
317     return true;
318   if (!ChainResult.get()->getType()->isPointerType()) {
319     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
320         << Chain->getSourceRange();
321     return true;
322   }
323 
324   QualType ReturnTy = CE->getCallReturnType(S.Context);
325   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
326   QualType BuiltinTy = S.Context.getFunctionType(
327       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
328   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
329 
330   Builtin =
331       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
332 
333   BuiltinCall->setType(CE->getType());
334   BuiltinCall->setValueKind(CE->getValueKind());
335   BuiltinCall->setObjectKind(CE->getObjectKind());
336   BuiltinCall->setCallee(Builtin);
337   BuiltinCall->setArg(1, ChainResult.get());
338 
339   return false;
340 }
341 
342 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
343                                      Scope::ScopeFlags NeededScopeFlags,
344                                      unsigned DiagID) {
345   // Scopes aren't available during instantiation. Fortunately, builtin
346   // functions cannot be template args so they cannot be formed through template
347   // instantiation. Therefore checking once during the parse is sufficient.
348   if (SemaRef.inTemplateInstantiation())
349     return false;
350 
351   Scope *S = SemaRef.getCurScope();
352   while (S && !S->isSEHExceptScope())
353     S = S->getParent();
354   if (!S || !(S->getFlags() & NeededScopeFlags)) {
355     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
356     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
357         << DRE->getDecl()->getIdentifier();
358     return true;
359   }
360 
361   return false;
362 }
363 
364 static inline bool isBlockPointer(Expr *Arg) {
365   return Arg->getType()->isBlockPointerType();
366 }
367 
368 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
369 /// void*, which is a requirement of device side enqueue.
370 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
371   const BlockPointerType *BPT =
372       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
373   ArrayRef<QualType> Params =
374       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
375   unsigned ArgCounter = 0;
376   bool IllegalParams = false;
377   // Iterate through the block parameters until either one is found that is not
378   // a local void*, or the block is valid.
379   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
380        I != E; ++I, ++ArgCounter) {
381     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
382         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
383             LangAS::opencl_local) {
384       // Get the location of the error. If a block literal has been passed
385       // (BlockExpr) then we can point straight to the offending argument,
386       // else we just point to the variable reference.
387       SourceLocation ErrorLoc;
388       if (isa<BlockExpr>(BlockArg)) {
389         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
390         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
391       } else if (isa<DeclRefExpr>(BlockArg)) {
392         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
393       }
394       S.Diag(ErrorLoc,
395              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
396       IllegalParams = true;
397     }
398   }
399 
400   return IllegalParams;
401 }
402 
403 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
404   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
405     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
406         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
407     return true;
408   }
409   return false;
410 }
411 
412 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
413   if (checkArgCount(S, TheCall, 2))
414     return true;
415 
416   if (checkOpenCLSubgroupExt(S, TheCall))
417     return true;
418 
419   // First argument is an ndrange_t type.
420   Expr *NDRangeArg = TheCall->getArg(0);
421   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
422     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
423         << TheCall->getDirectCallee() << "'ndrange_t'";
424     return true;
425   }
426 
427   Expr *BlockArg = TheCall->getArg(1);
428   if (!isBlockPointer(BlockArg)) {
429     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
430         << TheCall->getDirectCallee() << "block";
431     return true;
432   }
433   return checkOpenCLBlockArgs(S, BlockArg);
434 }
435 
436 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
437 /// get_kernel_work_group_size
438 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
439 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
440   if (checkArgCount(S, TheCall, 1))
441     return true;
442 
443   Expr *BlockArg = TheCall->getArg(0);
444   if (!isBlockPointer(BlockArg)) {
445     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
446         << TheCall->getDirectCallee() << "block";
447     return true;
448   }
449   return checkOpenCLBlockArgs(S, BlockArg);
450 }
451 
452 /// Diagnose integer type and any valid implicit conversion to it.
453 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
454                                       const QualType &IntType);
455 
456 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
457                                             unsigned Start, unsigned End) {
458   bool IllegalParams = false;
459   for (unsigned I = Start; I <= End; ++I)
460     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
461                                               S.Context.getSizeType());
462   return IllegalParams;
463 }
464 
465 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
466 /// 'local void*' parameter of passed block.
467 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
468                                            Expr *BlockArg,
469                                            unsigned NumNonVarArgs) {
470   const BlockPointerType *BPT =
471       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
472   unsigned NumBlockParams =
473       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
474   unsigned TotalNumArgs = TheCall->getNumArgs();
475 
476   // For each argument passed to the block, a corresponding uint needs to
477   // be passed to describe the size of the local memory.
478   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
479     S.Diag(TheCall->getBeginLoc(),
480            diag::err_opencl_enqueue_kernel_local_size_args);
481     return true;
482   }
483 
484   // Check that the sizes of the local memory are specified by integers.
485   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
486                                          TotalNumArgs - 1);
487 }
488 
489 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
490 /// overload formats specified in Table 6.13.17.1.
491 /// int enqueue_kernel(queue_t queue,
492 ///                    kernel_enqueue_flags_t flags,
493 ///                    const ndrange_t ndrange,
494 ///                    void (^block)(void))
495 /// int enqueue_kernel(queue_t queue,
496 ///                    kernel_enqueue_flags_t flags,
497 ///                    const ndrange_t ndrange,
498 ///                    uint num_events_in_wait_list,
499 ///                    clk_event_t *event_wait_list,
500 ///                    clk_event_t *event_ret,
501 ///                    void (^block)(void))
502 /// int enqueue_kernel(queue_t queue,
503 ///                    kernel_enqueue_flags_t flags,
504 ///                    const ndrange_t ndrange,
505 ///                    void (^block)(local void*, ...),
506 ///                    uint size0, ...)
507 /// int enqueue_kernel(queue_t queue,
508 ///                    kernel_enqueue_flags_t flags,
509 ///                    const ndrange_t ndrange,
510 ///                    uint num_events_in_wait_list,
511 ///                    clk_event_t *event_wait_list,
512 ///                    clk_event_t *event_ret,
513 ///                    void (^block)(local void*, ...),
514 ///                    uint size0, ...)
515 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
516   unsigned NumArgs = TheCall->getNumArgs();
517 
518   if (NumArgs < 4) {
519     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
520     return true;
521   }
522 
523   Expr *Arg0 = TheCall->getArg(0);
524   Expr *Arg1 = TheCall->getArg(1);
525   Expr *Arg2 = TheCall->getArg(2);
526   Expr *Arg3 = TheCall->getArg(3);
527 
528   // First argument always needs to be a queue_t type.
529   if (!Arg0->getType()->isQueueT()) {
530     S.Diag(TheCall->getArg(0)->getBeginLoc(),
531            diag::err_opencl_builtin_expected_type)
532         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
533     return true;
534   }
535 
536   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
537   if (!Arg1->getType()->isIntegerType()) {
538     S.Diag(TheCall->getArg(1)->getBeginLoc(),
539            diag::err_opencl_builtin_expected_type)
540         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
541     return true;
542   }
543 
544   // Third argument is always an ndrange_t type.
545   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
546     S.Diag(TheCall->getArg(2)->getBeginLoc(),
547            diag::err_opencl_builtin_expected_type)
548         << TheCall->getDirectCallee() << "'ndrange_t'";
549     return true;
550   }
551 
552   // With four arguments, there is only one form that the function could be
553   // called in: no events and no variable arguments.
554   if (NumArgs == 4) {
555     // check that the last argument is the right block type.
556     if (!isBlockPointer(Arg3)) {
557       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
558           << TheCall->getDirectCallee() << "block";
559       return true;
560     }
561     // we have a block type, check the prototype
562     const BlockPointerType *BPT =
563         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
564     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
565       S.Diag(Arg3->getBeginLoc(),
566              diag::err_opencl_enqueue_kernel_blocks_no_args);
567       return true;
568     }
569     return false;
570   }
571   // we can have block + varargs.
572   if (isBlockPointer(Arg3))
573     return (checkOpenCLBlockArgs(S, Arg3) ||
574             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
575   // last two cases with either exactly 7 args or 7 args and varargs.
576   if (NumArgs >= 7) {
577     // check common block argument.
578     Expr *Arg6 = TheCall->getArg(6);
579     if (!isBlockPointer(Arg6)) {
580       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
581           << TheCall->getDirectCallee() << "block";
582       return true;
583     }
584     if (checkOpenCLBlockArgs(S, Arg6))
585       return true;
586 
587     // Forth argument has to be any integer type.
588     if (!Arg3->getType()->isIntegerType()) {
589       S.Diag(TheCall->getArg(3)->getBeginLoc(),
590              diag::err_opencl_builtin_expected_type)
591           << TheCall->getDirectCallee() << "integer";
592       return true;
593     }
594     // check remaining common arguments.
595     Expr *Arg4 = TheCall->getArg(4);
596     Expr *Arg5 = TheCall->getArg(5);
597 
598     // Fifth argument is always passed as a pointer to clk_event_t.
599     if (!Arg4->isNullPointerConstant(S.Context,
600                                      Expr::NPC_ValueDependentIsNotNull) &&
601         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
602       S.Diag(TheCall->getArg(4)->getBeginLoc(),
603              diag::err_opencl_builtin_expected_type)
604           << TheCall->getDirectCallee()
605           << S.Context.getPointerType(S.Context.OCLClkEventTy);
606       return true;
607     }
608 
609     // Sixth argument is always passed as a pointer to clk_event_t.
610     if (!Arg5->isNullPointerConstant(S.Context,
611                                      Expr::NPC_ValueDependentIsNotNull) &&
612         !(Arg5->getType()->isPointerType() &&
613           Arg5->getType()->getPointeeType()->isClkEventT())) {
614       S.Diag(TheCall->getArg(5)->getBeginLoc(),
615              diag::err_opencl_builtin_expected_type)
616           << TheCall->getDirectCallee()
617           << S.Context.getPointerType(S.Context.OCLClkEventTy);
618       return true;
619     }
620 
621     if (NumArgs == 7)
622       return false;
623 
624     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
625   }
626 
627   // None of the specific case has been detected, give generic error
628   S.Diag(TheCall->getBeginLoc(),
629          diag::err_opencl_enqueue_kernel_incorrect_args);
630   return true;
631 }
632 
633 /// Returns OpenCL access qual.
634 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
635     return D->getAttr<OpenCLAccessAttr>();
636 }
637 
638 /// Returns true if pipe element type is different from the pointer.
639 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
640   const Expr *Arg0 = Call->getArg(0);
641   // First argument type should always be pipe.
642   if (!Arg0->getType()->isPipeType()) {
643     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
644         << Call->getDirectCallee() << Arg0->getSourceRange();
645     return true;
646   }
647   OpenCLAccessAttr *AccessQual =
648       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
649   // Validates the access qualifier is compatible with the call.
650   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
651   // read_only and write_only, and assumed to be read_only if no qualifier is
652   // specified.
653   switch (Call->getDirectCallee()->getBuiltinID()) {
654   case Builtin::BIread_pipe:
655   case Builtin::BIreserve_read_pipe:
656   case Builtin::BIcommit_read_pipe:
657   case Builtin::BIwork_group_reserve_read_pipe:
658   case Builtin::BIsub_group_reserve_read_pipe:
659   case Builtin::BIwork_group_commit_read_pipe:
660   case Builtin::BIsub_group_commit_read_pipe:
661     if (!(!AccessQual || AccessQual->isReadOnly())) {
662       S.Diag(Arg0->getBeginLoc(),
663              diag::err_opencl_builtin_pipe_invalid_access_modifier)
664           << "read_only" << Arg0->getSourceRange();
665       return true;
666     }
667     break;
668   case Builtin::BIwrite_pipe:
669   case Builtin::BIreserve_write_pipe:
670   case Builtin::BIcommit_write_pipe:
671   case Builtin::BIwork_group_reserve_write_pipe:
672   case Builtin::BIsub_group_reserve_write_pipe:
673   case Builtin::BIwork_group_commit_write_pipe:
674   case Builtin::BIsub_group_commit_write_pipe:
675     if (!(AccessQual && AccessQual->isWriteOnly())) {
676       S.Diag(Arg0->getBeginLoc(),
677              diag::err_opencl_builtin_pipe_invalid_access_modifier)
678           << "write_only" << Arg0->getSourceRange();
679       return true;
680     }
681     break;
682   default:
683     break;
684   }
685   return false;
686 }
687 
688 /// Returns true if pipe element type is different from the pointer.
689 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
690   const Expr *Arg0 = Call->getArg(0);
691   const Expr *ArgIdx = Call->getArg(Idx);
692   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
693   const QualType EltTy = PipeTy->getElementType();
694   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
695   // The Idx argument should be a pointer and the type of the pointer and
696   // the type of pipe element should also be the same.
697   if (!ArgTy ||
698       !S.Context.hasSameType(
699           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
700     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
701         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
702         << ArgIdx->getType() << ArgIdx->getSourceRange();
703     return true;
704   }
705   return false;
706 }
707 
708 // Performs semantic analysis for the read/write_pipe call.
709 // \param S Reference to the semantic analyzer.
710 // \param Call A pointer to the builtin call.
711 // \return True if a semantic error has been found, false otherwise.
712 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
713   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
714   // functions have two forms.
715   switch (Call->getNumArgs()) {
716   case 2:
717     if (checkOpenCLPipeArg(S, Call))
718       return true;
719     // The call with 2 arguments should be
720     // read/write_pipe(pipe T, T*).
721     // Check packet type T.
722     if (checkOpenCLPipePacketType(S, Call, 1))
723       return true;
724     break;
725 
726   case 4: {
727     if (checkOpenCLPipeArg(S, Call))
728       return true;
729     // The call with 4 arguments should be
730     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
731     // Check reserve_id_t.
732     if (!Call->getArg(1)->getType()->isReserveIDT()) {
733       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
734           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
735           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
736       return true;
737     }
738 
739     // Check the index.
740     const Expr *Arg2 = Call->getArg(2);
741     if (!Arg2->getType()->isIntegerType() &&
742         !Arg2->getType()->isUnsignedIntegerType()) {
743       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
744           << Call->getDirectCallee() << S.Context.UnsignedIntTy
745           << Arg2->getType() << Arg2->getSourceRange();
746       return true;
747     }
748 
749     // Check packet type T.
750     if (checkOpenCLPipePacketType(S, Call, 3))
751       return true;
752   } break;
753   default:
754     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
755         << Call->getDirectCallee() << Call->getSourceRange();
756     return true;
757   }
758 
759   return false;
760 }
761 
762 // Performs a semantic analysis on the {work_group_/sub_group_
763 //        /_}reserve_{read/write}_pipe
764 // \param S Reference to the semantic analyzer.
765 // \param Call The call to the builtin function to be analyzed.
766 // \return True if a semantic error was found, false otherwise.
767 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
768   if (checkArgCount(S, Call, 2))
769     return true;
770 
771   if (checkOpenCLPipeArg(S, Call))
772     return true;
773 
774   // Check the reserve size.
775   if (!Call->getArg(1)->getType()->isIntegerType() &&
776       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
777     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
778         << Call->getDirectCallee() << S.Context.UnsignedIntTy
779         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
780     return true;
781   }
782 
783   // Since return type of reserve_read/write_pipe built-in function is
784   // reserve_id_t, which is not defined in the builtin def file , we used int
785   // as return type and need to override the return type of these functions.
786   Call->setType(S.Context.OCLReserveIDTy);
787 
788   return false;
789 }
790 
791 // Performs a semantic analysis on {work_group_/sub_group_
792 //        /_}commit_{read/write}_pipe
793 // \param S Reference to the semantic analyzer.
794 // \param Call The call to the builtin function to be analyzed.
795 // \return True if a semantic error was found, false otherwise.
796 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
797   if (checkArgCount(S, Call, 2))
798     return true;
799 
800   if (checkOpenCLPipeArg(S, Call))
801     return true;
802 
803   // Check reserve_id_t.
804   if (!Call->getArg(1)->getType()->isReserveIDT()) {
805     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
806         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
807         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
808     return true;
809   }
810 
811   return false;
812 }
813 
814 // Performs a semantic analysis on the call to built-in Pipe
815 //        Query Functions.
816 // \param S Reference to the semantic analyzer.
817 // \param Call The call to the builtin function to be analyzed.
818 // \return True if a semantic error was found, false otherwise.
819 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
820   if (checkArgCount(S, Call, 1))
821     return true;
822 
823   if (!Call->getArg(0)->getType()->isPipeType()) {
824     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
825         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
826     return true;
827   }
828 
829   return false;
830 }
831 
832 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
833 // Performs semantic analysis for the to_global/local/private call.
834 // \param S Reference to the semantic analyzer.
835 // \param BuiltinID ID of the builtin function.
836 // \param Call A pointer to the builtin call.
837 // \return True if a semantic error has been found, false otherwise.
838 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
839                                     CallExpr *Call) {
840   if (Call->getNumArgs() != 1) {
841     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
842         << Call->getDirectCallee() << Call->getSourceRange();
843     return true;
844   }
845 
846   auto RT = Call->getArg(0)->getType();
847   if (!RT->isPointerType() || RT->getPointeeType()
848       .getAddressSpace() == LangAS::opencl_constant) {
849     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
850         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
851     return true;
852   }
853 
854   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
855     S.Diag(Call->getArg(0)->getBeginLoc(),
856            diag::warn_opencl_generic_address_space_arg)
857         << Call->getDirectCallee()->getNameInfo().getAsString()
858         << Call->getArg(0)->getSourceRange();
859   }
860 
861   RT = RT->getPointeeType();
862   auto Qual = RT.getQualifiers();
863   switch (BuiltinID) {
864   case Builtin::BIto_global:
865     Qual.setAddressSpace(LangAS::opencl_global);
866     break;
867   case Builtin::BIto_local:
868     Qual.setAddressSpace(LangAS::opencl_local);
869     break;
870   case Builtin::BIto_private:
871     Qual.setAddressSpace(LangAS::opencl_private);
872     break;
873   default:
874     llvm_unreachable("Invalid builtin function");
875   }
876   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
877       RT.getUnqualifiedType(), Qual)));
878 
879   return false;
880 }
881 
882 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
883   if (checkArgCount(S, TheCall, 1))
884     return ExprError();
885 
886   // Compute __builtin_launder's parameter type from the argument.
887   // The parameter type is:
888   //  * The type of the argument if it's not an array or function type,
889   //  Otherwise,
890   //  * The decayed argument type.
891   QualType ParamTy = [&]() {
892     QualType ArgTy = TheCall->getArg(0)->getType();
893     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
894       return S.Context.getPointerType(Ty->getElementType());
895     if (ArgTy->isFunctionType()) {
896       return S.Context.getPointerType(ArgTy);
897     }
898     return ArgTy;
899   }();
900 
901   TheCall->setType(ParamTy);
902 
903   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
904     if (!ParamTy->isPointerType())
905       return 0;
906     if (ParamTy->isFunctionPointerType())
907       return 1;
908     if (ParamTy->isVoidPointerType())
909       return 2;
910     return llvm::Optional<unsigned>{};
911   }();
912   if (DiagSelect.hasValue()) {
913     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
914         << DiagSelect.getValue() << TheCall->getSourceRange();
915     return ExprError();
916   }
917 
918   // We either have an incomplete class type, or we have a class template
919   // whose instantiation has not been forced. Example:
920   //
921   //   template <class T> struct Foo { T value; };
922   //   Foo<int> *p = nullptr;
923   //   auto *d = __builtin_launder(p);
924   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
925                             diag::err_incomplete_type))
926     return ExprError();
927 
928   assert(ParamTy->getPointeeType()->isObjectType() &&
929          "Unhandled non-object pointer case");
930 
931   InitializedEntity Entity =
932       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
933   ExprResult Arg =
934       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
935   if (Arg.isInvalid())
936     return ExprError();
937   TheCall->setArg(0, Arg.get());
938 
939   return TheCall;
940 }
941 
942 // Emit an error and return true if the current architecture is not in the list
943 // of supported architectures.
944 static bool
945 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
946                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
947   llvm::Triple::ArchType CurArch =
948       S.getASTContext().getTargetInfo().getTriple().getArch();
949   if (llvm::is_contained(SupportedArchs, CurArch))
950     return false;
951   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
952       << TheCall->getSourceRange();
953   return true;
954 }
955 
956 ExprResult
957 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
958                                CallExpr *TheCall) {
959   ExprResult TheCallResult(TheCall);
960 
961   // Find out if any arguments are required to be integer constant expressions.
962   unsigned ICEArguments = 0;
963   ASTContext::GetBuiltinTypeError Error;
964   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
965   if (Error != ASTContext::GE_None)
966     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
967 
968   // If any arguments are required to be ICE's, check and diagnose.
969   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
970     // Skip arguments not required to be ICE's.
971     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
972 
973     llvm::APSInt Result;
974     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
975       return true;
976     ICEArguments &= ~(1 << ArgNo);
977   }
978 
979   switch (BuiltinID) {
980   case Builtin::BI__builtin___CFStringMakeConstantString:
981     assert(TheCall->getNumArgs() == 1 &&
982            "Wrong # arguments to builtin CFStringMakeConstantString");
983     if (CheckObjCString(TheCall->getArg(0)))
984       return ExprError();
985     break;
986   case Builtin::BI__builtin_ms_va_start:
987   case Builtin::BI__builtin_stdarg_start:
988   case Builtin::BI__builtin_va_start:
989     if (SemaBuiltinVAStart(BuiltinID, TheCall))
990       return ExprError();
991     break;
992   case Builtin::BI__va_start: {
993     switch (Context.getTargetInfo().getTriple().getArch()) {
994     case llvm::Triple::aarch64:
995     case llvm::Triple::arm:
996     case llvm::Triple::thumb:
997       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
998         return ExprError();
999       break;
1000     default:
1001       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1002         return ExprError();
1003       break;
1004     }
1005     break;
1006   }
1007 
1008   // The acquire, release, and no fence variants are ARM and AArch64 only.
1009   case Builtin::BI_interlockedbittestandset_acq:
1010   case Builtin::BI_interlockedbittestandset_rel:
1011   case Builtin::BI_interlockedbittestandset_nf:
1012   case Builtin::BI_interlockedbittestandreset_acq:
1013   case Builtin::BI_interlockedbittestandreset_rel:
1014   case Builtin::BI_interlockedbittestandreset_nf:
1015     if (CheckBuiltinTargetSupport(
1016             *this, BuiltinID, TheCall,
1017             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1018       return ExprError();
1019     break;
1020 
1021   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1022   case Builtin::BI_bittest64:
1023   case Builtin::BI_bittestandcomplement64:
1024   case Builtin::BI_bittestandreset64:
1025   case Builtin::BI_bittestandset64:
1026   case Builtin::BI_interlockedbittestandreset64:
1027   case Builtin::BI_interlockedbittestandset64:
1028     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1029                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1030                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1031       return ExprError();
1032     break;
1033 
1034   case Builtin::BI__builtin_isgreater:
1035   case Builtin::BI__builtin_isgreaterequal:
1036   case Builtin::BI__builtin_isless:
1037   case Builtin::BI__builtin_islessequal:
1038   case Builtin::BI__builtin_islessgreater:
1039   case Builtin::BI__builtin_isunordered:
1040     if (SemaBuiltinUnorderedCompare(TheCall))
1041       return ExprError();
1042     break;
1043   case Builtin::BI__builtin_fpclassify:
1044     if (SemaBuiltinFPClassification(TheCall, 6))
1045       return ExprError();
1046     break;
1047   case Builtin::BI__builtin_isfinite:
1048   case Builtin::BI__builtin_isinf:
1049   case Builtin::BI__builtin_isinf_sign:
1050   case Builtin::BI__builtin_isnan:
1051   case Builtin::BI__builtin_isnormal:
1052   case Builtin::BI__builtin_signbit:
1053   case Builtin::BI__builtin_signbitf:
1054   case Builtin::BI__builtin_signbitl:
1055     if (SemaBuiltinFPClassification(TheCall, 1))
1056       return ExprError();
1057     break;
1058   case Builtin::BI__builtin_shufflevector:
1059     return SemaBuiltinShuffleVector(TheCall);
1060     // TheCall will be freed by the smart pointer here, but that's fine, since
1061     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1062   case Builtin::BI__builtin_prefetch:
1063     if (SemaBuiltinPrefetch(TheCall))
1064       return ExprError();
1065     break;
1066   case Builtin::BI__builtin_alloca_with_align:
1067     if (SemaBuiltinAllocaWithAlign(TheCall))
1068       return ExprError();
1069     break;
1070   case Builtin::BI__assume:
1071   case Builtin::BI__builtin_assume:
1072     if (SemaBuiltinAssume(TheCall))
1073       return ExprError();
1074     break;
1075   case Builtin::BI__builtin_assume_aligned:
1076     if (SemaBuiltinAssumeAligned(TheCall))
1077       return ExprError();
1078     break;
1079   case Builtin::BI__builtin_dynamic_object_size:
1080   case Builtin::BI__builtin_object_size:
1081     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1082       return ExprError();
1083     break;
1084   case Builtin::BI__builtin_longjmp:
1085     if (SemaBuiltinLongjmp(TheCall))
1086       return ExprError();
1087     break;
1088   case Builtin::BI__builtin_setjmp:
1089     if (SemaBuiltinSetjmp(TheCall))
1090       return ExprError();
1091     break;
1092   case Builtin::BI_setjmp:
1093   case Builtin::BI_setjmpex:
1094     if (checkArgCount(*this, TheCall, 1))
1095       return true;
1096     break;
1097   case Builtin::BI__builtin_classify_type:
1098     if (checkArgCount(*this, TheCall, 1)) return true;
1099     TheCall->setType(Context.IntTy);
1100     break;
1101   case Builtin::BI__builtin_constant_p:
1102     if (checkArgCount(*this, TheCall, 1)) return true;
1103     TheCall->setType(Context.IntTy);
1104     break;
1105   case Builtin::BI__builtin_launder:
1106     return SemaBuiltinLaunder(*this, TheCall);
1107   case Builtin::BI__sync_fetch_and_add:
1108   case Builtin::BI__sync_fetch_and_add_1:
1109   case Builtin::BI__sync_fetch_and_add_2:
1110   case Builtin::BI__sync_fetch_and_add_4:
1111   case Builtin::BI__sync_fetch_and_add_8:
1112   case Builtin::BI__sync_fetch_and_add_16:
1113   case Builtin::BI__sync_fetch_and_sub:
1114   case Builtin::BI__sync_fetch_and_sub_1:
1115   case Builtin::BI__sync_fetch_and_sub_2:
1116   case Builtin::BI__sync_fetch_and_sub_4:
1117   case Builtin::BI__sync_fetch_and_sub_8:
1118   case Builtin::BI__sync_fetch_and_sub_16:
1119   case Builtin::BI__sync_fetch_and_or:
1120   case Builtin::BI__sync_fetch_and_or_1:
1121   case Builtin::BI__sync_fetch_and_or_2:
1122   case Builtin::BI__sync_fetch_and_or_4:
1123   case Builtin::BI__sync_fetch_and_or_8:
1124   case Builtin::BI__sync_fetch_and_or_16:
1125   case Builtin::BI__sync_fetch_and_and:
1126   case Builtin::BI__sync_fetch_and_and_1:
1127   case Builtin::BI__sync_fetch_and_and_2:
1128   case Builtin::BI__sync_fetch_and_and_4:
1129   case Builtin::BI__sync_fetch_and_and_8:
1130   case Builtin::BI__sync_fetch_and_and_16:
1131   case Builtin::BI__sync_fetch_and_xor:
1132   case Builtin::BI__sync_fetch_and_xor_1:
1133   case Builtin::BI__sync_fetch_and_xor_2:
1134   case Builtin::BI__sync_fetch_and_xor_4:
1135   case Builtin::BI__sync_fetch_and_xor_8:
1136   case Builtin::BI__sync_fetch_and_xor_16:
1137   case Builtin::BI__sync_fetch_and_nand:
1138   case Builtin::BI__sync_fetch_and_nand_1:
1139   case Builtin::BI__sync_fetch_and_nand_2:
1140   case Builtin::BI__sync_fetch_and_nand_4:
1141   case Builtin::BI__sync_fetch_and_nand_8:
1142   case Builtin::BI__sync_fetch_and_nand_16:
1143   case Builtin::BI__sync_add_and_fetch:
1144   case Builtin::BI__sync_add_and_fetch_1:
1145   case Builtin::BI__sync_add_and_fetch_2:
1146   case Builtin::BI__sync_add_and_fetch_4:
1147   case Builtin::BI__sync_add_and_fetch_8:
1148   case Builtin::BI__sync_add_and_fetch_16:
1149   case Builtin::BI__sync_sub_and_fetch:
1150   case Builtin::BI__sync_sub_and_fetch_1:
1151   case Builtin::BI__sync_sub_and_fetch_2:
1152   case Builtin::BI__sync_sub_and_fetch_4:
1153   case Builtin::BI__sync_sub_and_fetch_8:
1154   case Builtin::BI__sync_sub_and_fetch_16:
1155   case Builtin::BI__sync_and_and_fetch:
1156   case Builtin::BI__sync_and_and_fetch_1:
1157   case Builtin::BI__sync_and_and_fetch_2:
1158   case Builtin::BI__sync_and_and_fetch_4:
1159   case Builtin::BI__sync_and_and_fetch_8:
1160   case Builtin::BI__sync_and_and_fetch_16:
1161   case Builtin::BI__sync_or_and_fetch:
1162   case Builtin::BI__sync_or_and_fetch_1:
1163   case Builtin::BI__sync_or_and_fetch_2:
1164   case Builtin::BI__sync_or_and_fetch_4:
1165   case Builtin::BI__sync_or_and_fetch_8:
1166   case Builtin::BI__sync_or_and_fetch_16:
1167   case Builtin::BI__sync_xor_and_fetch:
1168   case Builtin::BI__sync_xor_and_fetch_1:
1169   case Builtin::BI__sync_xor_and_fetch_2:
1170   case Builtin::BI__sync_xor_and_fetch_4:
1171   case Builtin::BI__sync_xor_and_fetch_8:
1172   case Builtin::BI__sync_xor_and_fetch_16:
1173   case Builtin::BI__sync_nand_and_fetch:
1174   case Builtin::BI__sync_nand_and_fetch_1:
1175   case Builtin::BI__sync_nand_and_fetch_2:
1176   case Builtin::BI__sync_nand_and_fetch_4:
1177   case Builtin::BI__sync_nand_and_fetch_8:
1178   case Builtin::BI__sync_nand_and_fetch_16:
1179   case Builtin::BI__sync_val_compare_and_swap:
1180   case Builtin::BI__sync_val_compare_and_swap_1:
1181   case Builtin::BI__sync_val_compare_and_swap_2:
1182   case Builtin::BI__sync_val_compare_and_swap_4:
1183   case Builtin::BI__sync_val_compare_and_swap_8:
1184   case Builtin::BI__sync_val_compare_and_swap_16:
1185   case Builtin::BI__sync_bool_compare_and_swap:
1186   case Builtin::BI__sync_bool_compare_and_swap_1:
1187   case Builtin::BI__sync_bool_compare_and_swap_2:
1188   case Builtin::BI__sync_bool_compare_and_swap_4:
1189   case Builtin::BI__sync_bool_compare_and_swap_8:
1190   case Builtin::BI__sync_bool_compare_and_swap_16:
1191   case Builtin::BI__sync_lock_test_and_set:
1192   case Builtin::BI__sync_lock_test_and_set_1:
1193   case Builtin::BI__sync_lock_test_and_set_2:
1194   case Builtin::BI__sync_lock_test_and_set_4:
1195   case Builtin::BI__sync_lock_test_and_set_8:
1196   case Builtin::BI__sync_lock_test_and_set_16:
1197   case Builtin::BI__sync_lock_release:
1198   case Builtin::BI__sync_lock_release_1:
1199   case Builtin::BI__sync_lock_release_2:
1200   case Builtin::BI__sync_lock_release_4:
1201   case Builtin::BI__sync_lock_release_8:
1202   case Builtin::BI__sync_lock_release_16:
1203   case Builtin::BI__sync_swap:
1204   case Builtin::BI__sync_swap_1:
1205   case Builtin::BI__sync_swap_2:
1206   case Builtin::BI__sync_swap_4:
1207   case Builtin::BI__sync_swap_8:
1208   case Builtin::BI__sync_swap_16:
1209     return SemaBuiltinAtomicOverloaded(TheCallResult);
1210   case Builtin::BI__sync_synchronize:
1211     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1212         << TheCall->getCallee()->getSourceRange();
1213     break;
1214   case Builtin::BI__builtin_nontemporal_load:
1215   case Builtin::BI__builtin_nontemporal_store:
1216     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1217 #define BUILTIN(ID, TYPE, ATTRS)
1218 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1219   case Builtin::BI##ID: \
1220     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1221 #include "clang/Basic/Builtins.def"
1222   case Builtin::BI__annotation:
1223     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1224       return ExprError();
1225     break;
1226   case Builtin::BI__builtin_annotation:
1227     if (SemaBuiltinAnnotation(*this, TheCall))
1228       return ExprError();
1229     break;
1230   case Builtin::BI__builtin_addressof:
1231     if (SemaBuiltinAddressof(*this, TheCall))
1232       return ExprError();
1233     break;
1234   case Builtin::BI__builtin_add_overflow:
1235   case Builtin::BI__builtin_sub_overflow:
1236   case Builtin::BI__builtin_mul_overflow:
1237     if (SemaBuiltinOverflow(*this, TheCall))
1238       return ExprError();
1239     break;
1240   case Builtin::BI__builtin_operator_new:
1241   case Builtin::BI__builtin_operator_delete: {
1242     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1243     ExprResult Res =
1244         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1245     if (Res.isInvalid())
1246       CorrectDelayedTyposInExpr(TheCallResult.get());
1247     return Res;
1248   }
1249   case Builtin::BI__builtin_dump_struct: {
1250     // We first want to ensure we are called with 2 arguments
1251     if (checkArgCount(*this, TheCall, 2))
1252       return ExprError();
1253     // Ensure that the first argument is of type 'struct XX *'
1254     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1255     const QualType PtrArgType = PtrArg->getType();
1256     if (!PtrArgType->isPointerType() ||
1257         !PtrArgType->getPointeeType()->isRecordType()) {
1258       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1259           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1260           << "structure pointer";
1261       return ExprError();
1262     }
1263 
1264     // Ensure that the second argument is of type 'FunctionType'
1265     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1266     const QualType FnPtrArgType = FnPtrArg->getType();
1267     if (!FnPtrArgType->isPointerType()) {
1268       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1269           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1270           << FnPtrArgType << "'int (*)(const char *, ...)'";
1271       return ExprError();
1272     }
1273 
1274     const auto *FuncType =
1275         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1276 
1277     if (!FuncType) {
1278       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1279           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1280           << FnPtrArgType << "'int (*)(const char *, ...)'";
1281       return ExprError();
1282     }
1283 
1284     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1285       if (!FT->getNumParams()) {
1286         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1287             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1288             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1289         return ExprError();
1290       }
1291       QualType PT = FT->getParamType(0);
1292       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1293           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1294           !PT->getPointeeType().isConstQualified()) {
1295         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1296             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1297             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1298         return ExprError();
1299       }
1300     }
1301 
1302     TheCall->setType(Context.IntTy);
1303     break;
1304   }
1305 
1306   // check secure string manipulation functions where overflows
1307   // are detectable at compile time
1308   case Builtin::BI__builtin___memcpy_chk:
1309     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
1310     break;
1311   case Builtin::BI__builtin___memmove_chk:
1312     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
1313     break;
1314   case Builtin::BI__builtin___memset_chk:
1315     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
1316     break;
1317   case Builtin::BI__builtin___strlcat_chk:
1318     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
1319     break;
1320   case Builtin::BI__builtin___strlcpy_chk:
1321     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
1322     break;
1323   case Builtin::BI__builtin___strncat_chk:
1324     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
1325     break;
1326   case Builtin::BI__builtin___strncpy_chk:
1327     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
1328     break;
1329   case Builtin::BI__builtin___stpncpy_chk:
1330     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
1331     break;
1332   case Builtin::BI__builtin___memccpy_chk:
1333     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
1334     break;
1335   case Builtin::BI__builtin___snprintf_chk:
1336     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
1337     break;
1338   case Builtin::BI__builtin___vsnprintf_chk:
1339     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
1340     break;
1341   case Builtin::BI__builtin_call_with_static_chain:
1342     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1343       return ExprError();
1344     break;
1345   case Builtin::BI__exception_code:
1346   case Builtin::BI_exception_code:
1347     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1348                                  diag::err_seh___except_block))
1349       return ExprError();
1350     break;
1351   case Builtin::BI__exception_info:
1352   case Builtin::BI_exception_info:
1353     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1354                                  diag::err_seh___except_filter))
1355       return ExprError();
1356     break;
1357   case Builtin::BI__GetExceptionInfo:
1358     if (checkArgCount(*this, TheCall, 1))
1359       return ExprError();
1360 
1361     if (CheckCXXThrowOperand(
1362             TheCall->getBeginLoc(),
1363             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1364             TheCall))
1365       return ExprError();
1366 
1367     TheCall->setType(Context.VoidPtrTy);
1368     break;
1369   // OpenCL v2.0, s6.13.16 - Pipe functions
1370   case Builtin::BIread_pipe:
1371   case Builtin::BIwrite_pipe:
1372     // Since those two functions are declared with var args, we need a semantic
1373     // check for the argument.
1374     if (SemaBuiltinRWPipe(*this, TheCall))
1375       return ExprError();
1376     break;
1377   case Builtin::BIreserve_read_pipe:
1378   case Builtin::BIreserve_write_pipe:
1379   case Builtin::BIwork_group_reserve_read_pipe:
1380   case Builtin::BIwork_group_reserve_write_pipe:
1381     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1382       return ExprError();
1383     break;
1384   case Builtin::BIsub_group_reserve_read_pipe:
1385   case Builtin::BIsub_group_reserve_write_pipe:
1386     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1387         SemaBuiltinReserveRWPipe(*this, TheCall))
1388       return ExprError();
1389     break;
1390   case Builtin::BIcommit_read_pipe:
1391   case Builtin::BIcommit_write_pipe:
1392   case Builtin::BIwork_group_commit_read_pipe:
1393   case Builtin::BIwork_group_commit_write_pipe:
1394     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1395       return ExprError();
1396     break;
1397   case Builtin::BIsub_group_commit_read_pipe:
1398   case Builtin::BIsub_group_commit_write_pipe:
1399     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1400         SemaBuiltinCommitRWPipe(*this, TheCall))
1401       return ExprError();
1402     break;
1403   case Builtin::BIget_pipe_num_packets:
1404   case Builtin::BIget_pipe_max_packets:
1405     if (SemaBuiltinPipePackets(*this, TheCall))
1406       return ExprError();
1407     break;
1408   case Builtin::BIto_global:
1409   case Builtin::BIto_local:
1410   case Builtin::BIto_private:
1411     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1412       return ExprError();
1413     break;
1414   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1415   case Builtin::BIenqueue_kernel:
1416     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1417       return ExprError();
1418     break;
1419   case Builtin::BIget_kernel_work_group_size:
1420   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1421     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1422       return ExprError();
1423     break;
1424   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1425   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1426     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1427       return ExprError();
1428     break;
1429   case Builtin::BI__builtin_os_log_format:
1430   case Builtin::BI__builtin_os_log_format_buffer_size:
1431     if (SemaBuiltinOSLogFormat(TheCall))
1432       return ExprError();
1433     break;
1434   }
1435 
1436   // Since the target specific builtins for each arch overlap, only check those
1437   // of the arch we are compiling for.
1438   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1439     switch (Context.getTargetInfo().getTriple().getArch()) {
1440       case llvm::Triple::arm:
1441       case llvm::Triple::armeb:
1442       case llvm::Triple::thumb:
1443       case llvm::Triple::thumbeb:
1444         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1445           return ExprError();
1446         break;
1447       case llvm::Triple::aarch64:
1448       case llvm::Triple::aarch64_be:
1449         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1450           return ExprError();
1451         break;
1452       case llvm::Triple::hexagon:
1453         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1454           return ExprError();
1455         break;
1456       case llvm::Triple::mips:
1457       case llvm::Triple::mipsel:
1458       case llvm::Triple::mips64:
1459       case llvm::Triple::mips64el:
1460         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1461           return ExprError();
1462         break;
1463       case llvm::Triple::systemz:
1464         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1465           return ExprError();
1466         break;
1467       case llvm::Triple::x86:
1468       case llvm::Triple::x86_64:
1469         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1470           return ExprError();
1471         break;
1472       case llvm::Triple::ppc:
1473       case llvm::Triple::ppc64:
1474       case llvm::Triple::ppc64le:
1475         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1476           return ExprError();
1477         break;
1478       default:
1479         break;
1480     }
1481   }
1482 
1483   return TheCallResult;
1484 }
1485 
1486 // Get the valid immediate range for the specified NEON type code.
1487 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1488   NeonTypeFlags Type(t);
1489   int IsQuad = ForceQuad ? true : Type.isQuad();
1490   switch (Type.getEltType()) {
1491   case NeonTypeFlags::Int8:
1492   case NeonTypeFlags::Poly8:
1493     return shift ? 7 : (8 << IsQuad) - 1;
1494   case NeonTypeFlags::Int16:
1495   case NeonTypeFlags::Poly16:
1496     return shift ? 15 : (4 << IsQuad) - 1;
1497   case NeonTypeFlags::Int32:
1498     return shift ? 31 : (2 << IsQuad) - 1;
1499   case NeonTypeFlags::Int64:
1500   case NeonTypeFlags::Poly64:
1501     return shift ? 63 : (1 << IsQuad) - 1;
1502   case NeonTypeFlags::Poly128:
1503     return shift ? 127 : (1 << IsQuad) - 1;
1504   case NeonTypeFlags::Float16:
1505     assert(!shift && "cannot shift float types!");
1506     return (4 << IsQuad) - 1;
1507   case NeonTypeFlags::Float32:
1508     assert(!shift && "cannot shift float types!");
1509     return (2 << IsQuad) - 1;
1510   case NeonTypeFlags::Float64:
1511     assert(!shift && "cannot shift float types!");
1512     return (1 << IsQuad) - 1;
1513   }
1514   llvm_unreachable("Invalid NeonTypeFlag!");
1515 }
1516 
1517 /// getNeonEltType - Return the QualType corresponding to the elements of
1518 /// the vector type specified by the NeonTypeFlags.  This is used to check
1519 /// the pointer arguments for Neon load/store intrinsics.
1520 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1521                                bool IsPolyUnsigned, bool IsInt64Long) {
1522   switch (Flags.getEltType()) {
1523   case NeonTypeFlags::Int8:
1524     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1525   case NeonTypeFlags::Int16:
1526     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1527   case NeonTypeFlags::Int32:
1528     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1529   case NeonTypeFlags::Int64:
1530     if (IsInt64Long)
1531       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1532     else
1533       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1534                                 : Context.LongLongTy;
1535   case NeonTypeFlags::Poly8:
1536     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1537   case NeonTypeFlags::Poly16:
1538     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1539   case NeonTypeFlags::Poly64:
1540     if (IsInt64Long)
1541       return Context.UnsignedLongTy;
1542     else
1543       return Context.UnsignedLongLongTy;
1544   case NeonTypeFlags::Poly128:
1545     break;
1546   case NeonTypeFlags::Float16:
1547     return Context.HalfTy;
1548   case NeonTypeFlags::Float32:
1549     return Context.FloatTy;
1550   case NeonTypeFlags::Float64:
1551     return Context.DoubleTy;
1552   }
1553   llvm_unreachable("Invalid NeonTypeFlag!");
1554 }
1555 
1556 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1557   llvm::APSInt Result;
1558   uint64_t mask = 0;
1559   unsigned TV = 0;
1560   int PtrArgNum = -1;
1561   bool HasConstPtr = false;
1562   switch (BuiltinID) {
1563 #define GET_NEON_OVERLOAD_CHECK
1564 #include "clang/Basic/arm_neon.inc"
1565 #include "clang/Basic/arm_fp16.inc"
1566 #undef GET_NEON_OVERLOAD_CHECK
1567   }
1568 
1569   // For NEON intrinsics which are overloaded on vector element type, validate
1570   // the immediate which specifies which variant to emit.
1571   unsigned ImmArg = TheCall->getNumArgs()-1;
1572   if (mask) {
1573     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1574       return true;
1575 
1576     TV = Result.getLimitedValue(64);
1577     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1578       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1579              << TheCall->getArg(ImmArg)->getSourceRange();
1580   }
1581 
1582   if (PtrArgNum >= 0) {
1583     // Check that pointer arguments have the specified type.
1584     Expr *Arg = TheCall->getArg(PtrArgNum);
1585     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1586       Arg = ICE->getSubExpr();
1587     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1588     QualType RHSTy = RHS.get()->getType();
1589 
1590     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1591     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1592                           Arch == llvm::Triple::aarch64_be;
1593     bool IsInt64Long =
1594         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1595     QualType EltTy =
1596         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1597     if (HasConstPtr)
1598       EltTy = EltTy.withConst();
1599     QualType LHSTy = Context.getPointerType(EltTy);
1600     AssignConvertType ConvTy;
1601     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1602     if (RHS.isInvalid())
1603       return true;
1604     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1605                                  RHS.get(), AA_Assigning))
1606       return true;
1607   }
1608 
1609   // For NEON intrinsics which take an immediate value as part of the
1610   // instruction, range check them here.
1611   unsigned i = 0, l = 0, u = 0;
1612   switch (BuiltinID) {
1613   default:
1614     return false;
1615   #define GET_NEON_IMMEDIATE_CHECK
1616   #include "clang/Basic/arm_neon.inc"
1617   #include "clang/Basic/arm_fp16.inc"
1618   #undef GET_NEON_IMMEDIATE_CHECK
1619   }
1620 
1621   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1622 }
1623 
1624 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1625                                         unsigned MaxWidth) {
1626   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1627           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1628           BuiltinID == ARM::BI__builtin_arm_strex ||
1629           BuiltinID == ARM::BI__builtin_arm_stlex ||
1630           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1631           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1632           BuiltinID == AArch64::BI__builtin_arm_strex ||
1633           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1634          "unexpected ARM builtin");
1635   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1636                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1637                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1638                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1639 
1640   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1641 
1642   // Ensure that we have the proper number of arguments.
1643   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1644     return true;
1645 
1646   // Inspect the pointer argument of the atomic builtin.  This should always be
1647   // a pointer type, whose element is an integral scalar or pointer type.
1648   // Because it is a pointer type, we don't have to worry about any implicit
1649   // casts here.
1650   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1651   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1652   if (PointerArgRes.isInvalid())
1653     return true;
1654   PointerArg = PointerArgRes.get();
1655 
1656   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1657   if (!pointerType) {
1658     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1659         << PointerArg->getType() << PointerArg->getSourceRange();
1660     return true;
1661   }
1662 
1663   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1664   // task is to insert the appropriate casts into the AST. First work out just
1665   // what the appropriate type is.
1666   QualType ValType = pointerType->getPointeeType();
1667   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1668   if (IsLdrex)
1669     AddrType.addConst();
1670 
1671   // Issue a warning if the cast is dodgy.
1672   CastKind CastNeeded = CK_NoOp;
1673   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1674     CastNeeded = CK_BitCast;
1675     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1676         << PointerArg->getType() << Context.getPointerType(AddrType)
1677         << AA_Passing << PointerArg->getSourceRange();
1678   }
1679 
1680   // Finally, do the cast and replace the argument with the corrected version.
1681   AddrType = Context.getPointerType(AddrType);
1682   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1683   if (PointerArgRes.isInvalid())
1684     return true;
1685   PointerArg = PointerArgRes.get();
1686 
1687   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1688 
1689   // In general, we allow ints, floats and pointers to be loaded and stored.
1690   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1691       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1692     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1693         << PointerArg->getType() << PointerArg->getSourceRange();
1694     return true;
1695   }
1696 
1697   // But ARM doesn't have instructions to deal with 128-bit versions.
1698   if (Context.getTypeSize(ValType) > MaxWidth) {
1699     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1700     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1701         << PointerArg->getType() << PointerArg->getSourceRange();
1702     return true;
1703   }
1704 
1705   switch (ValType.getObjCLifetime()) {
1706   case Qualifiers::OCL_None:
1707   case Qualifiers::OCL_ExplicitNone:
1708     // okay
1709     break;
1710 
1711   case Qualifiers::OCL_Weak:
1712   case Qualifiers::OCL_Strong:
1713   case Qualifiers::OCL_Autoreleasing:
1714     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1715         << ValType << PointerArg->getSourceRange();
1716     return true;
1717   }
1718 
1719   if (IsLdrex) {
1720     TheCall->setType(ValType);
1721     return false;
1722   }
1723 
1724   // Initialize the argument to be stored.
1725   ExprResult ValArg = TheCall->getArg(0);
1726   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1727       Context, ValType, /*consume*/ false);
1728   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1729   if (ValArg.isInvalid())
1730     return true;
1731   TheCall->setArg(0, ValArg.get());
1732 
1733   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1734   // but the custom checker bypasses all default analysis.
1735   TheCall->setType(Context.IntTy);
1736   return false;
1737 }
1738 
1739 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1740   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1741       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1742       BuiltinID == ARM::BI__builtin_arm_strex ||
1743       BuiltinID == ARM::BI__builtin_arm_stlex) {
1744     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1745   }
1746 
1747   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1748     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1749       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1750   }
1751 
1752   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1753       BuiltinID == ARM::BI__builtin_arm_wsr64)
1754     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1755 
1756   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1757       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1758       BuiltinID == ARM::BI__builtin_arm_wsr ||
1759       BuiltinID == ARM::BI__builtin_arm_wsrp)
1760     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1761 
1762   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1763     return true;
1764 
1765   // For intrinsics which take an immediate value as part of the instruction,
1766   // range check them here.
1767   // FIXME: VFP Intrinsics should error if VFP not present.
1768   switch (BuiltinID) {
1769   default: return false;
1770   case ARM::BI__builtin_arm_ssat:
1771     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1772   case ARM::BI__builtin_arm_usat:
1773     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1774   case ARM::BI__builtin_arm_ssat16:
1775     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1776   case ARM::BI__builtin_arm_usat16:
1777     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1778   case ARM::BI__builtin_arm_vcvtr_f:
1779   case ARM::BI__builtin_arm_vcvtr_d:
1780     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1781   case ARM::BI__builtin_arm_dmb:
1782   case ARM::BI__builtin_arm_dsb:
1783   case ARM::BI__builtin_arm_isb:
1784   case ARM::BI__builtin_arm_dbg:
1785     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1786   }
1787 }
1788 
1789 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1790                                          CallExpr *TheCall) {
1791   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1792       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1793       BuiltinID == AArch64::BI__builtin_arm_strex ||
1794       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1795     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1796   }
1797 
1798   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1799     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1800       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1801       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1802       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1803   }
1804 
1805   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1806       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1807     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1808 
1809   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1810       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1811       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1812       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1813     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1814 
1815   // Only check the valid encoding range. Any constant in this range would be
1816   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1817   // an exception for incorrect registers. This matches MSVC behavior.
1818   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1819       BuiltinID == AArch64::BI_WriteStatusReg)
1820     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1821 
1822   if (BuiltinID == AArch64::BI__getReg)
1823     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1824 
1825   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1826     return true;
1827 
1828   // For intrinsics which take an immediate value as part of the instruction,
1829   // range check them here.
1830   unsigned i = 0, l = 0, u = 0;
1831   switch (BuiltinID) {
1832   default: return false;
1833   case AArch64::BI__builtin_arm_dmb:
1834   case AArch64::BI__builtin_arm_dsb:
1835   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1836   }
1837 
1838   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1839 }
1840 
1841 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1842   struct BuiltinAndString {
1843     unsigned BuiltinID;
1844     const char *Str;
1845   };
1846 
1847   static BuiltinAndString ValidCPU[] = {
1848     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1849     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1850     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1851     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1852     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1853     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1854     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1855     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1856     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1857     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1858     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1859     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1860     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1861     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1862     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1863     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1864     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1865     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1866     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1867     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1868     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1869     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1870     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1871   };
1872 
1873   static BuiltinAndString ValidHVX[] = {
1874     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1875     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1876     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1877     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1878     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1879     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1880     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1881     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1882     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1883     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1884     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1885     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1886     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1887     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1888     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1889     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1890     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1891     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1892     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1893     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1894     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1895     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1896     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1897     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1898     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1899     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1900     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1901     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1902     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1903     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1904     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1905     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1906     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1907     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1908     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1909     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1910     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1911     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1912     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1913     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1914     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1915     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1916     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1917     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1918     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1919     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1920     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1921     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1922     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1923     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1924     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
1925     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
1926     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
1927     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
1928     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
1929     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
1930     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
1931     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
1932     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
1933     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
1934     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
1935     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
1936     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
1937     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
1938     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
1939     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
1940     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
1941     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
1942     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
1943     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
1944     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
1945     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
1946     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
1947     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
1948     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
1949     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
1950     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
1951     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
1952     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
1953     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
1954     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
1955     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
1958     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
1970     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2606   };
2607 
2608   // Sort the tables on first execution so we can binary search them.
2609   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2610     return LHS.BuiltinID < RHS.BuiltinID;
2611   };
2612   static const bool SortOnce =
2613       (llvm::sort(ValidCPU, SortCmp),
2614        llvm::sort(ValidHVX, SortCmp), true);
2615   (void)SortOnce;
2616   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2617     return BI.BuiltinID < BuiltinID;
2618   };
2619 
2620   const TargetInfo &TI = Context.getTargetInfo();
2621 
2622   const BuiltinAndString *FC =
2623       std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2624                        LowerBoundCmp);
2625   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2626     const TargetOptions &Opts = TI.getTargetOpts();
2627     StringRef CPU = Opts.CPU;
2628     if (!CPU.empty()) {
2629       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2630       CPU.consume_front("hexagon");
2631       SmallVector<StringRef, 3> CPUs;
2632       StringRef(FC->Str).split(CPUs, ',');
2633       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2634         return Diag(TheCall->getBeginLoc(),
2635                     diag::err_hexagon_builtin_unsupported_cpu);
2636     }
2637   }
2638 
2639   const BuiltinAndString *FH =
2640       std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2641                        LowerBoundCmp);
2642   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2643     if (!TI.hasFeature("hvx"))
2644       return Diag(TheCall->getBeginLoc(),
2645                   diag::err_hexagon_builtin_requires_hvx);
2646 
2647     SmallVector<StringRef, 3> HVXs;
2648     StringRef(FH->Str).split(HVXs, ',');
2649     bool IsValid = llvm::any_of(HVXs,
2650                                 [&TI] (StringRef V) {
2651                                   std::string F = "hvx" + V.str();
2652                                   return TI.hasFeature(F);
2653                                 });
2654     if (!IsValid)
2655       return Diag(TheCall->getBeginLoc(),
2656                   diag::err_hexagon_builtin_unsupported_hvx);
2657   }
2658 
2659   return false;
2660 }
2661 
2662 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2663   struct ArgInfo {
2664     uint8_t OpNum;
2665     bool IsSigned;
2666     uint8_t BitWidth;
2667     uint8_t Align;
2668   };
2669   struct BuiltinInfo {
2670     unsigned BuiltinID;
2671     ArgInfo Infos[2];
2672   };
2673 
2674   static BuiltinInfo Infos[] = {
2675     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2676     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2677     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2678     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2679     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2680     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2681     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2682     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2683     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2684     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2685     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2686 
2687     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2690     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2691     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2692     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2698 
2699     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2743     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2744     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2746     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2749     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2751                                                       {{ 1, false, 6,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2759                                                       {{ 1, false, 5,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2766                                                        { 2, false, 5,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2768                                                        { 2, false, 6,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2770                                                        { 3, false, 5,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2772                                                        { 3, false, 6,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2789                                                       {{ 2, false, 4,  0 },
2790                                                        { 3, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2792                                                       {{ 2, false, 4,  0 },
2793                                                        { 3, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2795                                                       {{ 2, false, 4,  0 },
2796                                                        { 3, false, 5,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2798                                                       {{ 2, false, 4,  0 },
2799                                                        { 3, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2811                                                        { 2, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2813                                                        { 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2823                                                       {{ 1, false, 4,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2826                                                       {{ 1, false, 4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2847                                                       {{ 3, false, 1,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2852                                                       {{ 3, false, 1,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2857                                                       {{ 3, false, 1,  0 }} },
2858   };
2859 
2860   // Use a dynamically initialized static to sort the table exactly once on
2861   // first run.
2862   static const bool SortOnce =
2863       (llvm::sort(Infos,
2864                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2865                    return LHS.BuiltinID < RHS.BuiltinID;
2866                  }),
2867        true);
2868   (void)SortOnce;
2869 
2870   const BuiltinInfo *F =
2871       std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2872                        [](const BuiltinInfo &BI, unsigned BuiltinID) {
2873                          return BI.BuiltinID < BuiltinID;
2874                        });
2875   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2876     return false;
2877 
2878   bool Error = false;
2879 
2880   for (const ArgInfo &A : F->Infos) {
2881     // Ignore empty ArgInfo elements.
2882     if (A.BitWidth == 0)
2883       continue;
2884 
2885     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2886     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2887     if (!A.Align) {
2888       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2889     } else {
2890       unsigned M = 1 << A.Align;
2891       Min *= M;
2892       Max *= M;
2893       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2894                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2895     }
2896   }
2897   return Error;
2898 }
2899 
2900 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2901                                            CallExpr *TheCall) {
2902   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2903          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2904 }
2905 
2906 
2907 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2908 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2909 // ordering for DSP is unspecified. MSA is ordered by the data format used
2910 // by the underlying instruction i.e., df/m, df/n and then by size.
2911 //
2912 // FIXME: The size tests here should instead be tablegen'd along with the
2913 //        definitions from include/clang/Basic/BuiltinsMips.def.
2914 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2915 //        be too.
2916 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2917   unsigned i = 0, l = 0, u = 0, m = 0;
2918   switch (BuiltinID) {
2919   default: return false;
2920   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2921   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2922   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2923   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2924   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2925   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2926   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2927   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2928   // df/m field.
2929   // These intrinsics take an unsigned 3 bit immediate.
2930   case Mips::BI__builtin_msa_bclri_b:
2931   case Mips::BI__builtin_msa_bnegi_b:
2932   case Mips::BI__builtin_msa_bseti_b:
2933   case Mips::BI__builtin_msa_sat_s_b:
2934   case Mips::BI__builtin_msa_sat_u_b:
2935   case Mips::BI__builtin_msa_slli_b:
2936   case Mips::BI__builtin_msa_srai_b:
2937   case Mips::BI__builtin_msa_srari_b:
2938   case Mips::BI__builtin_msa_srli_b:
2939   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2940   case Mips::BI__builtin_msa_binsli_b:
2941   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2942   // These intrinsics take an unsigned 4 bit immediate.
2943   case Mips::BI__builtin_msa_bclri_h:
2944   case Mips::BI__builtin_msa_bnegi_h:
2945   case Mips::BI__builtin_msa_bseti_h:
2946   case Mips::BI__builtin_msa_sat_s_h:
2947   case Mips::BI__builtin_msa_sat_u_h:
2948   case Mips::BI__builtin_msa_slli_h:
2949   case Mips::BI__builtin_msa_srai_h:
2950   case Mips::BI__builtin_msa_srari_h:
2951   case Mips::BI__builtin_msa_srli_h:
2952   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2953   case Mips::BI__builtin_msa_binsli_h:
2954   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2955   // These intrinsics take an unsigned 5 bit immediate.
2956   // The first block of intrinsics actually have an unsigned 5 bit field,
2957   // not a df/n field.
2958   case Mips::BI__builtin_msa_clei_u_b:
2959   case Mips::BI__builtin_msa_clei_u_h:
2960   case Mips::BI__builtin_msa_clei_u_w:
2961   case Mips::BI__builtin_msa_clei_u_d:
2962   case Mips::BI__builtin_msa_clti_u_b:
2963   case Mips::BI__builtin_msa_clti_u_h:
2964   case Mips::BI__builtin_msa_clti_u_w:
2965   case Mips::BI__builtin_msa_clti_u_d:
2966   case Mips::BI__builtin_msa_maxi_u_b:
2967   case Mips::BI__builtin_msa_maxi_u_h:
2968   case Mips::BI__builtin_msa_maxi_u_w:
2969   case Mips::BI__builtin_msa_maxi_u_d:
2970   case Mips::BI__builtin_msa_mini_u_b:
2971   case Mips::BI__builtin_msa_mini_u_h:
2972   case Mips::BI__builtin_msa_mini_u_w:
2973   case Mips::BI__builtin_msa_mini_u_d:
2974   case Mips::BI__builtin_msa_addvi_b:
2975   case Mips::BI__builtin_msa_addvi_h:
2976   case Mips::BI__builtin_msa_addvi_w:
2977   case Mips::BI__builtin_msa_addvi_d:
2978   case Mips::BI__builtin_msa_bclri_w:
2979   case Mips::BI__builtin_msa_bnegi_w:
2980   case Mips::BI__builtin_msa_bseti_w:
2981   case Mips::BI__builtin_msa_sat_s_w:
2982   case Mips::BI__builtin_msa_sat_u_w:
2983   case Mips::BI__builtin_msa_slli_w:
2984   case Mips::BI__builtin_msa_srai_w:
2985   case Mips::BI__builtin_msa_srari_w:
2986   case Mips::BI__builtin_msa_srli_w:
2987   case Mips::BI__builtin_msa_srlri_w:
2988   case Mips::BI__builtin_msa_subvi_b:
2989   case Mips::BI__builtin_msa_subvi_h:
2990   case Mips::BI__builtin_msa_subvi_w:
2991   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2992   case Mips::BI__builtin_msa_binsli_w:
2993   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2994   // These intrinsics take an unsigned 6 bit immediate.
2995   case Mips::BI__builtin_msa_bclri_d:
2996   case Mips::BI__builtin_msa_bnegi_d:
2997   case Mips::BI__builtin_msa_bseti_d:
2998   case Mips::BI__builtin_msa_sat_s_d:
2999   case Mips::BI__builtin_msa_sat_u_d:
3000   case Mips::BI__builtin_msa_slli_d:
3001   case Mips::BI__builtin_msa_srai_d:
3002   case Mips::BI__builtin_msa_srari_d:
3003   case Mips::BI__builtin_msa_srli_d:
3004   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3005   case Mips::BI__builtin_msa_binsli_d:
3006   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3007   // These intrinsics take a signed 5 bit immediate.
3008   case Mips::BI__builtin_msa_ceqi_b:
3009   case Mips::BI__builtin_msa_ceqi_h:
3010   case Mips::BI__builtin_msa_ceqi_w:
3011   case Mips::BI__builtin_msa_ceqi_d:
3012   case Mips::BI__builtin_msa_clti_s_b:
3013   case Mips::BI__builtin_msa_clti_s_h:
3014   case Mips::BI__builtin_msa_clti_s_w:
3015   case Mips::BI__builtin_msa_clti_s_d:
3016   case Mips::BI__builtin_msa_clei_s_b:
3017   case Mips::BI__builtin_msa_clei_s_h:
3018   case Mips::BI__builtin_msa_clei_s_w:
3019   case Mips::BI__builtin_msa_clei_s_d:
3020   case Mips::BI__builtin_msa_maxi_s_b:
3021   case Mips::BI__builtin_msa_maxi_s_h:
3022   case Mips::BI__builtin_msa_maxi_s_w:
3023   case Mips::BI__builtin_msa_maxi_s_d:
3024   case Mips::BI__builtin_msa_mini_s_b:
3025   case Mips::BI__builtin_msa_mini_s_h:
3026   case Mips::BI__builtin_msa_mini_s_w:
3027   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3028   // These intrinsics take an unsigned 8 bit immediate.
3029   case Mips::BI__builtin_msa_andi_b:
3030   case Mips::BI__builtin_msa_nori_b:
3031   case Mips::BI__builtin_msa_ori_b:
3032   case Mips::BI__builtin_msa_shf_b:
3033   case Mips::BI__builtin_msa_shf_h:
3034   case Mips::BI__builtin_msa_shf_w:
3035   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3036   case Mips::BI__builtin_msa_bseli_b:
3037   case Mips::BI__builtin_msa_bmnzi_b:
3038   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3039   // df/n format
3040   // These intrinsics take an unsigned 4 bit immediate.
3041   case Mips::BI__builtin_msa_copy_s_b:
3042   case Mips::BI__builtin_msa_copy_u_b:
3043   case Mips::BI__builtin_msa_insve_b:
3044   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3045   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3046   // These intrinsics take an unsigned 3 bit immediate.
3047   case Mips::BI__builtin_msa_copy_s_h:
3048   case Mips::BI__builtin_msa_copy_u_h:
3049   case Mips::BI__builtin_msa_insve_h:
3050   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3051   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3052   // These intrinsics take an unsigned 2 bit immediate.
3053   case Mips::BI__builtin_msa_copy_s_w:
3054   case Mips::BI__builtin_msa_copy_u_w:
3055   case Mips::BI__builtin_msa_insve_w:
3056   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3057   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3058   // These intrinsics take an unsigned 1 bit immediate.
3059   case Mips::BI__builtin_msa_copy_s_d:
3060   case Mips::BI__builtin_msa_copy_u_d:
3061   case Mips::BI__builtin_msa_insve_d:
3062   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3063   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3064   // Memory offsets and immediate loads.
3065   // These intrinsics take a signed 10 bit immediate.
3066   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3067   case Mips::BI__builtin_msa_ldi_h:
3068   case Mips::BI__builtin_msa_ldi_w:
3069   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3070   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3071   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3072   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3073   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3074   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3075   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3076   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3077   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3078   }
3079 
3080   if (!m)
3081     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3082 
3083   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3084          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3085 }
3086 
3087 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3088   unsigned i = 0, l = 0, u = 0;
3089   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3090                       BuiltinID == PPC::BI__builtin_divdeu ||
3091                       BuiltinID == PPC::BI__builtin_bpermd;
3092   bool IsTarget64Bit = Context.getTargetInfo()
3093                               .getTypeWidth(Context
3094                                             .getTargetInfo()
3095                                             .getIntPtrType()) == 64;
3096   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3097                        BuiltinID == PPC::BI__builtin_divweu ||
3098                        BuiltinID == PPC::BI__builtin_divde ||
3099                        BuiltinID == PPC::BI__builtin_divdeu;
3100 
3101   if (Is64BitBltin && !IsTarget64Bit)
3102     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3103            << TheCall->getSourceRange();
3104 
3105   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3106       (BuiltinID == PPC::BI__builtin_bpermd &&
3107        !Context.getTargetInfo().hasFeature("bpermd")))
3108     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3109            << TheCall->getSourceRange();
3110 
3111   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3112     if (!Context.getTargetInfo().hasFeature("vsx"))
3113       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3114              << TheCall->getSourceRange();
3115     return false;
3116   };
3117 
3118   switch (BuiltinID) {
3119   default: return false;
3120   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3121   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3122     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3123            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3124   case PPC::BI__builtin_tbegin:
3125   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3126   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3127   case PPC::BI__builtin_tabortwc:
3128   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3129   case PPC::BI__builtin_tabortwci:
3130   case PPC::BI__builtin_tabortdci:
3131     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3132            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3133   case PPC::BI__builtin_vsx_xxpermdi:
3134   case PPC::BI__builtin_vsx_xxsldwi:
3135     return SemaBuiltinVSX(TheCall);
3136   case PPC::BI__builtin_unpack_vector_int128:
3137     return SemaVSXCheck(TheCall) ||
3138            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3139   case PPC::BI__builtin_pack_vector_int128:
3140     return SemaVSXCheck(TheCall);
3141   }
3142   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3143 }
3144 
3145 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3146                                            CallExpr *TheCall) {
3147   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3148     Expr *Arg = TheCall->getArg(0);
3149     llvm::APSInt AbortCode(32);
3150     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3151         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3152       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3153              << Arg->getSourceRange();
3154   }
3155 
3156   // For intrinsics which take an immediate value as part of the instruction,
3157   // range check them here.
3158   unsigned i = 0, l = 0, u = 0;
3159   switch (BuiltinID) {
3160   default: return false;
3161   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3162   case SystemZ::BI__builtin_s390_verimb:
3163   case SystemZ::BI__builtin_s390_verimh:
3164   case SystemZ::BI__builtin_s390_verimf:
3165   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3166   case SystemZ::BI__builtin_s390_vfaeb:
3167   case SystemZ::BI__builtin_s390_vfaeh:
3168   case SystemZ::BI__builtin_s390_vfaef:
3169   case SystemZ::BI__builtin_s390_vfaebs:
3170   case SystemZ::BI__builtin_s390_vfaehs:
3171   case SystemZ::BI__builtin_s390_vfaefs:
3172   case SystemZ::BI__builtin_s390_vfaezb:
3173   case SystemZ::BI__builtin_s390_vfaezh:
3174   case SystemZ::BI__builtin_s390_vfaezf:
3175   case SystemZ::BI__builtin_s390_vfaezbs:
3176   case SystemZ::BI__builtin_s390_vfaezhs:
3177   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3178   case SystemZ::BI__builtin_s390_vfisb:
3179   case SystemZ::BI__builtin_s390_vfidb:
3180     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3181            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3182   case SystemZ::BI__builtin_s390_vftcisb:
3183   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3184   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3185   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3186   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3187   case SystemZ::BI__builtin_s390_vstrcb:
3188   case SystemZ::BI__builtin_s390_vstrch:
3189   case SystemZ::BI__builtin_s390_vstrcf:
3190   case SystemZ::BI__builtin_s390_vstrczb:
3191   case SystemZ::BI__builtin_s390_vstrczh:
3192   case SystemZ::BI__builtin_s390_vstrczf:
3193   case SystemZ::BI__builtin_s390_vstrcbs:
3194   case SystemZ::BI__builtin_s390_vstrchs:
3195   case SystemZ::BI__builtin_s390_vstrcfs:
3196   case SystemZ::BI__builtin_s390_vstrczbs:
3197   case SystemZ::BI__builtin_s390_vstrczhs:
3198   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3199   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3200   case SystemZ::BI__builtin_s390_vfminsb:
3201   case SystemZ::BI__builtin_s390_vfmaxsb:
3202   case SystemZ::BI__builtin_s390_vfmindb:
3203   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3204   }
3205   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3206 }
3207 
3208 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3209 /// This checks that the target supports __builtin_cpu_supports and
3210 /// that the string argument is constant and valid.
3211 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3212   Expr *Arg = TheCall->getArg(0);
3213 
3214   // Check if the argument is a string literal.
3215   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3216     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3217            << Arg->getSourceRange();
3218 
3219   // Check the contents of the string.
3220   StringRef Feature =
3221       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3222   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3223     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3224            << Arg->getSourceRange();
3225   return false;
3226 }
3227 
3228 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3229 /// This checks that the target supports __builtin_cpu_is and
3230 /// that the string argument is constant and valid.
3231 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3232   Expr *Arg = TheCall->getArg(0);
3233 
3234   // Check if the argument is a string literal.
3235   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3236     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3237            << Arg->getSourceRange();
3238 
3239   // Check the contents of the string.
3240   StringRef Feature =
3241       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3242   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3243     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3244            << Arg->getSourceRange();
3245   return false;
3246 }
3247 
3248 // Check if the rounding mode is legal.
3249 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3250   // Indicates if this instruction has rounding control or just SAE.
3251   bool HasRC = false;
3252 
3253   unsigned ArgNum = 0;
3254   switch (BuiltinID) {
3255   default:
3256     return false;
3257   case X86::BI__builtin_ia32_vcvttsd2si32:
3258   case X86::BI__builtin_ia32_vcvttsd2si64:
3259   case X86::BI__builtin_ia32_vcvttsd2usi32:
3260   case X86::BI__builtin_ia32_vcvttsd2usi64:
3261   case X86::BI__builtin_ia32_vcvttss2si32:
3262   case X86::BI__builtin_ia32_vcvttss2si64:
3263   case X86::BI__builtin_ia32_vcvttss2usi32:
3264   case X86::BI__builtin_ia32_vcvttss2usi64:
3265     ArgNum = 1;
3266     break;
3267   case X86::BI__builtin_ia32_maxpd512:
3268   case X86::BI__builtin_ia32_maxps512:
3269   case X86::BI__builtin_ia32_minpd512:
3270   case X86::BI__builtin_ia32_minps512:
3271     ArgNum = 2;
3272     break;
3273   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3274   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3275   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3276   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3277   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3278   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3279   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3280   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3281   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3282   case X86::BI__builtin_ia32_exp2pd_mask:
3283   case X86::BI__builtin_ia32_exp2ps_mask:
3284   case X86::BI__builtin_ia32_getexppd512_mask:
3285   case X86::BI__builtin_ia32_getexpps512_mask:
3286   case X86::BI__builtin_ia32_rcp28pd_mask:
3287   case X86::BI__builtin_ia32_rcp28ps_mask:
3288   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3289   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3290   case X86::BI__builtin_ia32_vcomisd:
3291   case X86::BI__builtin_ia32_vcomiss:
3292   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3293     ArgNum = 3;
3294     break;
3295   case X86::BI__builtin_ia32_cmppd512_mask:
3296   case X86::BI__builtin_ia32_cmpps512_mask:
3297   case X86::BI__builtin_ia32_cmpsd_mask:
3298   case X86::BI__builtin_ia32_cmpss_mask:
3299   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3300   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3301   case X86::BI__builtin_ia32_getexpss128_round_mask:
3302   case X86::BI__builtin_ia32_maxsd_round_mask:
3303   case X86::BI__builtin_ia32_maxss_round_mask:
3304   case X86::BI__builtin_ia32_minsd_round_mask:
3305   case X86::BI__builtin_ia32_minss_round_mask:
3306   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3307   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3308   case X86::BI__builtin_ia32_reducepd512_mask:
3309   case X86::BI__builtin_ia32_reduceps512_mask:
3310   case X86::BI__builtin_ia32_rndscalepd_mask:
3311   case X86::BI__builtin_ia32_rndscaleps_mask:
3312   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3313   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3314     ArgNum = 4;
3315     break;
3316   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3317   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3318   case X86::BI__builtin_ia32_fixupimmps512_mask:
3319   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3320   case X86::BI__builtin_ia32_fixupimmsd_mask:
3321   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3322   case X86::BI__builtin_ia32_fixupimmss_mask:
3323   case X86::BI__builtin_ia32_fixupimmss_maskz:
3324   case X86::BI__builtin_ia32_rangepd512_mask:
3325   case X86::BI__builtin_ia32_rangeps512_mask:
3326   case X86::BI__builtin_ia32_rangesd128_round_mask:
3327   case X86::BI__builtin_ia32_rangess128_round_mask:
3328   case X86::BI__builtin_ia32_reducesd_mask:
3329   case X86::BI__builtin_ia32_reducess_mask:
3330   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3331   case X86::BI__builtin_ia32_rndscaless_round_mask:
3332     ArgNum = 5;
3333     break;
3334   case X86::BI__builtin_ia32_vcvtsd2si64:
3335   case X86::BI__builtin_ia32_vcvtsd2si32:
3336   case X86::BI__builtin_ia32_vcvtsd2usi32:
3337   case X86::BI__builtin_ia32_vcvtsd2usi64:
3338   case X86::BI__builtin_ia32_vcvtss2si32:
3339   case X86::BI__builtin_ia32_vcvtss2si64:
3340   case X86::BI__builtin_ia32_vcvtss2usi32:
3341   case X86::BI__builtin_ia32_vcvtss2usi64:
3342   case X86::BI__builtin_ia32_sqrtpd512:
3343   case X86::BI__builtin_ia32_sqrtps512:
3344     ArgNum = 1;
3345     HasRC = true;
3346     break;
3347   case X86::BI__builtin_ia32_addpd512:
3348   case X86::BI__builtin_ia32_addps512:
3349   case X86::BI__builtin_ia32_divpd512:
3350   case X86::BI__builtin_ia32_divps512:
3351   case X86::BI__builtin_ia32_mulpd512:
3352   case X86::BI__builtin_ia32_mulps512:
3353   case X86::BI__builtin_ia32_subpd512:
3354   case X86::BI__builtin_ia32_subps512:
3355   case X86::BI__builtin_ia32_cvtsi2sd64:
3356   case X86::BI__builtin_ia32_cvtsi2ss32:
3357   case X86::BI__builtin_ia32_cvtsi2ss64:
3358   case X86::BI__builtin_ia32_cvtusi2sd64:
3359   case X86::BI__builtin_ia32_cvtusi2ss32:
3360   case X86::BI__builtin_ia32_cvtusi2ss64:
3361     ArgNum = 2;
3362     HasRC = true;
3363     break;
3364   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3365   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3366   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3367   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3368   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3369   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3370   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3371   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3372   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3373   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3374   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3375     ArgNum = 3;
3376     HasRC = true;
3377     break;
3378   case X86::BI__builtin_ia32_addss_round_mask:
3379   case X86::BI__builtin_ia32_addsd_round_mask:
3380   case X86::BI__builtin_ia32_divss_round_mask:
3381   case X86::BI__builtin_ia32_divsd_round_mask:
3382   case X86::BI__builtin_ia32_mulss_round_mask:
3383   case X86::BI__builtin_ia32_mulsd_round_mask:
3384   case X86::BI__builtin_ia32_subss_round_mask:
3385   case X86::BI__builtin_ia32_subsd_round_mask:
3386   case X86::BI__builtin_ia32_scalefpd512_mask:
3387   case X86::BI__builtin_ia32_scalefps512_mask:
3388   case X86::BI__builtin_ia32_scalefsd_round_mask:
3389   case X86::BI__builtin_ia32_scalefss_round_mask:
3390   case X86::BI__builtin_ia32_getmantpd512_mask:
3391   case X86::BI__builtin_ia32_getmantps512_mask:
3392   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3393   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3394   case X86::BI__builtin_ia32_sqrtss_round_mask:
3395   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3396   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3397   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3398   case X86::BI__builtin_ia32_vfmaddss3_mask:
3399   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3400   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3401   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3402   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3403   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3404   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3405   case X86::BI__builtin_ia32_vfmaddps512_mask:
3406   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3407   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3408   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3409   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3410   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3411   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3412   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3413   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3414   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3415   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3416   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3417     ArgNum = 4;
3418     HasRC = true;
3419     break;
3420   case X86::BI__builtin_ia32_getmantsd_round_mask:
3421   case X86::BI__builtin_ia32_getmantss_round_mask:
3422     ArgNum = 5;
3423     HasRC = true;
3424     break;
3425   }
3426 
3427   llvm::APSInt Result;
3428 
3429   // We can't check the value of a dependent argument.
3430   Expr *Arg = TheCall->getArg(ArgNum);
3431   if (Arg->isTypeDependent() || Arg->isValueDependent())
3432     return false;
3433 
3434   // Check constant-ness first.
3435   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3436     return true;
3437 
3438   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3439   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3440   // combined with ROUND_NO_EXC.
3441   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3442       Result == 8/*ROUND_NO_EXC*/ ||
3443       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3444     return false;
3445 
3446   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3447          << Arg->getSourceRange();
3448 }
3449 
3450 // Check if the gather/scatter scale is legal.
3451 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3452                                              CallExpr *TheCall) {
3453   unsigned ArgNum = 0;
3454   switch (BuiltinID) {
3455   default:
3456     return false;
3457   case X86::BI__builtin_ia32_gatherpfdpd:
3458   case X86::BI__builtin_ia32_gatherpfdps:
3459   case X86::BI__builtin_ia32_gatherpfqpd:
3460   case X86::BI__builtin_ia32_gatherpfqps:
3461   case X86::BI__builtin_ia32_scatterpfdpd:
3462   case X86::BI__builtin_ia32_scatterpfdps:
3463   case X86::BI__builtin_ia32_scatterpfqpd:
3464   case X86::BI__builtin_ia32_scatterpfqps:
3465     ArgNum = 3;
3466     break;
3467   case X86::BI__builtin_ia32_gatherd_pd:
3468   case X86::BI__builtin_ia32_gatherd_pd256:
3469   case X86::BI__builtin_ia32_gatherq_pd:
3470   case X86::BI__builtin_ia32_gatherq_pd256:
3471   case X86::BI__builtin_ia32_gatherd_ps:
3472   case X86::BI__builtin_ia32_gatherd_ps256:
3473   case X86::BI__builtin_ia32_gatherq_ps:
3474   case X86::BI__builtin_ia32_gatherq_ps256:
3475   case X86::BI__builtin_ia32_gatherd_q:
3476   case X86::BI__builtin_ia32_gatherd_q256:
3477   case X86::BI__builtin_ia32_gatherq_q:
3478   case X86::BI__builtin_ia32_gatherq_q256:
3479   case X86::BI__builtin_ia32_gatherd_d:
3480   case X86::BI__builtin_ia32_gatherd_d256:
3481   case X86::BI__builtin_ia32_gatherq_d:
3482   case X86::BI__builtin_ia32_gatherq_d256:
3483   case X86::BI__builtin_ia32_gather3div2df:
3484   case X86::BI__builtin_ia32_gather3div2di:
3485   case X86::BI__builtin_ia32_gather3div4df:
3486   case X86::BI__builtin_ia32_gather3div4di:
3487   case X86::BI__builtin_ia32_gather3div4sf:
3488   case X86::BI__builtin_ia32_gather3div4si:
3489   case X86::BI__builtin_ia32_gather3div8sf:
3490   case X86::BI__builtin_ia32_gather3div8si:
3491   case X86::BI__builtin_ia32_gather3siv2df:
3492   case X86::BI__builtin_ia32_gather3siv2di:
3493   case X86::BI__builtin_ia32_gather3siv4df:
3494   case X86::BI__builtin_ia32_gather3siv4di:
3495   case X86::BI__builtin_ia32_gather3siv4sf:
3496   case X86::BI__builtin_ia32_gather3siv4si:
3497   case X86::BI__builtin_ia32_gather3siv8sf:
3498   case X86::BI__builtin_ia32_gather3siv8si:
3499   case X86::BI__builtin_ia32_gathersiv8df:
3500   case X86::BI__builtin_ia32_gathersiv16sf:
3501   case X86::BI__builtin_ia32_gatherdiv8df:
3502   case X86::BI__builtin_ia32_gatherdiv16sf:
3503   case X86::BI__builtin_ia32_gathersiv8di:
3504   case X86::BI__builtin_ia32_gathersiv16si:
3505   case X86::BI__builtin_ia32_gatherdiv8di:
3506   case X86::BI__builtin_ia32_gatherdiv16si:
3507   case X86::BI__builtin_ia32_scatterdiv2df:
3508   case X86::BI__builtin_ia32_scatterdiv2di:
3509   case X86::BI__builtin_ia32_scatterdiv4df:
3510   case X86::BI__builtin_ia32_scatterdiv4di:
3511   case X86::BI__builtin_ia32_scatterdiv4sf:
3512   case X86::BI__builtin_ia32_scatterdiv4si:
3513   case X86::BI__builtin_ia32_scatterdiv8sf:
3514   case X86::BI__builtin_ia32_scatterdiv8si:
3515   case X86::BI__builtin_ia32_scattersiv2df:
3516   case X86::BI__builtin_ia32_scattersiv2di:
3517   case X86::BI__builtin_ia32_scattersiv4df:
3518   case X86::BI__builtin_ia32_scattersiv4di:
3519   case X86::BI__builtin_ia32_scattersiv4sf:
3520   case X86::BI__builtin_ia32_scattersiv4si:
3521   case X86::BI__builtin_ia32_scattersiv8sf:
3522   case X86::BI__builtin_ia32_scattersiv8si:
3523   case X86::BI__builtin_ia32_scattersiv8df:
3524   case X86::BI__builtin_ia32_scattersiv16sf:
3525   case X86::BI__builtin_ia32_scatterdiv8df:
3526   case X86::BI__builtin_ia32_scatterdiv16sf:
3527   case X86::BI__builtin_ia32_scattersiv8di:
3528   case X86::BI__builtin_ia32_scattersiv16si:
3529   case X86::BI__builtin_ia32_scatterdiv8di:
3530   case X86::BI__builtin_ia32_scatterdiv16si:
3531     ArgNum = 4;
3532     break;
3533   }
3534 
3535   llvm::APSInt Result;
3536 
3537   // We can't check the value of a dependent argument.
3538   Expr *Arg = TheCall->getArg(ArgNum);
3539   if (Arg->isTypeDependent() || Arg->isValueDependent())
3540     return false;
3541 
3542   // Check constant-ness first.
3543   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3544     return true;
3545 
3546   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3547     return false;
3548 
3549   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3550          << Arg->getSourceRange();
3551 }
3552 
3553 static bool isX86_32Builtin(unsigned BuiltinID) {
3554   // These builtins only work on x86-32 targets.
3555   switch (BuiltinID) {
3556   case X86::BI__builtin_ia32_readeflags_u32:
3557   case X86::BI__builtin_ia32_writeeflags_u32:
3558     return true;
3559   }
3560 
3561   return false;
3562 }
3563 
3564 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3565   if (BuiltinID == X86::BI__builtin_cpu_supports)
3566     return SemaBuiltinCpuSupports(*this, TheCall);
3567 
3568   if (BuiltinID == X86::BI__builtin_cpu_is)
3569     return SemaBuiltinCpuIs(*this, TheCall);
3570 
3571   // Check for 32-bit only builtins on a 64-bit target.
3572   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3573   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3574     return Diag(TheCall->getCallee()->getBeginLoc(),
3575                 diag::err_32_bit_builtin_64_bit_tgt);
3576 
3577   // If the intrinsic has rounding or SAE make sure its valid.
3578   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3579     return true;
3580 
3581   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3582   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3583     return true;
3584 
3585   // For intrinsics which take an immediate value as part of the instruction,
3586   // range check them here.
3587   int i = 0, l = 0, u = 0;
3588   switch (BuiltinID) {
3589   default:
3590     return false;
3591   case X86::BI__builtin_ia32_vec_ext_v2si:
3592   case X86::BI__builtin_ia32_vec_ext_v2di:
3593   case X86::BI__builtin_ia32_vextractf128_pd256:
3594   case X86::BI__builtin_ia32_vextractf128_ps256:
3595   case X86::BI__builtin_ia32_vextractf128_si256:
3596   case X86::BI__builtin_ia32_extract128i256:
3597   case X86::BI__builtin_ia32_extractf64x4_mask:
3598   case X86::BI__builtin_ia32_extracti64x4_mask:
3599   case X86::BI__builtin_ia32_extractf32x8_mask:
3600   case X86::BI__builtin_ia32_extracti32x8_mask:
3601   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3602   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3603   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3604   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3605     i = 1; l = 0; u = 1;
3606     break;
3607   case X86::BI__builtin_ia32_vec_set_v2di:
3608   case X86::BI__builtin_ia32_vinsertf128_pd256:
3609   case X86::BI__builtin_ia32_vinsertf128_ps256:
3610   case X86::BI__builtin_ia32_vinsertf128_si256:
3611   case X86::BI__builtin_ia32_insert128i256:
3612   case X86::BI__builtin_ia32_insertf32x8:
3613   case X86::BI__builtin_ia32_inserti32x8:
3614   case X86::BI__builtin_ia32_insertf64x4:
3615   case X86::BI__builtin_ia32_inserti64x4:
3616   case X86::BI__builtin_ia32_insertf64x2_256:
3617   case X86::BI__builtin_ia32_inserti64x2_256:
3618   case X86::BI__builtin_ia32_insertf32x4_256:
3619   case X86::BI__builtin_ia32_inserti32x4_256:
3620     i = 2; l = 0; u = 1;
3621     break;
3622   case X86::BI__builtin_ia32_vpermilpd:
3623   case X86::BI__builtin_ia32_vec_ext_v4hi:
3624   case X86::BI__builtin_ia32_vec_ext_v4si:
3625   case X86::BI__builtin_ia32_vec_ext_v4sf:
3626   case X86::BI__builtin_ia32_vec_ext_v4di:
3627   case X86::BI__builtin_ia32_extractf32x4_mask:
3628   case X86::BI__builtin_ia32_extracti32x4_mask:
3629   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3630   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3631     i = 1; l = 0; u = 3;
3632     break;
3633   case X86::BI_mm_prefetch:
3634   case X86::BI__builtin_ia32_vec_ext_v8hi:
3635   case X86::BI__builtin_ia32_vec_ext_v8si:
3636     i = 1; l = 0; u = 7;
3637     break;
3638   case X86::BI__builtin_ia32_sha1rnds4:
3639   case X86::BI__builtin_ia32_blendpd:
3640   case X86::BI__builtin_ia32_shufpd:
3641   case X86::BI__builtin_ia32_vec_set_v4hi:
3642   case X86::BI__builtin_ia32_vec_set_v4si:
3643   case X86::BI__builtin_ia32_vec_set_v4di:
3644   case X86::BI__builtin_ia32_shuf_f32x4_256:
3645   case X86::BI__builtin_ia32_shuf_f64x2_256:
3646   case X86::BI__builtin_ia32_shuf_i32x4_256:
3647   case X86::BI__builtin_ia32_shuf_i64x2_256:
3648   case X86::BI__builtin_ia32_insertf64x2_512:
3649   case X86::BI__builtin_ia32_inserti64x2_512:
3650   case X86::BI__builtin_ia32_insertf32x4:
3651   case X86::BI__builtin_ia32_inserti32x4:
3652     i = 2; l = 0; u = 3;
3653     break;
3654   case X86::BI__builtin_ia32_vpermil2pd:
3655   case X86::BI__builtin_ia32_vpermil2pd256:
3656   case X86::BI__builtin_ia32_vpermil2ps:
3657   case X86::BI__builtin_ia32_vpermil2ps256:
3658     i = 3; l = 0; u = 3;
3659     break;
3660   case X86::BI__builtin_ia32_cmpb128_mask:
3661   case X86::BI__builtin_ia32_cmpw128_mask:
3662   case X86::BI__builtin_ia32_cmpd128_mask:
3663   case X86::BI__builtin_ia32_cmpq128_mask:
3664   case X86::BI__builtin_ia32_cmpb256_mask:
3665   case X86::BI__builtin_ia32_cmpw256_mask:
3666   case X86::BI__builtin_ia32_cmpd256_mask:
3667   case X86::BI__builtin_ia32_cmpq256_mask:
3668   case X86::BI__builtin_ia32_cmpb512_mask:
3669   case X86::BI__builtin_ia32_cmpw512_mask:
3670   case X86::BI__builtin_ia32_cmpd512_mask:
3671   case X86::BI__builtin_ia32_cmpq512_mask:
3672   case X86::BI__builtin_ia32_ucmpb128_mask:
3673   case X86::BI__builtin_ia32_ucmpw128_mask:
3674   case X86::BI__builtin_ia32_ucmpd128_mask:
3675   case X86::BI__builtin_ia32_ucmpq128_mask:
3676   case X86::BI__builtin_ia32_ucmpb256_mask:
3677   case X86::BI__builtin_ia32_ucmpw256_mask:
3678   case X86::BI__builtin_ia32_ucmpd256_mask:
3679   case X86::BI__builtin_ia32_ucmpq256_mask:
3680   case X86::BI__builtin_ia32_ucmpb512_mask:
3681   case X86::BI__builtin_ia32_ucmpw512_mask:
3682   case X86::BI__builtin_ia32_ucmpd512_mask:
3683   case X86::BI__builtin_ia32_ucmpq512_mask:
3684   case X86::BI__builtin_ia32_vpcomub:
3685   case X86::BI__builtin_ia32_vpcomuw:
3686   case X86::BI__builtin_ia32_vpcomud:
3687   case X86::BI__builtin_ia32_vpcomuq:
3688   case X86::BI__builtin_ia32_vpcomb:
3689   case X86::BI__builtin_ia32_vpcomw:
3690   case X86::BI__builtin_ia32_vpcomd:
3691   case X86::BI__builtin_ia32_vpcomq:
3692   case X86::BI__builtin_ia32_vec_set_v8hi:
3693   case X86::BI__builtin_ia32_vec_set_v8si:
3694     i = 2; l = 0; u = 7;
3695     break;
3696   case X86::BI__builtin_ia32_vpermilpd256:
3697   case X86::BI__builtin_ia32_roundps:
3698   case X86::BI__builtin_ia32_roundpd:
3699   case X86::BI__builtin_ia32_roundps256:
3700   case X86::BI__builtin_ia32_roundpd256:
3701   case X86::BI__builtin_ia32_getmantpd128_mask:
3702   case X86::BI__builtin_ia32_getmantpd256_mask:
3703   case X86::BI__builtin_ia32_getmantps128_mask:
3704   case X86::BI__builtin_ia32_getmantps256_mask:
3705   case X86::BI__builtin_ia32_getmantpd512_mask:
3706   case X86::BI__builtin_ia32_getmantps512_mask:
3707   case X86::BI__builtin_ia32_vec_ext_v16qi:
3708   case X86::BI__builtin_ia32_vec_ext_v16hi:
3709     i = 1; l = 0; u = 15;
3710     break;
3711   case X86::BI__builtin_ia32_pblendd128:
3712   case X86::BI__builtin_ia32_blendps:
3713   case X86::BI__builtin_ia32_blendpd256:
3714   case X86::BI__builtin_ia32_shufpd256:
3715   case X86::BI__builtin_ia32_roundss:
3716   case X86::BI__builtin_ia32_roundsd:
3717   case X86::BI__builtin_ia32_rangepd128_mask:
3718   case X86::BI__builtin_ia32_rangepd256_mask:
3719   case X86::BI__builtin_ia32_rangepd512_mask:
3720   case X86::BI__builtin_ia32_rangeps128_mask:
3721   case X86::BI__builtin_ia32_rangeps256_mask:
3722   case X86::BI__builtin_ia32_rangeps512_mask:
3723   case X86::BI__builtin_ia32_getmantsd_round_mask:
3724   case X86::BI__builtin_ia32_getmantss_round_mask:
3725   case X86::BI__builtin_ia32_vec_set_v16qi:
3726   case X86::BI__builtin_ia32_vec_set_v16hi:
3727     i = 2; l = 0; u = 15;
3728     break;
3729   case X86::BI__builtin_ia32_vec_ext_v32qi:
3730     i = 1; l = 0; u = 31;
3731     break;
3732   case X86::BI__builtin_ia32_cmpps:
3733   case X86::BI__builtin_ia32_cmpss:
3734   case X86::BI__builtin_ia32_cmppd:
3735   case X86::BI__builtin_ia32_cmpsd:
3736   case X86::BI__builtin_ia32_cmpps256:
3737   case X86::BI__builtin_ia32_cmppd256:
3738   case X86::BI__builtin_ia32_cmpps128_mask:
3739   case X86::BI__builtin_ia32_cmppd128_mask:
3740   case X86::BI__builtin_ia32_cmpps256_mask:
3741   case X86::BI__builtin_ia32_cmppd256_mask:
3742   case X86::BI__builtin_ia32_cmpps512_mask:
3743   case X86::BI__builtin_ia32_cmppd512_mask:
3744   case X86::BI__builtin_ia32_cmpsd_mask:
3745   case X86::BI__builtin_ia32_cmpss_mask:
3746   case X86::BI__builtin_ia32_vec_set_v32qi:
3747     i = 2; l = 0; u = 31;
3748     break;
3749   case X86::BI__builtin_ia32_permdf256:
3750   case X86::BI__builtin_ia32_permdi256:
3751   case X86::BI__builtin_ia32_permdf512:
3752   case X86::BI__builtin_ia32_permdi512:
3753   case X86::BI__builtin_ia32_vpermilps:
3754   case X86::BI__builtin_ia32_vpermilps256:
3755   case X86::BI__builtin_ia32_vpermilpd512:
3756   case X86::BI__builtin_ia32_vpermilps512:
3757   case X86::BI__builtin_ia32_pshufd:
3758   case X86::BI__builtin_ia32_pshufd256:
3759   case X86::BI__builtin_ia32_pshufd512:
3760   case X86::BI__builtin_ia32_pshufhw:
3761   case X86::BI__builtin_ia32_pshufhw256:
3762   case X86::BI__builtin_ia32_pshufhw512:
3763   case X86::BI__builtin_ia32_pshuflw:
3764   case X86::BI__builtin_ia32_pshuflw256:
3765   case X86::BI__builtin_ia32_pshuflw512:
3766   case X86::BI__builtin_ia32_vcvtps2ph:
3767   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3768   case X86::BI__builtin_ia32_vcvtps2ph256:
3769   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3770   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3771   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3772   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3773   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3774   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3775   case X86::BI__builtin_ia32_rndscaleps_mask:
3776   case X86::BI__builtin_ia32_rndscalepd_mask:
3777   case X86::BI__builtin_ia32_reducepd128_mask:
3778   case X86::BI__builtin_ia32_reducepd256_mask:
3779   case X86::BI__builtin_ia32_reducepd512_mask:
3780   case X86::BI__builtin_ia32_reduceps128_mask:
3781   case X86::BI__builtin_ia32_reduceps256_mask:
3782   case X86::BI__builtin_ia32_reduceps512_mask:
3783   case X86::BI__builtin_ia32_prold512:
3784   case X86::BI__builtin_ia32_prolq512:
3785   case X86::BI__builtin_ia32_prold128:
3786   case X86::BI__builtin_ia32_prold256:
3787   case X86::BI__builtin_ia32_prolq128:
3788   case X86::BI__builtin_ia32_prolq256:
3789   case X86::BI__builtin_ia32_prord512:
3790   case X86::BI__builtin_ia32_prorq512:
3791   case X86::BI__builtin_ia32_prord128:
3792   case X86::BI__builtin_ia32_prord256:
3793   case X86::BI__builtin_ia32_prorq128:
3794   case X86::BI__builtin_ia32_prorq256:
3795   case X86::BI__builtin_ia32_fpclasspd128_mask:
3796   case X86::BI__builtin_ia32_fpclasspd256_mask:
3797   case X86::BI__builtin_ia32_fpclassps128_mask:
3798   case X86::BI__builtin_ia32_fpclassps256_mask:
3799   case X86::BI__builtin_ia32_fpclassps512_mask:
3800   case X86::BI__builtin_ia32_fpclasspd512_mask:
3801   case X86::BI__builtin_ia32_fpclasssd_mask:
3802   case X86::BI__builtin_ia32_fpclassss_mask:
3803   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3804   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3805   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3806   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3807   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3808   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3809   case X86::BI__builtin_ia32_kshiftliqi:
3810   case X86::BI__builtin_ia32_kshiftlihi:
3811   case X86::BI__builtin_ia32_kshiftlisi:
3812   case X86::BI__builtin_ia32_kshiftlidi:
3813   case X86::BI__builtin_ia32_kshiftriqi:
3814   case X86::BI__builtin_ia32_kshiftrihi:
3815   case X86::BI__builtin_ia32_kshiftrisi:
3816   case X86::BI__builtin_ia32_kshiftridi:
3817     i = 1; l = 0; u = 255;
3818     break;
3819   case X86::BI__builtin_ia32_vperm2f128_pd256:
3820   case X86::BI__builtin_ia32_vperm2f128_ps256:
3821   case X86::BI__builtin_ia32_vperm2f128_si256:
3822   case X86::BI__builtin_ia32_permti256:
3823   case X86::BI__builtin_ia32_pblendw128:
3824   case X86::BI__builtin_ia32_pblendw256:
3825   case X86::BI__builtin_ia32_blendps256:
3826   case X86::BI__builtin_ia32_pblendd256:
3827   case X86::BI__builtin_ia32_palignr128:
3828   case X86::BI__builtin_ia32_palignr256:
3829   case X86::BI__builtin_ia32_palignr512:
3830   case X86::BI__builtin_ia32_alignq512:
3831   case X86::BI__builtin_ia32_alignd512:
3832   case X86::BI__builtin_ia32_alignd128:
3833   case X86::BI__builtin_ia32_alignd256:
3834   case X86::BI__builtin_ia32_alignq128:
3835   case X86::BI__builtin_ia32_alignq256:
3836   case X86::BI__builtin_ia32_vcomisd:
3837   case X86::BI__builtin_ia32_vcomiss:
3838   case X86::BI__builtin_ia32_shuf_f32x4:
3839   case X86::BI__builtin_ia32_shuf_f64x2:
3840   case X86::BI__builtin_ia32_shuf_i32x4:
3841   case X86::BI__builtin_ia32_shuf_i64x2:
3842   case X86::BI__builtin_ia32_shufpd512:
3843   case X86::BI__builtin_ia32_shufps:
3844   case X86::BI__builtin_ia32_shufps256:
3845   case X86::BI__builtin_ia32_shufps512:
3846   case X86::BI__builtin_ia32_dbpsadbw128:
3847   case X86::BI__builtin_ia32_dbpsadbw256:
3848   case X86::BI__builtin_ia32_dbpsadbw512:
3849   case X86::BI__builtin_ia32_vpshldd128:
3850   case X86::BI__builtin_ia32_vpshldd256:
3851   case X86::BI__builtin_ia32_vpshldd512:
3852   case X86::BI__builtin_ia32_vpshldq128:
3853   case X86::BI__builtin_ia32_vpshldq256:
3854   case X86::BI__builtin_ia32_vpshldq512:
3855   case X86::BI__builtin_ia32_vpshldw128:
3856   case X86::BI__builtin_ia32_vpshldw256:
3857   case X86::BI__builtin_ia32_vpshldw512:
3858   case X86::BI__builtin_ia32_vpshrdd128:
3859   case X86::BI__builtin_ia32_vpshrdd256:
3860   case X86::BI__builtin_ia32_vpshrdd512:
3861   case X86::BI__builtin_ia32_vpshrdq128:
3862   case X86::BI__builtin_ia32_vpshrdq256:
3863   case X86::BI__builtin_ia32_vpshrdq512:
3864   case X86::BI__builtin_ia32_vpshrdw128:
3865   case X86::BI__builtin_ia32_vpshrdw256:
3866   case X86::BI__builtin_ia32_vpshrdw512:
3867     i = 2; l = 0; u = 255;
3868     break;
3869   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3870   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3871   case X86::BI__builtin_ia32_fixupimmps512_mask:
3872   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3873   case X86::BI__builtin_ia32_fixupimmsd_mask:
3874   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3875   case X86::BI__builtin_ia32_fixupimmss_mask:
3876   case X86::BI__builtin_ia32_fixupimmss_maskz:
3877   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3878   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3879   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3880   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3881   case X86::BI__builtin_ia32_fixupimmps128_mask:
3882   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3883   case X86::BI__builtin_ia32_fixupimmps256_mask:
3884   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3885   case X86::BI__builtin_ia32_pternlogd512_mask:
3886   case X86::BI__builtin_ia32_pternlogd512_maskz:
3887   case X86::BI__builtin_ia32_pternlogq512_mask:
3888   case X86::BI__builtin_ia32_pternlogq512_maskz:
3889   case X86::BI__builtin_ia32_pternlogd128_mask:
3890   case X86::BI__builtin_ia32_pternlogd128_maskz:
3891   case X86::BI__builtin_ia32_pternlogd256_mask:
3892   case X86::BI__builtin_ia32_pternlogd256_maskz:
3893   case X86::BI__builtin_ia32_pternlogq128_mask:
3894   case X86::BI__builtin_ia32_pternlogq128_maskz:
3895   case X86::BI__builtin_ia32_pternlogq256_mask:
3896   case X86::BI__builtin_ia32_pternlogq256_maskz:
3897     i = 3; l = 0; u = 255;
3898     break;
3899   case X86::BI__builtin_ia32_gatherpfdpd:
3900   case X86::BI__builtin_ia32_gatherpfdps:
3901   case X86::BI__builtin_ia32_gatherpfqpd:
3902   case X86::BI__builtin_ia32_gatherpfqps:
3903   case X86::BI__builtin_ia32_scatterpfdpd:
3904   case X86::BI__builtin_ia32_scatterpfdps:
3905   case X86::BI__builtin_ia32_scatterpfqpd:
3906   case X86::BI__builtin_ia32_scatterpfqps:
3907     i = 4; l = 2; u = 3;
3908     break;
3909   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3910   case X86::BI__builtin_ia32_rndscaless_round_mask:
3911     i = 4; l = 0; u = 255;
3912     break;
3913   }
3914 
3915   // Note that we don't force a hard error on the range check here, allowing
3916   // template-generated or macro-generated dead code to potentially have out-of-
3917   // range values. These need to code generate, but don't need to necessarily
3918   // make any sense. We use a warning that defaults to an error.
3919   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3920 }
3921 
3922 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3923 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3924 /// Returns true when the format fits the function and the FormatStringInfo has
3925 /// been populated.
3926 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3927                                FormatStringInfo *FSI) {
3928   FSI->HasVAListArg = Format->getFirstArg() == 0;
3929   FSI->FormatIdx = Format->getFormatIdx() - 1;
3930   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3931 
3932   // The way the format attribute works in GCC, the implicit this argument
3933   // of member functions is counted. However, it doesn't appear in our own
3934   // lists, so decrement format_idx in that case.
3935   if (IsCXXMember) {
3936     if(FSI->FormatIdx == 0)
3937       return false;
3938     --FSI->FormatIdx;
3939     if (FSI->FirstDataArg != 0)
3940       --FSI->FirstDataArg;
3941   }
3942   return true;
3943 }
3944 
3945 /// Checks if a the given expression evaluates to null.
3946 ///
3947 /// Returns true if the value evaluates to null.
3948 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3949   // If the expression has non-null type, it doesn't evaluate to null.
3950   if (auto nullability
3951         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3952     if (*nullability == NullabilityKind::NonNull)
3953       return false;
3954   }
3955 
3956   // As a special case, transparent unions initialized with zero are
3957   // considered null for the purposes of the nonnull attribute.
3958   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3959     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3960       if (const CompoundLiteralExpr *CLE =
3961           dyn_cast<CompoundLiteralExpr>(Expr))
3962         if (const InitListExpr *ILE =
3963             dyn_cast<InitListExpr>(CLE->getInitializer()))
3964           Expr = ILE->getInit(0);
3965   }
3966 
3967   bool Result;
3968   return (!Expr->isValueDependent() &&
3969           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3970           !Result);
3971 }
3972 
3973 static void CheckNonNullArgument(Sema &S,
3974                                  const Expr *ArgExpr,
3975                                  SourceLocation CallSiteLoc) {
3976   if (CheckNonNullExpr(S, ArgExpr))
3977     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3978            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
3979 }
3980 
3981 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3982   FormatStringInfo FSI;
3983   if ((GetFormatStringType(Format) == FST_NSString) &&
3984       getFormatStringInfo(Format, false, &FSI)) {
3985     Idx = FSI.FormatIdx;
3986     return true;
3987   }
3988   return false;
3989 }
3990 
3991 /// Diagnose use of %s directive in an NSString which is being passed
3992 /// as formatting string to formatting method.
3993 static void
3994 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3995                                         const NamedDecl *FDecl,
3996                                         Expr **Args,
3997                                         unsigned NumArgs) {
3998   unsigned Idx = 0;
3999   bool Format = false;
4000   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4001   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4002     Idx = 2;
4003     Format = true;
4004   }
4005   else
4006     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4007       if (S.GetFormatNSStringIdx(I, Idx)) {
4008         Format = true;
4009         break;
4010       }
4011     }
4012   if (!Format || NumArgs <= Idx)
4013     return;
4014   const Expr *FormatExpr = Args[Idx];
4015   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4016     FormatExpr = CSCE->getSubExpr();
4017   const StringLiteral *FormatString;
4018   if (const ObjCStringLiteral *OSL =
4019       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4020     FormatString = OSL->getString();
4021   else
4022     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4023   if (!FormatString)
4024     return;
4025   if (S.FormatStringHasSArg(FormatString)) {
4026     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4027       << "%s" << 1 << 1;
4028     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4029       << FDecl->getDeclName();
4030   }
4031 }
4032 
4033 /// Determine whether the given type has a non-null nullability annotation.
4034 static bool isNonNullType(ASTContext &ctx, QualType type) {
4035   if (auto nullability = type->getNullability(ctx))
4036     return *nullability == NullabilityKind::NonNull;
4037 
4038   return false;
4039 }
4040 
4041 static void CheckNonNullArguments(Sema &S,
4042                                   const NamedDecl *FDecl,
4043                                   const FunctionProtoType *Proto,
4044                                   ArrayRef<const Expr *> Args,
4045                                   SourceLocation CallSiteLoc) {
4046   assert((FDecl || Proto) && "Need a function declaration or prototype");
4047 
4048   // Check the attributes attached to the method/function itself.
4049   llvm::SmallBitVector NonNullArgs;
4050   if (FDecl) {
4051     // Handle the nonnull attribute on the function/method declaration itself.
4052     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4053       if (!NonNull->args_size()) {
4054         // Easy case: all pointer arguments are nonnull.
4055         for (const auto *Arg : Args)
4056           if (S.isValidPointerAttrType(Arg->getType()))
4057             CheckNonNullArgument(S, Arg, CallSiteLoc);
4058         return;
4059       }
4060 
4061       for (const ParamIdx &Idx : NonNull->args()) {
4062         unsigned IdxAST = Idx.getASTIndex();
4063         if (IdxAST >= Args.size())
4064           continue;
4065         if (NonNullArgs.empty())
4066           NonNullArgs.resize(Args.size());
4067         NonNullArgs.set(IdxAST);
4068       }
4069     }
4070   }
4071 
4072   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4073     // Handle the nonnull attribute on the parameters of the
4074     // function/method.
4075     ArrayRef<ParmVarDecl*> parms;
4076     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4077       parms = FD->parameters();
4078     else
4079       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4080 
4081     unsigned ParamIndex = 0;
4082     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4083          I != E; ++I, ++ParamIndex) {
4084       const ParmVarDecl *PVD = *I;
4085       if (PVD->hasAttr<NonNullAttr>() ||
4086           isNonNullType(S.Context, PVD->getType())) {
4087         if (NonNullArgs.empty())
4088           NonNullArgs.resize(Args.size());
4089 
4090         NonNullArgs.set(ParamIndex);
4091       }
4092     }
4093   } else {
4094     // If we have a non-function, non-method declaration but no
4095     // function prototype, try to dig out the function prototype.
4096     if (!Proto) {
4097       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4098         QualType type = VD->getType().getNonReferenceType();
4099         if (auto pointerType = type->getAs<PointerType>())
4100           type = pointerType->getPointeeType();
4101         else if (auto blockType = type->getAs<BlockPointerType>())
4102           type = blockType->getPointeeType();
4103         // FIXME: data member pointers?
4104 
4105         // Dig out the function prototype, if there is one.
4106         Proto = type->getAs<FunctionProtoType>();
4107       }
4108     }
4109 
4110     // Fill in non-null argument information from the nullability
4111     // information on the parameter types (if we have them).
4112     if (Proto) {
4113       unsigned Index = 0;
4114       for (auto paramType : Proto->getParamTypes()) {
4115         if (isNonNullType(S.Context, paramType)) {
4116           if (NonNullArgs.empty())
4117             NonNullArgs.resize(Args.size());
4118 
4119           NonNullArgs.set(Index);
4120         }
4121 
4122         ++Index;
4123       }
4124     }
4125   }
4126 
4127   // Check for non-null arguments.
4128   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4129        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4130     if (NonNullArgs[ArgIndex])
4131       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4132   }
4133 }
4134 
4135 /// Handles the checks for format strings, non-POD arguments to vararg
4136 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4137 /// attributes.
4138 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4139                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4140                      bool IsMemberFunction, SourceLocation Loc,
4141                      SourceRange Range, VariadicCallType CallType) {
4142   // FIXME: We should check as much as we can in the template definition.
4143   if (CurContext->isDependentContext())
4144     return;
4145 
4146   // Printf and scanf checking.
4147   llvm::SmallBitVector CheckedVarArgs;
4148   if (FDecl) {
4149     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4150       // Only create vector if there are format attributes.
4151       CheckedVarArgs.resize(Args.size());
4152 
4153       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4154                            CheckedVarArgs);
4155     }
4156   }
4157 
4158   // Refuse POD arguments that weren't caught by the format string
4159   // checks above.
4160   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4161   if (CallType != VariadicDoesNotApply &&
4162       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4163     unsigned NumParams = Proto ? Proto->getNumParams()
4164                        : FDecl && isa<FunctionDecl>(FDecl)
4165                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4166                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4167                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4168                        : 0;
4169 
4170     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4171       // Args[ArgIdx] can be null in malformed code.
4172       if (const Expr *Arg = Args[ArgIdx]) {
4173         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4174           checkVariadicArgument(Arg, CallType);
4175       }
4176     }
4177   }
4178 
4179   if (FDecl || Proto) {
4180     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4181 
4182     // Type safety checking.
4183     if (FDecl) {
4184       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4185         CheckArgumentWithTypeTag(I, Args, Loc);
4186     }
4187   }
4188 
4189   if (FD)
4190     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4191 }
4192 
4193 /// CheckConstructorCall - Check a constructor call for correctness and safety
4194 /// properties not enforced by the C type system.
4195 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4196                                 ArrayRef<const Expr *> Args,
4197                                 const FunctionProtoType *Proto,
4198                                 SourceLocation Loc) {
4199   VariadicCallType CallType =
4200     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4201   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4202             Loc, SourceRange(), CallType);
4203 }
4204 
4205 /// CheckFunctionCall - Check a direct function call for various correctness
4206 /// and safety properties not strictly enforced by the C type system.
4207 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4208                              const FunctionProtoType *Proto) {
4209   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4210                               isa<CXXMethodDecl>(FDecl);
4211   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4212                           IsMemberOperatorCall;
4213   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4214                                                   TheCall->getCallee());
4215   Expr** Args = TheCall->getArgs();
4216   unsigned NumArgs = TheCall->getNumArgs();
4217 
4218   Expr *ImplicitThis = nullptr;
4219   if (IsMemberOperatorCall) {
4220     // If this is a call to a member operator, hide the first argument
4221     // from checkCall.
4222     // FIXME: Our choice of AST representation here is less than ideal.
4223     ImplicitThis = Args[0];
4224     ++Args;
4225     --NumArgs;
4226   } else if (IsMemberFunction)
4227     ImplicitThis =
4228         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4229 
4230   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4231             IsMemberFunction, TheCall->getRParenLoc(),
4232             TheCall->getCallee()->getSourceRange(), CallType);
4233 
4234   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4235   // None of the checks below are needed for functions that don't have
4236   // simple names (e.g., C++ conversion functions).
4237   if (!FnInfo)
4238     return false;
4239 
4240   CheckAbsoluteValueFunction(TheCall, FDecl);
4241   CheckMaxUnsignedZero(TheCall, FDecl);
4242 
4243   if (getLangOpts().ObjC)
4244     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4245 
4246   unsigned CMId = FDecl->getMemoryFunctionKind();
4247   if (CMId == 0)
4248     return false;
4249 
4250   // Handle memory setting and copying functions.
4251   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4252     CheckStrlcpycatArguments(TheCall, FnInfo);
4253   else if (CMId == Builtin::BIstrncat)
4254     CheckStrncatArguments(TheCall, FnInfo);
4255   else
4256     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4257 
4258   return false;
4259 }
4260 
4261 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4262                                ArrayRef<const Expr *> Args) {
4263   VariadicCallType CallType =
4264       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4265 
4266   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4267             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4268             CallType);
4269 
4270   return false;
4271 }
4272 
4273 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4274                             const FunctionProtoType *Proto) {
4275   QualType Ty;
4276   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4277     Ty = V->getType().getNonReferenceType();
4278   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4279     Ty = F->getType().getNonReferenceType();
4280   else
4281     return false;
4282 
4283   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4284       !Ty->isFunctionProtoType())
4285     return false;
4286 
4287   VariadicCallType CallType;
4288   if (!Proto || !Proto->isVariadic()) {
4289     CallType = VariadicDoesNotApply;
4290   } else if (Ty->isBlockPointerType()) {
4291     CallType = VariadicBlock;
4292   } else { // Ty->isFunctionPointerType()
4293     CallType = VariadicFunction;
4294   }
4295 
4296   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4297             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4298             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4299             TheCall->getCallee()->getSourceRange(), CallType);
4300 
4301   return false;
4302 }
4303 
4304 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4305 /// such as function pointers returned from functions.
4306 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4307   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4308                                                   TheCall->getCallee());
4309   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4310             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4311             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4312             TheCall->getCallee()->getSourceRange(), CallType);
4313 
4314   return false;
4315 }
4316 
4317 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4318   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4319     return false;
4320 
4321   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4322   switch (Op) {
4323   case AtomicExpr::AO__c11_atomic_init:
4324   case AtomicExpr::AO__opencl_atomic_init:
4325     llvm_unreachable("There is no ordering argument for an init");
4326 
4327   case AtomicExpr::AO__c11_atomic_load:
4328   case AtomicExpr::AO__opencl_atomic_load:
4329   case AtomicExpr::AO__atomic_load_n:
4330   case AtomicExpr::AO__atomic_load:
4331     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4332            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4333 
4334   case AtomicExpr::AO__c11_atomic_store:
4335   case AtomicExpr::AO__opencl_atomic_store:
4336   case AtomicExpr::AO__atomic_store:
4337   case AtomicExpr::AO__atomic_store_n:
4338     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4339            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4340            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4341 
4342   default:
4343     return true;
4344   }
4345 }
4346 
4347 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4348                                          AtomicExpr::AtomicOp Op) {
4349   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4350   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4351 
4352   // All the non-OpenCL operations take one of the following forms.
4353   // The OpenCL operations take the __c11 forms with one extra argument for
4354   // synchronization scope.
4355   enum {
4356     // C    __c11_atomic_init(A *, C)
4357     Init,
4358 
4359     // C    __c11_atomic_load(A *, int)
4360     Load,
4361 
4362     // void __atomic_load(A *, CP, int)
4363     LoadCopy,
4364 
4365     // void __atomic_store(A *, CP, int)
4366     Copy,
4367 
4368     // C    __c11_atomic_add(A *, M, int)
4369     Arithmetic,
4370 
4371     // C    __atomic_exchange_n(A *, CP, int)
4372     Xchg,
4373 
4374     // void __atomic_exchange(A *, C *, CP, int)
4375     GNUXchg,
4376 
4377     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4378     C11CmpXchg,
4379 
4380     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4381     GNUCmpXchg
4382   } Form = Init;
4383 
4384   const unsigned NumForm = GNUCmpXchg + 1;
4385   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4386   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4387   // where:
4388   //   C is an appropriate type,
4389   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4390   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4391   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4392   //   the int parameters are for orderings.
4393 
4394   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4395       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4396       "need to update code for modified forms");
4397   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4398                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4399                         AtomicExpr::AO__atomic_load,
4400                 "need to update code for modified C11 atomics");
4401   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4402                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4403   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4404                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4405                IsOpenCL;
4406   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4407              Op == AtomicExpr::AO__atomic_store_n ||
4408              Op == AtomicExpr::AO__atomic_exchange_n ||
4409              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4410   bool IsAddSub = false;
4411   bool IsMinMax = false;
4412 
4413   switch (Op) {
4414   case AtomicExpr::AO__c11_atomic_init:
4415   case AtomicExpr::AO__opencl_atomic_init:
4416     Form = Init;
4417     break;
4418 
4419   case AtomicExpr::AO__c11_atomic_load:
4420   case AtomicExpr::AO__opencl_atomic_load:
4421   case AtomicExpr::AO__atomic_load_n:
4422     Form = Load;
4423     break;
4424 
4425   case AtomicExpr::AO__atomic_load:
4426     Form = LoadCopy;
4427     break;
4428 
4429   case AtomicExpr::AO__c11_atomic_store:
4430   case AtomicExpr::AO__opencl_atomic_store:
4431   case AtomicExpr::AO__atomic_store:
4432   case AtomicExpr::AO__atomic_store_n:
4433     Form = Copy;
4434     break;
4435 
4436   case AtomicExpr::AO__c11_atomic_fetch_add:
4437   case AtomicExpr::AO__c11_atomic_fetch_sub:
4438   case AtomicExpr::AO__opencl_atomic_fetch_add:
4439   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4440   case AtomicExpr::AO__opencl_atomic_fetch_min:
4441   case AtomicExpr::AO__opencl_atomic_fetch_max:
4442   case AtomicExpr::AO__atomic_fetch_add:
4443   case AtomicExpr::AO__atomic_fetch_sub:
4444   case AtomicExpr::AO__atomic_add_fetch:
4445   case AtomicExpr::AO__atomic_sub_fetch:
4446     IsAddSub = true;
4447     LLVM_FALLTHROUGH;
4448   case AtomicExpr::AO__c11_atomic_fetch_and:
4449   case AtomicExpr::AO__c11_atomic_fetch_or:
4450   case AtomicExpr::AO__c11_atomic_fetch_xor:
4451   case AtomicExpr::AO__opencl_atomic_fetch_and:
4452   case AtomicExpr::AO__opencl_atomic_fetch_or:
4453   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4454   case AtomicExpr::AO__atomic_fetch_and:
4455   case AtomicExpr::AO__atomic_fetch_or:
4456   case AtomicExpr::AO__atomic_fetch_xor:
4457   case AtomicExpr::AO__atomic_fetch_nand:
4458   case AtomicExpr::AO__atomic_and_fetch:
4459   case AtomicExpr::AO__atomic_or_fetch:
4460   case AtomicExpr::AO__atomic_xor_fetch:
4461   case AtomicExpr::AO__atomic_nand_fetch:
4462     Form = Arithmetic;
4463     break;
4464 
4465   case AtomicExpr::AO__atomic_fetch_min:
4466   case AtomicExpr::AO__atomic_fetch_max:
4467     IsMinMax = true;
4468     Form = Arithmetic;
4469     break;
4470 
4471   case AtomicExpr::AO__c11_atomic_exchange:
4472   case AtomicExpr::AO__opencl_atomic_exchange:
4473   case AtomicExpr::AO__atomic_exchange_n:
4474     Form = Xchg;
4475     break;
4476 
4477   case AtomicExpr::AO__atomic_exchange:
4478     Form = GNUXchg;
4479     break;
4480 
4481   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4482   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4483   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4484   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4485     Form = C11CmpXchg;
4486     break;
4487 
4488   case AtomicExpr::AO__atomic_compare_exchange:
4489   case AtomicExpr::AO__atomic_compare_exchange_n:
4490     Form = GNUCmpXchg;
4491     break;
4492   }
4493 
4494   unsigned AdjustedNumArgs = NumArgs[Form];
4495   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4496     ++AdjustedNumArgs;
4497   // Check we have the right number of arguments.
4498   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4499     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4500         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4501         << TheCall->getCallee()->getSourceRange();
4502     return ExprError();
4503   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4504     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4505          diag::err_typecheck_call_too_many_args)
4506         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4507         << TheCall->getCallee()->getSourceRange();
4508     return ExprError();
4509   }
4510 
4511   // Inspect the first argument of the atomic operation.
4512   Expr *Ptr = TheCall->getArg(0);
4513   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4514   if (ConvertedPtr.isInvalid())
4515     return ExprError();
4516 
4517   Ptr = ConvertedPtr.get();
4518   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4519   if (!pointerType) {
4520     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4521         << Ptr->getType() << Ptr->getSourceRange();
4522     return ExprError();
4523   }
4524 
4525   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4526   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4527   QualType ValType = AtomTy; // 'C'
4528   if (IsC11) {
4529     if (!AtomTy->isAtomicType()) {
4530       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4531           << Ptr->getType() << Ptr->getSourceRange();
4532       return ExprError();
4533     }
4534     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4535         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4536       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4537           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4538           << Ptr->getSourceRange();
4539       return ExprError();
4540     }
4541     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4542   } else if (Form != Load && Form != LoadCopy) {
4543     if (ValType.isConstQualified()) {
4544       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4545           << Ptr->getType() << Ptr->getSourceRange();
4546       return ExprError();
4547     }
4548   }
4549 
4550   // For an arithmetic operation, the implied arithmetic must be well-formed.
4551   if (Form == Arithmetic) {
4552     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4553     if (IsAddSub && !ValType->isIntegerType()
4554         && !ValType->isPointerType()) {
4555       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4556           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4557       return ExprError();
4558     }
4559     if (IsMinMax) {
4560       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4561       if (!BT || (BT->getKind() != BuiltinType::Int &&
4562                   BT->getKind() != BuiltinType::UInt)) {
4563         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4564         return ExprError();
4565       }
4566     }
4567     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4568       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4569           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4570       return ExprError();
4571     }
4572     if (IsC11 && ValType->isPointerType() &&
4573         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4574                             diag::err_incomplete_type)) {
4575       return ExprError();
4576     }
4577   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4578     // For __atomic_*_n operations, the value type must be a scalar integral or
4579     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4580     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4581         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4582     return ExprError();
4583   }
4584 
4585   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4586       !AtomTy->isScalarType()) {
4587     // For GNU atomics, require a trivially-copyable type. This is not part of
4588     // the GNU atomics specification, but we enforce it for sanity.
4589     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4590         << Ptr->getType() << Ptr->getSourceRange();
4591     return ExprError();
4592   }
4593 
4594   switch (ValType.getObjCLifetime()) {
4595   case Qualifiers::OCL_None:
4596   case Qualifiers::OCL_ExplicitNone:
4597     // okay
4598     break;
4599 
4600   case Qualifiers::OCL_Weak:
4601   case Qualifiers::OCL_Strong:
4602   case Qualifiers::OCL_Autoreleasing:
4603     // FIXME: Can this happen? By this point, ValType should be known
4604     // to be trivially copyable.
4605     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4606         << ValType << Ptr->getSourceRange();
4607     return ExprError();
4608   }
4609 
4610   // All atomic operations have an overload which takes a pointer to a volatile
4611   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4612   // into the result or the other operands. Similarly atomic_load takes a
4613   // pointer to a const 'A'.
4614   ValType.removeLocalVolatile();
4615   ValType.removeLocalConst();
4616   QualType ResultType = ValType;
4617   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4618       Form == Init)
4619     ResultType = Context.VoidTy;
4620   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4621     ResultType = Context.BoolTy;
4622 
4623   // The type of a parameter passed 'by value'. In the GNU atomics, such
4624   // arguments are actually passed as pointers.
4625   QualType ByValType = ValType; // 'CP'
4626   bool IsPassedByAddress = false;
4627   if (!IsC11 && !IsN) {
4628     ByValType = Ptr->getType();
4629     IsPassedByAddress = true;
4630   }
4631 
4632   // The first argument's non-CV pointer type is used to deduce the type of
4633   // subsequent arguments, except for:
4634   //  - weak flag (always converted to bool)
4635   //  - memory order (always converted to int)
4636   //  - scope  (always converted to int)
4637   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4638     QualType Ty;
4639     if (i < NumVals[Form] + 1) {
4640       switch (i) {
4641       case 0:
4642         // The first argument is always a pointer. It has a fixed type.
4643         // It is always dereferenced, a nullptr is undefined.
4644         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4645         // Nothing else to do: we already know all we want about this pointer.
4646         continue;
4647       case 1:
4648         // The second argument is the non-atomic operand. For arithmetic, this
4649         // is always passed by value, and for a compare_exchange it is always
4650         // passed by address. For the rest, GNU uses by-address and C11 uses
4651         // by-value.
4652         assert(Form != Load);
4653         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4654           Ty = ValType;
4655         else if (Form == Copy || Form == Xchg) {
4656           if (IsPassedByAddress)
4657             // The value pointer is always dereferenced, a nullptr is undefined.
4658             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4659           Ty = ByValType;
4660         } else if (Form == Arithmetic)
4661           Ty = Context.getPointerDiffType();
4662         else {
4663           Expr *ValArg = TheCall->getArg(i);
4664           // The value pointer is always dereferenced, a nullptr is undefined.
4665           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4666           LangAS AS = LangAS::Default;
4667           // Keep address space of non-atomic pointer type.
4668           if (const PointerType *PtrTy =
4669                   ValArg->getType()->getAs<PointerType>()) {
4670             AS = PtrTy->getPointeeType().getAddressSpace();
4671           }
4672           Ty = Context.getPointerType(
4673               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4674         }
4675         break;
4676       case 2:
4677         // The third argument to compare_exchange / GNU exchange is the desired
4678         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4679         if (IsPassedByAddress)
4680           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4681         Ty = ByValType;
4682         break;
4683       case 3:
4684         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4685         Ty = Context.BoolTy;
4686         break;
4687       }
4688     } else {
4689       // The order(s) and scope are always converted to int.
4690       Ty = Context.IntTy;
4691     }
4692 
4693     InitializedEntity Entity =
4694         InitializedEntity::InitializeParameter(Context, Ty, false);
4695     ExprResult Arg = TheCall->getArg(i);
4696     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4697     if (Arg.isInvalid())
4698       return true;
4699     TheCall->setArg(i, Arg.get());
4700   }
4701 
4702   // Permute the arguments into a 'consistent' order.
4703   SmallVector<Expr*, 5> SubExprs;
4704   SubExprs.push_back(Ptr);
4705   switch (Form) {
4706   case Init:
4707     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4708     SubExprs.push_back(TheCall->getArg(1)); // Val1
4709     break;
4710   case Load:
4711     SubExprs.push_back(TheCall->getArg(1)); // Order
4712     break;
4713   case LoadCopy:
4714   case Copy:
4715   case Arithmetic:
4716   case Xchg:
4717     SubExprs.push_back(TheCall->getArg(2)); // Order
4718     SubExprs.push_back(TheCall->getArg(1)); // Val1
4719     break;
4720   case GNUXchg:
4721     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4722     SubExprs.push_back(TheCall->getArg(3)); // Order
4723     SubExprs.push_back(TheCall->getArg(1)); // Val1
4724     SubExprs.push_back(TheCall->getArg(2)); // Val2
4725     break;
4726   case C11CmpXchg:
4727     SubExprs.push_back(TheCall->getArg(3)); // Order
4728     SubExprs.push_back(TheCall->getArg(1)); // Val1
4729     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4730     SubExprs.push_back(TheCall->getArg(2)); // Val2
4731     break;
4732   case GNUCmpXchg:
4733     SubExprs.push_back(TheCall->getArg(4)); // Order
4734     SubExprs.push_back(TheCall->getArg(1)); // Val1
4735     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4736     SubExprs.push_back(TheCall->getArg(2)); // Val2
4737     SubExprs.push_back(TheCall->getArg(3)); // Weak
4738     break;
4739   }
4740 
4741   if (SubExprs.size() >= 2 && Form != Init) {
4742     llvm::APSInt Result(32);
4743     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4744         !isValidOrderingForOp(Result.getSExtValue(), Op))
4745       Diag(SubExprs[1]->getBeginLoc(),
4746            diag::warn_atomic_op_has_invalid_memory_order)
4747           << SubExprs[1]->getSourceRange();
4748   }
4749 
4750   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4751     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4752     llvm::APSInt Result(32);
4753     if (Scope->isIntegerConstantExpr(Result, Context) &&
4754         !ScopeModel->isValid(Result.getZExtValue())) {
4755       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4756           << Scope->getSourceRange();
4757     }
4758     SubExprs.push_back(Scope);
4759   }
4760 
4761   AtomicExpr *AE =
4762       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4763                                ResultType, Op, TheCall->getRParenLoc());
4764 
4765   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4766        Op == AtomicExpr::AO__c11_atomic_store ||
4767        Op == AtomicExpr::AO__opencl_atomic_load ||
4768        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4769       Context.AtomicUsesUnsupportedLibcall(AE))
4770     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4771         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4772              Op == AtomicExpr::AO__opencl_atomic_load)
4773                 ? 0
4774                 : 1);
4775 
4776   return AE;
4777 }
4778 
4779 /// checkBuiltinArgument - Given a call to a builtin function, perform
4780 /// normal type-checking on the given argument, updating the call in
4781 /// place.  This is useful when a builtin function requires custom
4782 /// type-checking for some of its arguments but not necessarily all of
4783 /// them.
4784 ///
4785 /// Returns true on error.
4786 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4787   FunctionDecl *Fn = E->getDirectCallee();
4788   assert(Fn && "builtin call without direct callee!");
4789 
4790   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4791   InitializedEntity Entity =
4792     InitializedEntity::InitializeParameter(S.Context, Param);
4793 
4794   ExprResult Arg = E->getArg(0);
4795   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4796   if (Arg.isInvalid())
4797     return true;
4798 
4799   E->setArg(ArgIndex, Arg.get());
4800   return false;
4801 }
4802 
4803 /// We have a call to a function like __sync_fetch_and_add, which is an
4804 /// overloaded function based on the pointer type of its first argument.
4805 /// The main ActOnCallExpr routines have already promoted the types of
4806 /// arguments because all of these calls are prototyped as void(...).
4807 ///
4808 /// This function goes through and does final semantic checking for these
4809 /// builtins, as well as generating any warnings.
4810 ExprResult
4811 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4812   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4813   Expr *Callee = TheCall->getCallee();
4814   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4815   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4816 
4817   // Ensure that we have at least one argument to do type inference from.
4818   if (TheCall->getNumArgs() < 1) {
4819     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4820         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4821     return ExprError();
4822   }
4823 
4824   // Inspect the first argument of the atomic builtin.  This should always be
4825   // a pointer type, whose element is an integral scalar or pointer type.
4826   // Because it is a pointer type, we don't have to worry about any implicit
4827   // casts here.
4828   // FIXME: We don't allow floating point scalars as input.
4829   Expr *FirstArg = TheCall->getArg(0);
4830   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4831   if (FirstArgResult.isInvalid())
4832     return ExprError();
4833   FirstArg = FirstArgResult.get();
4834   TheCall->setArg(0, FirstArg);
4835 
4836   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4837   if (!pointerType) {
4838     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4839         << FirstArg->getType() << FirstArg->getSourceRange();
4840     return ExprError();
4841   }
4842 
4843   QualType ValType = pointerType->getPointeeType();
4844   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4845       !ValType->isBlockPointerType()) {
4846     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4847         << FirstArg->getType() << FirstArg->getSourceRange();
4848     return ExprError();
4849   }
4850 
4851   if (ValType.isConstQualified()) {
4852     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4853         << FirstArg->getType() << FirstArg->getSourceRange();
4854     return ExprError();
4855   }
4856 
4857   switch (ValType.getObjCLifetime()) {
4858   case Qualifiers::OCL_None:
4859   case Qualifiers::OCL_ExplicitNone:
4860     // okay
4861     break;
4862 
4863   case Qualifiers::OCL_Weak:
4864   case Qualifiers::OCL_Strong:
4865   case Qualifiers::OCL_Autoreleasing:
4866     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4867         << ValType << FirstArg->getSourceRange();
4868     return ExprError();
4869   }
4870 
4871   // Strip any qualifiers off ValType.
4872   ValType = ValType.getUnqualifiedType();
4873 
4874   // The majority of builtins return a value, but a few have special return
4875   // types, so allow them to override appropriately below.
4876   QualType ResultType = ValType;
4877 
4878   // We need to figure out which concrete builtin this maps onto.  For example,
4879   // __sync_fetch_and_add with a 2 byte object turns into
4880   // __sync_fetch_and_add_2.
4881 #define BUILTIN_ROW(x) \
4882   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4883     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4884 
4885   static const unsigned BuiltinIndices[][5] = {
4886     BUILTIN_ROW(__sync_fetch_and_add),
4887     BUILTIN_ROW(__sync_fetch_and_sub),
4888     BUILTIN_ROW(__sync_fetch_and_or),
4889     BUILTIN_ROW(__sync_fetch_and_and),
4890     BUILTIN_ROW(__sync_fetch_and_xor),
4891     BUILTIN_ROW(__sync_fetch_and_nand),
4892 
4893     BUILTIN_ROW(__sync_add_and_fetch),
4894     BUILTIN_ROW(__sync_sub_and_fetch),
4895     BUILTIN_ROW(__sync_and_and_fetch),
4896     BUILTIN_ROW(__sync_or_and_fetch),
4897     BUILTIN_ROW(__sync_xor_and_fetch),
4898     BUILTIN_ROW(__sync_nand_and_fetch),
4899 
4900     BUILTIN_ROW(__sync_val_compare_and_swap),
4901     BUILTIN_ROW(__sync_bool_compare_and_swap),
4902     BUILTIN_ROW(__sync_lock_test_and_set),
4903     BUILTIN_ROW(__sync_lock_release),
4904     BUILTIN_ROW(__sync_swap)
4905   };
4906 #undef BUILTIN_ROW
4907 
4908   // Determine the index of the size.
4909   unsigned SizeIndex;
4910   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4911   case 1: SizeIndex = 0; break;
4912   case 2: SizeIndex = 1; break;
4913   case 4: SizeIndex = 2; break;
4914   case 8: SizeIndex = 3; break;
4915   case 16: SizeIndex = 4; break;
4916   default:
4917     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4918         << FirstArg->getType() << FirstArg->getSourceRange();
4919     return ExprError();
4920   }
4921 
4922   // Each of these builtins has one pointer argument, followed by some number of
4923   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4924   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4925   // as the number of fixed args.
4926   unsigned BuiltinID = FDecl->getBuiltinID();
4927   unsigned BuiltinIndex, NumFixed = 1;
4928   bool WarnAboutSemanticsChange = false;
4929   switch (BuiltinID) {
4930   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4931   case Builtin::BI__sync_fetch_and_add:
4932   case Builtin::BI__sync_fetch_and_add_1:
4933   case Builtin::BI__sync_fetch_and_add_2:
4934   case Builtin::BI__sync_fetch_and_add_4:
4935   case Builtin::BI__sync_fetch_and_add_8:
4936   case Builtin::BI__sync_fetch_and_add_16:
4937     BuiltinIndex = 0;
4938     break;
4939 
4940   case Builtin::BI__sync_fetch_and_sub:
4941   case Builtin::BI__sync_fetch_and_sub_1:
4942   case Builtin::BI__sync_fetch_and_sub_2:
4943   case Builtin::BI__sync_fetch_and_sub_4:
4944   case Builtin::BI__sync_fetch_and_sub_8:
4945   case Builtin::BI__sync_fetch_and_sub_16:
4946     BuiltinIndex = 1;
4947     break;
4948 
4949   case Builtin::BI__sync_fetch_and_or:
4950   case Builtin::BI__sync_fetch_and_or_1:
4951   case Builtin::BI__sync_fetch_and_or_2:
4952   case Builtin::BI__sync_fetch_and_or_4:
4953   case Builtin::BI__sync_fetch_and_or_8:
4954   case Builtin::BI__sync_fetch_and_or_16:
4955     BuiltinIndex = 2;
4956     break;
4957 
4958   case Builtin::BI__sync_fetch_and_and:
4959   case Builtin::BI__sync_fetch_and_and_1:
4960   case Builtin::BI__sync_fetch_and_and_2:
4961   case Builtin::BI__sync_fetch_and_and_4:
4962   case Builtin::BI__sync_fetch_and_and_8:
4963   case Builtin::BI__sync_fetch_and_and_16:
4964     BuiltinIndex = 3;
4965     break;
4966 
4967   case Builtin::BI__sync_fetch_and_xor:
4968   case Builtin::BI__sync_fetch_and_xor_1:
4969   case Builtin::BI__sync_fetch_and_xor_2:
4970   case Builtin::BI__sync_fetch_and_xor_4:
4971   case Builtin::BI__sync_fetch_and_xor_8:
4972   case Builtin::BI__sync_fetch_and_xor_16:
4973     BuiltinIndex = 4;
4974     break;
4975 
4976   case Builtin::BI__sync_fetch_and_nand:
4977   case Builtin::BI__sync_fetch_and_nand_1:
4978   case Builtin::BI__sync_fetch_and_nand_2:
4979   case Builtin::BI__sync_fetch_and_nand_4:
4980   case Builtin::BI__sync_fetch_and_nand_8:
4981   case Builtin::BI__sync_fetch_and_nand_16:
4982     BuiltinIndex = 5;
4983     WarnAboutSemanticsChange = true;
4984     break;
4985 
4986   case Builtin::BI__sync_add_and_fetch:
4987   case Builtin::BI__sync_add_and_fetch_1:
4988   case Builtin::BI__sync_add_and_fetch_2:
4989   case Builtin::BI__sync_add_and_fetch_4:
4990   case Builtin::BI__sync_add_and_fetch_8:
4991   case Builtin::BI__sync_add_and_fetch_16:
4992     BuiltinIndex = 6;
4993     break;
4994 
4995   case Builtin::BI__sync_sub_and_fetch:
4996   case Builtin::BI__sync_sub_and_fetch_1:
4997   case Builtin::BI__sync_sub_and_fetch_2:
4998   case Builtin::BI__sync_sub_and_fetch_4:
4999   case Builtin::BI__sync_sub_and_fetch_8:
5000   case Builtin::BI__sync_sub_and_fetch_16:
5001     BuiltinIndex = 7;
5002     break;
5003 
5004   case Builtin::BI__sync_and_and_fetch:
5005   case Builtin::BI__sync_and_and_fetch_1:
5006   case Builtin::BI__sync_and_and_fetch_2:
5007   case Builtin::BI__sync_and_and_fetch_4:
5008   case Builtin::BI__sync_and_and_fetch_8:
5009   case Builtin::BI__sync_and_and_fetch_16:
5010     BuiltinIndex = 8;
5011     break;
5012 
5013   case Builtin::BI__sync_or_and_fetch:
5014   case Builtin::BI__sync_or_and_fetch_1:
5015   case Builtin::BI__sync_or_and_fetch_2:
5016   case Builtin::BI__sync_or_and_fetch_4:
5017   case Builtin::BI__sync_or_and_fetch_8:
5018   case Builtin::BI__sync_or_and_fetch_16:
5019     BuiltinIndex = 9;
5020     break;
5021 
5022   case Builtin::BI__sync_xor_and_fetch:
5023   case Builtin::BI__sync_xor_and_fetch_1:
5024   case Builtin::BI__sync_xor_and_fetch_2:
5025   case Builtin::BI__sync_xor_and_fetch_4:
5026   case Builtin::BI__sync_xor_and_fetch_8:
5027   case Builtin::BI__sync_xor_and_fetch_16:
5028     BuiltinIndex = 10;
5029     break;
5030 
5031   case Builtin::BI__sync_nand_and_fetch:
5032   case Builtin::BI__sync_nand_and_fetch_1:
5033   case Builtin::BI__sync_nand_and_fetch_2:
5034   case Builtin::BI__sync_nand_and_fetch_4:
5035   case Builtin::BI__sync_nand_and_fetch_8:
5036   case Builtin::BI__sync_nand_and_fetch_16:
5037     BuiltinIndex = 11;
5038     WarnAboutSemanticsChange = true;
5039     break;
5040 
5041   case Builtin::BI__sync_val_compare_and_swap:
5042   case Builtin::BI__sync_val_compare_and_swap_1:
5043   case Builtin::BI__sync_val_compare_and_swap_2:
5044   case Builtin::BI__sync_val_compare_and_swap_4:
5045   case Builtin::BI__sync_val_compare_and_swap_8:
5046   case Builtin::BI__sync_val_compare_and_swap_16:
5047     BuiltinIndex = 12;
5048     NumFixed = 2;
5049     break;
5050 
5051   case Builtin::BI__sync_bool_compare_and_swap:
5052   case Builtin::BI__sync_bool_compare_and_swap_1:
5053   case Builtin::BI__sync_bool_compare_and_swap_2:
5054   case Builtin::BI__sync_bool_compare_and_swap_4:
5055   case Builtin::BI__sync_bool_compare_and_swap_8:
5056   case Builtin::BI__sync_bool_compare_and_swap_16:
5057     BuiltinIndex = 13;
5058     NumFixed = 2;
5059     ResultType = Context.BoolTy;
5060     break;
5061 
5062   case Builtin::BI__sync_lock_test_and_set:
5063   case Builtin::BI__sync_lock_test_and_set_1:
5064   case Builtin::BI__sync_lock_test_and_set_2:
5065   case Builtin::BI__sync_lock_test_and_set_4:
5066   case Builtin::BI__sync_lock_test_and_set_8:
5067   case Builtin::BI__sync_lock_test_and_set_16:
5068     BuiltinIndex = 14;
5069     break;
5070 
5071   case Builtin::BI__sync_lock_release:
5072   case Builtin::BI__sync_lock_release_1:
5073   case Builtin::BI__sync_lock_release_2:
5074   case Builtin::BI__sync_lock_release_4:
5075   case Builtin::BI__sync_lock_release_8:
5076   case Builtin::BI__sync_lock_release_16:
5077     BuiltinIndex = 15;
5078     NumFixed = 0;
5079     ResultType = Context.VoidTy;
5080     break;
5081 
5082   case Builtin::BI__sync_swap:
5083   case Builtin::BI__sync_swap_1:
5084   case Builtin::BI__sync_swap_2:
5085   case Builtin::BI__sync_swap_4:
5086   case Builtin::BI__sync_swap_8:
5087   case Builtin::BI__sync_swap_16:
5088     BuiltinIndex = 16;
5089     break;
5090   }
5091 
5092   // Now that we know how many fixed arguments we expect, first check that we
5093   // have at least that many.
5094   if (TheCall->getNumArgs() < 1+NumFixed) {
5095     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5096         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5097         << Callee->getSourceRange();
5098     return ExprError();
5099   }
5100 
5101   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5102       << Callee->getSourceRange();
5103 
5104   if (WarnAboutSemanticsChange) {
5105     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5106         << Callee->getSourceRange();
5107   }
5108 
5109   // Get the decl for the concrete builtin from this, we can tell what the
5110   // concrete integer type we should convert to is.
5111   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5112   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5113   FunctionDecl *NewBuiltinDecl;
5114   if (NewBuiltinID == BuiltinID)
5115     NewBuiltinDecl = FDecl;
5116   else {
5117     // Perform builtin lookup to avoid redeclaring it.
5118     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5119     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5120     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5121     assert(Res.getFoundDecl());
5122     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5123     if (!NewBuiltinDecl)
5124       return ExprError();
5125   }
5126 
5127   // The first argument --- the pointer --- has a fixed type; we
5128   // deduce the types of the rest of the arguments accordingly.  Walk
5129   // the remaining arguments, converting them to the deduced value type.
5130   for (unsigned i = 0; i != NumFixed; ++i) {
5131     ExprResult Arg = TheCall->getArg(i+1);
5132 
5133     // GCC does an implicit conversion to the pointer or integer ValType.  This
5134     // can fail in some cases (1i -> int**), check for this error case now.
5135     // Initialize the argument.
5136     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5137                                                    ValType, /*consume*/ false);
5138     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5139     if (Arg.isInvalid())
5140       return ExprError();
5141 
5142     // Okay, we have something that *can* be converted to the right type.  Check
5143     // to see if there is a potentially weird extension going on here.  This can
5144     // happen when you do an atomic operation on something like an char* and
5145     // pass in 42.  The 42 gets converted to char.  This is even more strange
5146     // for things like 45.123 -> char, etc.
5147     // FIXME: Do this check.
5148     TheCall->setArg(i+1, Arg.get());
5149   }
5150 
5151   // Create a new DeclRefExpr to refer to the new decl.
5152   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5153       Context,
5154       DRE->getQualifierLoc(),
5155       SourceLocation(),
5156       NewBuiltinDecl,
5157       /*enclosing*/ false,
5158       DRE->getLocation(),
5159       Context.BuiltinFnTy,
5160       DRE->getValueKind());
5161 
5162   // Set the callee in the CallExpr.
5163   // FIXME: This loses syntactic information.
5164   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5165   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5166                                               CK_BuiltinFnToFnPtr);
5167   TheCall->setCallee(PromotedCall.get());
5168 
5169   // Change the result type of the call to match the original value type. This
5170   // is arbitrary, but the codegen for these builtins ins design to handle it
5171   // gracefully.
5172   TheCall->setType(ResultType);
5173 
5174   return TheCallResult;
5175 }
5176 
5177 /// SemaBuiltinNontemporalOverloaded - We have a call to
5178 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5179 /// overloaded function based on the pointer type of its last argument.
5180 ///
5181 /// This function goes through and does final semantic checking for these
5182 /// builtins.
5183 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5184   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5185   DeclRefExpr *DRE =
5186       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5187   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5188   unsigned BuiltinID = FDecl->getBuiltinID();
5189   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5190           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5191          "Unexpected nontemporal load/store builtin!");
5192   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5193   unsigned numArgs = isStore ? 2 : 1;
5194 
5195   // Ensure that we have the proper number of arguments.
5196   if (checkArgCount(*this, TheCall, numArgs))
5197     return ExprError();
5198 
5199   // Inspect the last argument of the nontemporal builtin.  This should always
5200   // be a pointer type, from which we imply the type of the memory access.
5201   // Because it is a pointer type, we don't have to worry about any implicit
5202   // casts here.
5203   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5204   ExprResult PointerArgResult =
5205       DefaultFunctionArrayLvalueConversion(PointerArg);
5206 
5207   if (PointerArgResult.isInvalid())
5208     return ExprError();
5209   PointerArg = PointerArgResult.get();
5210   TheCall->setArg(numArgs - 1, PointerArg);
5211 
5212   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5213   if (!pointerType) {
5214     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5215         << PointerArg->getType() << PointerArg->getSourceRange();
5216     return ExprError();
5217   }
5218 
5219   QualType ValType = pointerType->getPointeeType();
5220 
5221   // Strip any qualifiers off ValType.
5222   ValType = ValType.getUnqualifiedType();
5223   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5224       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5225       !ValType->isVectorType()) {
5226     Diag(DRE->getBeginLoc(),
5227          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5228         << PointerArg->getType() << PointerArg->getSourceRange();
5229     return ExprError();
5230   }
5231 
5232   if (!isStore) {
5233     TheCall->setType(ValType);
5234     return TheCallResult;
5235   }
5236 
5237   ExprResult ValArg = TheCall->getArg(0);
5238   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5239       Context, ValType, /*consume*/ false);
5240   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5241   if (ValArg.isInvalid())
5242     return ExprError();
5243 
5244   TheCall->setArg(0, ValArg.get());
5245   TheCall->setType(Context.VoidTy);
5246   return TheCallResult;
5247 }
5248 
5249 /// CheckObjCString - Checks that the argument to the builtin
5250 /// CFString constructor is correct
5251 /// Note: It might also make sense to do the UTF-16 conversion here (would
5252 /// simplify the backend).
5253 bool Sema::CheckObjCString(Expr *Arg) {
5254   Arg = Arg->IgnoreParenCasts();
5255   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5256 
5257   if (!Literal || !Literal->isAscii()) {
5258     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5259         << Arg->getSourceRange();
5260     return true;
5261   }
5262 
5263   if (Literal->containsNonAsciiOrNull()) {
5264     StringRef String = Literal->getString();
5265     unsigned NumBytes = String.size();
5266     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5267     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5268     llvm::UTF16 *ToPtr = &ToBuf[0];
5269 
5270     llvm::ConversionResult Result =
5271         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5272                                  ToPtr + NumBytes, llvm::strictConversion);
5273     // Check for conversion failure.
5274     if (Result != llvm::conversionOK)
5275       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5276           << Arg->getSourceRange();
5277   }
5278   return false;
5279 }
5280 
5281 /// CheckObjCString - Checks that the format string argument to the os_log()
5282 /// and os_trace() functions is correct, and converts it to const char *.
5283 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5284   Arg = Arg->IgnoreParenCasts();
5285   auto *Literal = dyn_cast<StringLiteral>(Arg);
5286   if (!Literal) {
5287     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5288       Literal = ObjcLiteral->getString();
5289     }
5290   }
5291 
5292   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5293     return ExprError(
5294         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5295         << Arg->getSourceRange());
5296   }
5297 
5298   ExprResult Result(Literal);
5299   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5300   InitializedEntity Entity =
5301       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5302   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5303   return Result;
5304 }
5305 
5306 /// Check that the user is calling the appropriate va_start builtin for the
5307 /// target and calling convention.
5308 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5309   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5310   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5311   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5312   bool IsWindows = TT.isOSWindows();
5313   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5314   if (IsX64 || IsAArch64) {
5315     CallingConv CC = CC_C;
5316     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5317       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5318     if (IsMSVAStart) {
5319       // Don't allow this in System V ABI functions.
5320       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5321         return S.Diag(Fn->getBeginLoc(),
5322                       diag::err_ms_va_start_used_in_sysv_function);
5323     } else {
5324       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5325       // On x64 Windows, don't allow this in System V ABI functions.
5326       // (Yes, that means there's no corresponding way to support variadic
5327       // System V ABI functions on Windows.)
5328       if ((IsWindows && CC == CC_X86_64SysV) ||
5329           (!IsWindows && CC == CC_Win64))
5330         return S.Diag(Fn->getBeginLoc(),
5331                       diag::err_va_start_used_in_wrong_abi_function)
5332                << !IsWindows;
5333     }
5334     return false;
5335   }
5336 
5337   if (IsMSVAStart)
5338     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5339   return false;
5340 }
5341 
5342 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5343                                              ParmVarDecl **LastParam = nullptr) {
5344   // Determine whether the current function, block, or obj-c method is variadic
5345   // and get its parameter list.
5346   bool IsVariadic = false;
5347   ArrayRef<ParmVarDecl *> Params;
5348   DeclContext *Caller = S.CurContext;
5349   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5350     IsVariadic = Block->isVariadic();
5351     Params = Block->parameters();
5352   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5353     IsVariadic = FD->isVariadic();
5354     Params = FD->parameters();
5355   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5356     IsVariadic = MD->isVariadic();
5357     // FIXME: This isn't correct for methods (results in bogus warning).
5358     Params = MD->parameters();
5359   } else if (isa<CapturedDecl>(Caller)) {
5360     // We don't support va_start in a CapturedDecl.
5361     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5362     return true;
5363   } else {
5364     // This must be some other declcontext that parses exprs.
5365     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5366     return true;
5367   }
5368 
5369   if (!IsVariadic) {
5370     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5371     return true;
5372   }
5373 
5374   if (LastParam)
5375     *LastParam = Params.empty() ? nullptr : Params.back();
5376 
5377   return false;
5378 }
5379 
5380 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5381 /// for validity.  Emit an error and return true on failure; return false
5382 /// on success.
5383 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5384   Expr *Fn = TheCall->getCallee();
5385 
5386   if (checkVAStartABI(*this, BuiltinID, Fn))
5387     return true;
5388 
5389   if (TheCall->getNumArgs() > 2) {
5390     Diag(TheCall->getArg(2)->getBeginLoc(),
5391          diag::err_typecheck_call_too_many_args)
5392         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5393         << Fn->getSourceRange()
5394         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5395                        (*(TheCall->arg_end() - 1))->getEndLoc());
5396     return true;
5397   }
5398 
5399   if (TheCall->getNumArgs() < 2) {
5400     return Diag(TheCall->getEndLoc(),
5401                 diag::err_typecheck_call_too_few_args_at_least)
5402            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5403   }
5404 
5405   // Type-check the first argument normally.
5406   if (checkBuiltinArgument(*this, TheCall, 0))
5407     return true;
5408 
5409   // Check that the current function is variadic, and get its last parameter.
5410   ParmVarDecl *LastParam;
5411   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5412     return true;
5413 
5414   // Verify that the second argument to the builtin is the last argument of the
5415   // current function or method.
5416   bool SecondArgIsLastNamedArgument = false;
5417   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5418 
5419   // These are valid if SecondArgIsLastNamedArgument is false after the next
5420   // block.
5421   QualType Type;
5422   SourceLocation ParamLoc;
5423   bool IsCRegister = false;
5424 
5425   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5426     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5427       SecondArgIsLastNamedArgument = PV == LastParam;
5428 
5429       Type = PV->getType();
5430       ParamLoc = PV->getLocation();
5431       IsCRegister =
5432           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5433     }
5434   }
5435 
5436   if (!SecondArgIsLastNamedArgument)
5437     Diag(TheCall->getArg(1)->getBeginLoc(),
5438          diag::warn_second_arg_of_va_start_not_last_named_param);
5439   else if (IsCRegister || Type->isReferenceType() ||
5440            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5441              // Promotable integers are UB, but enumerations need a bit of
5442              // extra checking to see what their promotable type actually is.
5443              if (!Type->isPromotableIntegerType())
5444                return false;
5445              if (!Type->isEnumeralType())
5446                return true;
5447              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5448              return !(ED &&
5449                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5450            }()) {
5451     unsigned Reason = 0;
5452     if (Type->isReferenceType())  Reason = 1;
5453     else if (IsCRegister)         Reason = 2;
5454     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5455     Diag(ParamLoc, diag::note_parameter_type) << Type;
5456   }
5457 
5458   TheCall->setType(Context.VoidTy);
5459   return false;
5460 }
5461 
5462 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5463   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5464   //                 const char *named_addr);
5465 
5466   Expr *Func = Call->getCallee();
5467 
5468   if (Call->getNumArgs() < 3)
5469     return Diag(Call->getEndLoc(),
5470                 diag::err_typecheck_call_too_few_args_at_least)
5471            << 0 /*function call*/ << 3 << Call->getNumArgs();
5472 
5473   // Type-check the first argument normally.
5474   if (checkBuiltinArgument(*this, Call, 0))
5475     return true;
5476 
5477   // Check that the current function is variadic.
5478   if (checkVAStartIsInVariadicFunction(*this, Func))
5479     return true;
5480 
5481   // __va_start on Windows does not validate the parameter qualifiers
5482 
5483   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5484   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5485 
5486   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5487   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5488 
5489   const QualType &ConstCharPtrTy =
5490       Context.getPointerType(Context.CharTy.withConst());
5491   if (!Arg1Ty->isPointerType() ||
5492       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5493     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5494         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5495         << 0                                      /* qualifier difference */
5496         << 3                                      /* parameter mismatch */
5497         << 2 << Arg1->getType() << ConstCharPtrTy;
5498 
5499   const QualType SizeTy = Context.getSizeType();
5500   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5501     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5502         << Arg2->getType() << SizeTy << 1 /* different class */
5503         << 0                              /* qualifier difference */
5504         << 3                              /* parameter mismatch */
5505         << 3 << Arg2->getType() << SizeTy;
5506 
5507   return false;
5508 }
5509 
5510 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5511 /// friends.  This is declared to take (...), so we have to check everything.
5512 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5513   if (TheCall->getNumArgs() < 2)
5514     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5515            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5516   if (TheCall->getNumArgs() > 2)
5517     return Diag(TheCall->getArg(2)->getBeginLoc(),
5518                 diag::err_typecheck_call_too_many_args)
5519            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5520            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5521                           (*(TheCall->arg_end() - 1))->getEndLoc());
5522 
5523   ExprResult OrigArg0 = TheCall->getArg(0);
5524   ExprResult OrigArg1 = TheCall->getArg(1);
5525 
5526   // Do standard promotions between the two arguments, returning their common
5527   // type.
5528   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5529   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5530     return true;
5531 
5532   // Make sure any conversions are pushed back into the call; this is
5533   // type safe since unordered compare builtins are declared as "_Bool
5534   // foo(...)".
5535   TheCall->setArg(0, OrigArg0.get());
5536   TheCall->setArg(1, OrigArg1.get());
5537 
5538   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5539     return false;
5540 
5541   // If the common type isn't a real floating type, then the arguments were
5542   // invalid for this operation.
5543   if (Res.isNull() || !Res->isRealFloatingType())
5544     return Diag(OrigArg0.get()->getBeginLoc(),
5545                 diag::err_typecheck_call_invalid_ordered_compare)
5546            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5547            << SourceRange(OrigArg0.get()->getBeginLoc(),
5548                           OrigArg1.get()->getEndLoc());
5549 
5550   return false;
5551 }
5552 
5553 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5554 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5555 /// to check everything. We expect the last argument to be a floating point
5556 /// value.
5557 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5558   if (TheCall->getNumArgs() < NumArgs)
5559     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5560            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5561   if (TheCall->getNumArgs() > NumArgs)
5562     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5563                 diag::err_typecheck_call_too_many_args)
5564            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5565            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5566                           (*(TheCall->arg_end() - 1))->getEndLoc());
5567 
5568   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5569 
5570   if (OrigArg->isTypeDependent())
5571     return false;
5572 
5573   // This operation requires a non-_Complex floating-point number.
5574   if (!OrigArg->getType()->isRealFloatingType())
5575     return Diag(OrigArg->getBeginLoc(),
5576                 diag::err_typecheck_call_invalid_unary_fp)
5577            << OrigArg->getType() << OrigArg->getSourceRange();
5578 
5579   // If this is an implicit conversion from float -> float, double, or
5580   // long double, remove it.
5581   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5582     // Only remove standard FloatCasts, leaving other casts inplace
5583     if (Cast->getCastKind() == CK_FloatingCast) {
5584       Expr *CastArg = Cast->getSubExpr();
5585       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5586         assert(
5587             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5588              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5589              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5590             "promotion from float to either float, double, or long double is "
5591             "the only expected cast here");
5592         Cast->setSubExpr(nullptr);
5593         TheCall->setArg(NumArgs-1, CastArg);
5594       }
5595     }
5596   }
5597 
5598   return false;
5599 }
5600 
5601 // Customized Sema Checking for VSX builtins that have the following signature:
5602 // vector [...] builtinName(vector [...], vector [...], const int);
5603 // Which takes the same type of vectors (any legal vector type) for the first
5604 // two arguments and takes compile time constant for the third argument.
5605 // Example builtins are :
5606 // vector double vec_xxpermdi(vector double, vector double, int);
5607 // vector short vec_xxsldwi(vector short, vector short, int);
5608 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5609   unsigned ExpectedNumArgs = 3;
5610   if (TheCall->getNumArgs() < ExpectedNumArgs)
5611     return Diag(TheCall->getEndLoc(),
5612                 diag::err_typecheck_call_too_few_args_at_least)
5613            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5614            << TheCall->getSourceRange();
5615 
5616   if (TheCall->getNumArgs() > ExpectedNumArgs)
5617     return Diag(TheCall->getEndLoc(),
5618                 diag::err_typecheck_call_too_many_args_at_most)
5619            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5620            << TheCall->getSourceRange();
5621 
5622   // Check the third argument is a compile time constant
5623   llvm::APSInt Value;
5624   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5625     return Diag(TheCall->getBeginLoc(),
5626                 diag::err_vsx_builtin_nonconstant_argument)
5627            << 3 /* argument index */ << TheCall->getDirectCallee()
5628            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5629                           TheCall->getArg(2)->getEndLoc());
5630 
5631   QualType Arg1Ty = TheCall->getArg(0)->getType();
5632   QualType Arg2Ty = TheCall->getArg(1)->getType();
5633 
5634   // Check the type of argument 1 and argument 2 are vectors.
5635   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5636   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5637       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5638     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5639            << TheCall->getDirectCallee()
5640            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5641                           TheCall->getArg(1)->getEndLoc());
5642   }
5643 
5644   // Check the first two arguments are the same type.
5645   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5646     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5647            << TheCall->getDirectCallee()
5648            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5649                           TheCall->getArg(1)->getEndLoc());
5650   }
5651 
5652   // When default clang type checking is turned off and the customized type
5653   // checking is used, the returning type of the function must be explicitly
5654   // set. Otherwise it is _Bool by default.
5655   TheCall->setType(Arg1Ty);
5656 
5657   return false;
5658 }
5659 
5660 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5661 // This is declared to take (...), so we have to check everything.
5662 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5663   if (TheCall->getNumArgs() < 2)
5664     return ExprError(Diag(TheCall->getEndLoc(),
5665                           diag::err_typecheck_call_too_few_args_at_least)
5666                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5667                      << TheCall->getSourceRange());
5668 
5669   // Determine which of the following types of shufflevector we're checking:
5670   // 1) unary, vector mask: (lhs, mask)
5671   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5672   QualType resType = TheCall->getArg(0)->getType();
5673   unsigned numElements = 0;
5674 
5675   if (!TheCall->getArg(0)->isTypeDependent() &&
5676       !TheCall->getArg(1)->isTypeDependent()) {
5677     QualType LHSType = TheCall->getArg(0)->getType();
5678     QualType RHSType = TheCall->getArg(1)->getType();
5679 
5680     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5681       return ExprError(
5682           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5683           << TheCall->getDirectCallee()
5684           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5685                          TheCall->getArg(1)->getEndLoc()));
5686 
5687     numElements = LHSType->getAs<VectorType>()->getNumElements();
5688     unsigned numResElements = TheCall->getNumArgs() - 2;
5689 
5690     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5691     // with mask.  If so, verify that RHS is an integer vector type with the
5692     // same number of elts as lhs.
5693     if (TheCall->getNumArgs() == 2) {
5694       if (!RHSType->hasIntegerRepresentation() ||
5695           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5696         return ExprError(Diag(TheCall->getBeginLoc(),
5697                               diag::err_vec_builtin_incompatible_vector)
5698                          << TheCall->getDirectCallee()
5699                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5700                                         TheCall->getArg(1)->getEndLoc()));
5701     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5702       return ExprError(Diag(TheCall->getBeginLoc(),
5703                             diag::err_vec_builtin_incompatible_vector)
5704                        << TheCall->getDirectCallee()
5705                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5706                                       TheCall->getArg(1)->getEndLoc()));
5707     } else if (numElements != numResElements) {
5708       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5709       resType = Context.getVectorType(eltType, numResElements,
5710                                       VectorType::GenericVector);
5711     }
5712   }
5713 
5714   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5715     if (TheCall->getArg(i)->isTypeDependent() ||
5716         TheCall->getArg(i)->isValueDependent())
5717       continue;
5718 
5719     llvm::APSInt Result(32);
5720     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5721       return ExprError(Diag(TheCall->getBeginLoc(),
5722                             diag::err_shufflevector_nonconstant_argument)
5723                        << TheCall->getArg(i)->getSourceRange());
5724 
5725     // Allow -1 which will be translated to undef in the IR.
5726     if (Result.isSigned() && Result.isAllOnesValue())
5727       continue;
5728 
5729     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5730       return ExprError(Diag(TheCall->getBeginLoc(),
5731                             diag::err_shufflevector_argument_too_large)
5732                        << TheCall->getArg(i)->getSourceRange());
5733   }
5734 
5735   SmallVector<Expr*, 32> exprs;
5736 
5737   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5738     exprs.push_back(TheCall->getArg(i));
5739     TheCall->setArg(i, nullptr);
5740   }
5741 
5742   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5743                                          TheCall->getCallee()->getBeginLoc(),
5744                                          TheCall->getRParenLoc());
5745 }
5746 
5747 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5748 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5749                                        SourceLocation BuiltinLoc,
5750                                        SourceLocation RParenLoc) {
5751   ExprValueKind VK = VK_RValue;
5752   ExprObjectKind OK = OK_Ordinary;
5753   QualType DstTy = TInfo->getType();
5754   QualType SrcTy = E->getType();
5755 
5756   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5757     return ExprError(Diag(BuiltinLoc,
5758                           diag::err_convertvector_non_vector)
5759                      << E->getSourceRange());
5760   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5761     return ExprError(Diag(BuiltinLoc,
5762                           diag::err_convertvector_non_vector_type));
5763 
5764   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5765     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5766     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5767     if (SrcElts != DstElts)
5768       return ExprError(Diag(BuiltinLoc,
5769                             diag::err_convertvector_incompatible_vector)
5770                        << E->getSourceRange());
5771   }
5772 
5773   return new (Context)
5774       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5775 }
5776 
5777 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5778 // This is declared to take (const void*, ...) and can take two
5779 // optional constant int args.
5780 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5781   unsigned NumArgs = TheCall->getNumArgs();
5782 
5783   if (NumArgs > 3)
5784     return Diag(TheCall->getEndLoc(),
5785                 diag::err_typecheck_call_too_many_args_at_most)
5786            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5787 
5788   // Argument 0 is checked for us and the remaining arguments must be
5789   // constant integers.
5790   for (unsigned i = 1; i != NumArgs; ++i)
5791     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5792       return true;
5793 
5794   return false;
5795 }
5796 
5797 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5798 // __assume does not evaluate its arguments, and should warn if its argument
5799 // has side effects.
5800 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5801   Expr *Arg = TheCall->getArg(0);
5802   if (Arg->isInstantiationDependent()) return false;
5803 
5804   if (Arg->HasSideEffects(Context))
5805     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5806         << Arg->getSourceRange()
5807         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5808 
5809   return false;
5810 }
5811 
5812 /// Handle __builtin_alloca_with_align. This is declared
5813 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5814 /// than 8.
5815 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5816   // The alignment must be a constant integer.
5817   Expr *Arg = TheCall->getArg(1);
5818 
5819   // We can't check the value of a dependent argument.
5820   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5821     if (const auto *UE =
5822             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5823       if (UE->getKind() == UETT_AlignOf ||
5824           UE->getKind() == UETT_PreferredAlignOf)
5825         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5826             << Arg->getSourceRange();
5827 
5828     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5829 
5830     if (!Result.isPowerOf2())
5831       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5832              << Arg->getSourceRange();
5833 
5834     if (Result < Context.getCharWidth())
5835       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5836              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5837 
5838     if (Result > std::numeric_limits<int32_t>::max())
5839       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5840              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5841   }
5842 
5843   return false;
5844 }
5845 
5846 /// Handle __builtin_assume_aligned. This is declared
5847 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5848 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5849   unsigned NumArgs = TheCall->getNumArgs();
5850 
5851   if (NumArgs > 3)
5852     return Diag(TheCall->getEndLoc(),
5853                 diag::err_typecheck_call_too_many_args_at_most)
5854            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5855 
5856   // The alignment must be a constant integer.
5857   Expr *Arg = TheCall->getArg(1);
5858 
5859   // We can't check the value of a dependent argument.
5860   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5861     llvm::APSInt Result;
5862     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5863       return true;
5864 
5865     if (!Result.isPowerOf2())
5866       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5867              << Arg->getSourceRange();
5868   }
5869 
5870   if (NumArgs > 2) {
5871     ExprResult Arg(TheCall->getArg(2));
5872     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5873       Context.getSizeType(), false);
5874     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5875     if (Arg.isInvalid()) return true;
5876     TheCall->setArg(2, Arg.get());
5877   }
5878 
5879   return false;
5880 }
5881 
5882 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5883   unsigned BuiltinID =
5884       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5885   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5886 
5887   unsigned NumArgs = TheCall->getNumArgs();
5888   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5889   if (NumArgs < NumRequiredArgs) {
5890     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5891            << 0 /* function call */ << NumRequiredArgs << NumArgs
5892            << TheCall->getSourceRange();
5893   }
5894   if (NumArgs >= NumRequiredArgs + 0x100) {
5895     return Diag(TheCall->getEndLoc(),
5896                 diag::err_typecheck_call_too_many_args_at_most)
5897            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5898            << TheCall->getSourceRange();
5899   }
5900   unsigned i = 0;
5901 
5902   // For formatting call, check buffer arg.
5903   if (!IsSizeCall) {
5904     ExprResult Arg(TheCall->getArg(i));
5905     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5906         Context, Context.VoidPtrTy, false);
5907     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5908     if (Arg.isInvalid())
5909       return true;
5910     TheCall->setArg(i, Arg.get());
5911     i++;
5912   }
5913 
5914   // Check string literal arg.
5915   unsigned FormatIdx = i;
5916   {
5917     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5918     if (Arg.isInvalid())
5919       return true;
5920     TheCall->setArg(i, Arg.get());
5921     i++;
5922   }
5923 
5924   // Make sure variadic args are scalar.
5925   unsigned FirstDataArg = i;
5926   while (i < NumArgs) {
5927     ExprResult Arg = DefaultVariadicArgumentPromotion(
5928         TheCall->getArg(i), VariadicFunction, nullptr);
5929     if (Arg.isInvalid())
5930       return true;
5931     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5932     if (ArgSize.getQuantity() >= 0x100) {
5933       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5934              << i << (int)ArgSize.getQuantity() << 0xff
5935              << TheCall->getSourceRange();
5936     }
5937     TheCall->setArg(i, Arg.get());
5938     i++;
5939   }
5940 
5941   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5942   // call to avoid duplicate diagnostics.
5943   if (!IsSizeCall) {
5944     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5945     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5946     bool Success = CheckFormatArguments(
5947         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5948         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5949         CheckedVarArgs);
5950     if (!Success)
5951       return true;
5952   }
5953 
5954   if (IsSizeCall) {
5955     TheCall->setType(Context.getSizeType());
5956   } else {
5957     TheCall->setType(Context.VoidPtrTy);
5958   }
5959   return false;
5960 }
5961 
5962 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5963 /// TheCall is a constant expression.
5964 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5965                                   llvm::APSInt &Result) {
5966   Expr *Arg = TheCall->getArg(ArgNum);
5967   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5968   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5969 
5970   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5971 
5972   if (!Arg->isIntegerConstantExpr(Result, Context))
5973     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5974            << FDecl->getDeclName() << Arg->getSourceRange();
5975 
5976   return false;
5977 }
5978 
5979 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5980 /// TheCall is a constant expression in the range [Low, High].
5981 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5982                                        int Low, int High, bool RangeIsError) {
5983   llvm::APSInt Result;
5984 
5985   // We can't check the value of a dependent argument.
5986   Expr *Arg = TheCall->getArg(ArgNum);
5987   if (Arg->isTypeDependent() || Arg->isValueDependent())
5988     return false;
5989 
5990   // Check constant-ness first.
5991   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5992     return true;
5993 
5994   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5995     if (RangeIsError)
5996       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5997              << Result.toString(10) << Low << High << Arg->getSourceRange();
5998     else
5999       // Defer the warning until we know if the code will be emitted so that
6000       // dead code can ignore this.
6001       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6002                           PDiag(diag::warn_argument_invalid_range)
6003                               << Result.toString(10) << Low << High
6004                               << Arg->getSourceRange());
6005   }
6006 
6007   return false;
6008 }
6009 
6010 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6011 /// TheCall is a constant expression is a multiple of Num..
6012 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6013                                           unsigned Num) {
6014   llvm::APSInt Result;
6015 
6016   // We can't check the value of a dependent argument.
6017   Expr *Arg = TheCall->getArg(ArgNum);
6018   if (Arg->isTypeDependent() || Arg->isValueDependent())
6019     return false;
6020 
6021   // Check constant-ness first.
6022   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6023     return true;
6024 
6025   if (Result.getSExtValue() % Num != 0)
6026     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6027            << Num << Arg->getSourceRange();
6028 
6029   return false;
6030 }
6031 
6032 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6033 /// TheCall is an ARM/AArch64 special register string literal.
6034 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6035                                     int ArgNum, unsigned ExpectedFieldNum,
6036                                     bool AllowName) {
6037   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6038                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6039                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6040                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6041                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6042                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6043   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6044                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6045                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6046                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6047                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6048                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6049   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6050 
6051   // We can't check the value of a dependent argument.
6052   Expr *Arg = TheCall->getArg(ArgNum);
6053   if (Arg->isTypeDependent() || Arg->isValueDependent())
6054     return false;
6055 
6056   // Check if the argument is a string literal.
6057   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6058     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6059            << Arg->getSourceRange();
6060 
6061   // Check the type of special register given.
6062   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6063   SmallVector<StringRef, 6> Fields;
6064   Reg.split(Fields, ":");
6065 
6066   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6067     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6068            << Arg->getSourceRange();
6069 
6070   // If the string is the name of a register then we cannot check that it is
6071   // valid here but if the string is of one the forms described in ACLE then we
6072   // can check that the supplied fields are integers and within the valid
6073   // ranges.
6074   if (Fields.size() > 1) {
6075     bool FiveFields = Fields.size() == 5;
6076 
6077     bool ValidString = true;
6078     if (IsARMBuiltin) {
6079       ValidString &= Fields[0].startswith_lower("cp") ||
6080                      Fields[0].startswith_lower("p");
6081       if (ValidString)
6082         Fields[0] =
6083           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6084 
6085       ValidString &= Fields[2].startswith_lower("c");
6086       if (ValidString)
6087         Fields[2] = Fields[2].drop_front(1);
6088 
6089       if (FiveFields) {
6090         ValidString &= Fields[3].startswith_lower("c");
6091         if (ValidString)
6092           Fields[3] = Fields[3].drop_front(1);
6093       }
6094     }
6095 
6096     SmallVector<int, 5> Ranges;
6097     if (FiveFields)
6098       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6099     else
6100       Ranges.append({15, 7, 15});
6101 
6102     for (unsigned i=0; i<Fields.size(); ++i) {
6103       int IntField;
6104       ValidString &= !Fields[i].getAsInteger(10, IntField);
6105       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6106     }
6107 
6108     if (!ValidString)
6109       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6110              << Arg->getSourceRange();
6111   } else if (IsAArch64Builtin && Fields.size() == 1) {
6112     // If the register name is one of those that appear in the condition below
6113     // and the special register builtin being used is one of the write builtins,
6114     // then we require that the argument provided for writing to the register
6115     // is an integer constant expression. This is because it will be lowered to
6116     // an MSR (immediate) instruction, so we need to know the immediate at
6117     // compile time.
6118     if (TheCall->getNumArgs() != 2)
6119       return false;
6120 
6121     std::string RegLower = Reg.lower();
6122     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6123         RegLower != "pan" && RegLower != "uao")
6124       return false;
6125 
6126     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6127   }
6128 
6129   return false;
6130 }
6131 
6132 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6133 /// This checks that the target supports __builtin_longjmp and
6134 /// that val is a constant 1.
6135 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6136   if (!Context.getTargetInfo().hasSjLjLowering())
6137     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6138            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6139 
6140   Expr *Arg = TheCall->getArg(1);
6141   llvm::APSInt Result;
6142 
6143   // TODO: This is less than ideal. Overload this to take a value.
6144   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6145     return true;
6146 
6147   if (Result != 1)
6148     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6149            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6150 
6151   return false;
6152 }
6153 
6154 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6155 /// This checks that the target supports __builtin_setjmp.
6156 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6157   if (!Context.getTargetInfo().hasSjLjLowering())
6158     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6159            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6160   return false;
6161 }
6162 
6163 namespace {
6164 
6165 class UncoveredArgHandler {
6166   enum { Unknown = -1, AllCovered = -2 };
6167 
6168   signed FirstUncoveredArg = Unknown;
6169   SmallVector<const Expr *, 4> DiagnosticExprs;
6170 
6171 public:
6172   UncoveredArgHandler() = default;
6173 
6174   bool hasUncoveredArg() const {
6175     return (FirstUncoveredArg >= 0);
6176   }
6177 
6178   unsigned getUncoveredArg() const {
6179     assert(hasUncoveredArg() && "no uncovered argument");
6180     return FirstUncoveredArg;
6181   }
6182 
6183   void setAllCovered() {
6184     // A string has been found with all arguments covered, so clear out
6185     // the diagnostics.
6186     DiagnosticExprs.clear();
6187     FirstUncoveredArg = AllCovered;
6188   }
6189 
6190   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6191     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6192 
6193     // Don't update if a previous string covers all arguments.
6194     if (FirstUncoveredArg == AllCovered)
6195       return;
6196 
6197     // UncoveredArgHandler tracks the highest uncovered argument index
6198     // and with it all the strings that match this index.
6199     if (NewFirstUncoveredArg == FirstUncoveredArg)
6200       DiagnosticExprs.push_back(StrExpr);
6201     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6202       DiagnosticExprs.clear();
6203       DiagnosticExprs.push_back(StrExpr);
6204       FirstUncoveredArg = NewFirstUncoveredArg;
6205     }
6206   }
6207 
6208   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6209 };
6210 
6211 enum StringLiteralCheckType {
6212   SLCT_NotALiteral,
6213   SLCT_UncheckedLiteral,
6214   SLCT_CheckedLiteral
6215 };
6216 
6217 } // namespace
6218 
6219 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6220                                      BinaryOperatorKind BinOpKind,
6221                                      bool AddendIsRight) {
6222   unsigned BitWidth = Offset.getBitWidth();
6223   unsigned AddendBitWidth = Addend.getBitWidth();
6224   // There might be negative interim results.
6225   if (Addend.isUnsigned()) {
6226     Addend = Addend.zext(++AddendBitWidth);
6227     Addend.setIsSigned(true);
6228   }
6229   // Adjust the bit width of the APSInts.
6230   if (AddendBitWidth > BitWidth) {
6231     Offset = Offset.sext(AddendBitWidth);
6232     BitWidth = AddendBitWidth;
6233   } else if (BitWidth > AddendBitWidth) {
6234     Addend = Addend.sext(BitWidth);
6235   }
6236 
6237   bool Ov = false;
6238   llvm::APSInt ResOffset = Offset;
6239   if (BinOpKind == BO_Add)
6240     ResOffset = Offset.sadd_ov(Addend, Ov);
6241   else {
6242     assert(AddendIsRight && BinOpKind == BO_Sub &&
6243            "operator must be add or sub with addend on the right");
6244     ResOffset = Offset.ssub_ov(Addend, Ov);
6245   }
6246 
6247   // We add an offset to a pointer here so we should support an offset as big as
6248   // possible.
6249   if (Ov) {
6250     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6251            "index (intermediate) result too big");
6252     Offset = Offset.sext(2 * BitWidth);
6253     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6254     return;
6255   }
6256 
6257   Offset = ResOffset;
6258 }
6259 
6260 namespace {
6261 
6262 // This is a wrapper class around StringLiteral to support offsetted string
6263 // literals as format strings. It takes the offset into account when returning
6264 // the string and its length or the source locations to display notes correctly.
6265 class FormatStringLiteral {
6266   const StringLiteral *FExpr;
6267   int64_t Offset;
6268 
6269  public:
6270   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6271       : FExpr(fexpr), Offset(Offset) {}
6272 
6273   StringRef getString() const {
6274     return FExpr->getString().drop_front(Offset);
6275   }
6276 
6277   unsigned getByteLength() const {
6278     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6279   }
6280 
6281   unsigned getLength() const { return FExpr->getLength() - Offset; }
6282   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6283 
6284   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6285 
6286   QualType getType() const { return FExpr->getType(); }
6287 
6288   bool isAscii() const { return FExpr->isAscii(); }
6289   bool isWide() const { return FExpr->isWide(); }
6290   bool isUTF8() const { return FExpr->isUTF8(); }
6291   bool isUTF16() const { return FExpr->isUTF16(); }
6292   bool isUTF32() const { return FExpr->isUTF32(); }
6293   bool isPascal() const { return FExpr->isPascal(); }
6294 
6295   SourceLocation getLocationOfByte(
6296       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6297       const TargetInfo &Target, unsigned *StartToken = nullptr,
6298       unsigned *StartTokenByteOffset = nullptr) const {
6299     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6300                                     StartToken, StartTokenByteOffset);
6301   }
6302 
6303   SourceLocation getBeginLoc() const LLVM_READONLY {
6304     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6305   }
6306 
6307   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6308 };
6309 
6310 }  // namespace
6311 
6312 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6313                               const Expr *OrigFormatExpr,
6314                               ArrayRef<const Expr *> Args,
6315                               bool HasVAListArg, unsigned format_idx,
6316                               unsigned firstDataArg,
6317                               Sema::FormatStringType Type,
6318                               bool inFunctionCall,
6319                               Sema::VariadicCallType CallType,
6320                               llvm::SmallBitVector &CheckedVarArgs,
6321                               UncoveredArgHandler &UncoveredArg);
6322 
6323 // Determine if an expression is a string literal or constant string.
6324 // If this function returns false on the arguments to a function expecting a
6325 // format string, we will usually need to emit a warning.
6326 // True string literals are then checked by CheckFormatString.
6327 static StringLiteralCheckType
6328 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6329                       bool HasVAListArg, unsigned format_idx,
6330                       unsigned firstDataArg, Sema::FormatStringType Type,
6331                       Sema::VariadicCallType CallType, bool InFunctionCall,
6332                       llvm::SmallBitVector &CheckedVarArgs,
6333                       UncoveredArgHandler &UncoveredArg,
6334                       llvm::APSInt Offset) {
6335  tryAgain:
6336   assert(Offset.isSigned() && "invalid offset");
6337 
6338   if (E->isTypeDependent() || E->isValueDependent())
6339     return SLCT_NotALiteral;
6340 
6341   E = E->IgnoreParenCasts();
6342 
6343   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6344     // Technically -Wformat-nonliteral does not warn about this case.
6345     // The behavior of printf and friends in this case is implementation
6346     // dependent.  Ideally if the format string cannot be null then
6347     // it should have a 'nonnull' attribute in the function prototype.
6348     return SLCT_UncheckedLiteral;
6349 
6350   switch (E->getStmtClass()) {
6351   case Stmt::BinaryConditionalOperatorClass:
6352   case Stmt::ConditionalOperatorClass: {
6353     // The expression is a literal if both sub-expressions were, and it was
6354     // completely checked only if both sub-expressions were checked.
6355     const AbstractConditionalOperator *C =
6356         cast<AbstractConditionalOperator>(E);
6357 
6358     // Determine whether it is necessary to check both sub-expressions, for
6359     // example, because the condition expression is a constant that can be
6360     // evaluated at compile time.
6361     bool CheckLeft = true, CheckRight = true;
6362 
6363     bool Cond;
6364     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6365       if (Cond)
6366         CheckRight = false;
6367       else
6368         CheckLeft = false;
6369     }
6370 
6371     // We need to maintain the offsets for the right and the left hand side
6372     // separately to check if every possible indexed expression is a valid
6373     // string literal. They might have different offsets for different string
6374     // literals in the end.
6375     StringLiteralCheckType Left;
6376     if (!CheckLeft)
6377       Left = SLCT_UncheckedLiteral;
6378     else {
6379       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6380                                    HasVAListArg, format_idx, firstDataArg,
6381                                    Type, CallType, InFunctionCall,
6382                                    CheckedVarArgs, UncoveredArg, Offset);
6383       if (Left == SLCT_NotALiteral || !CheckRight) {
6384         return Left;
6385       }
6386     }
6387 
6388     StringLiteralCheckType Right =
6389         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6390                               HasVAListArg, format_idx, firstDataArg,
6391                               Type, CallType, InFunctionCall, CheckedVarArgs,
6392                               UncoveredArg, Offset);
6393 
6394     return (CheckLeft && Left < Right) ? Left : Right;
6395   }
6396 
6397   case Stmt::ImplicitCastExprClass:
6398     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6399     goto tryAgain;
6400 
6401   case Stmt::OpaqueValueExprClass:
6402     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6403       E = src;
6404       goto tryAgain;
6405     }
6406     return SLCT_NotALiteral;
6407 
6408   case Stmt::PredefinedExprClass:
6409     // While __func__, etc., are technically not string literals, they
6410     // cannot contain format specifiers and thus are not a security
6411     // liability.
6412     return SLCT_UncheckedLiteral;
6413 
6414   case Stmt::DeclRefExprClass: {
6415     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6416 
6417     // As an exception, do not flag errors for variables binding to
6418     // const string literals.
6419     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6420       bool isConstant = false;
6421       QualType T = DR->getType();
6422 
6423       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6424         isConstant = AT->getElementType().isConstant(S.Context);
6425       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6426         isConstant = T.isConstant(S.Context) &&
6427                      PT->getPointeeType().isConstant(S.Context);
6428       } else if (T->isObjCObjectPointerType()) {
6429         // In ObjC, there is usually no "const ObjectPointer" type,
6430         // so don't check if the pointee type is constant.
6431         isConstant = T.isConstant(S.Context);
6432       }
6433 
6434       if (isConstant) {
6435         if (const Expr *Init = VD->getAnyInitializer()) {
6436           // Look through initializers like const char c[] = { "foo" }
6437           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6438             if (InitList->isStringLiteralInit())
6439               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6440           }
6441           return checkFormatStringExpr(S, Init, Args,
6442                                        HasVAListArg, format_idx,
6443                                        firstDataArg, Type, CallType,
6444                                        /*InFunctionCall*/ false, CheckedVarArgs,
6445                                        UncoveredArg, Offset);
6446         }
6447       }
6448 
6449       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6450       // special check to see if the format string is a function parameter
6451       // of the function calling the printf function.  If the function
6452       // has an attribute indicating it is a printf-like function, then we
6453       // should suppress warnings concerning non-literals being used in a call
6454       // to a vprintf function.  For example:
6455       //
6456       // void
6457       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6458       //      va_list ap;
6459       //      va_start(ap, fmt);
6460       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6461       //      ...
6462       // }
6463       if (HasVAListArg) {
6464         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6465           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6466             int PVIndex = PV->getFunctionScopeIndex() + 1;
6467             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6468               // adjust for implicit parameter
6469               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6470                 if (MD->isInstance())
6471                   ++PVIndex;
6472               // We also check if the formats are compatible.
6473               // We can't pass a 'scanf' string to a 'printf' function.
6474               if (PVIndex == PVFormat->getFormatIdx() &&
6475                   Type == S.GetFormatStringType(PVFormat))
6476                 return SLCT_UncheckedLiteral;
6477             }
6478           }
6479         }
6480       }
6481     }
6482 
6483     return SLCT_NotALiteral;
6484   }
6485 
6486   case Stmt::CallExprClass:
6487   case Stmt::CXXMemberCallExprClass: {
6488     const CallExpr *CE = cast<CallExpr>(E);
6489     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6490       bool IsFirst = true;
6491       StringLiteralCheckType CommonResult;
6492       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6493         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6494         StringLiteralCheckType Result = checkFormatStringExpr(
6495             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6496             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6497         if (IsFirst) {
6498           CommonResult = Result;
6499           IsFirst = false;
6500         }
6501       }
6502       if (!IsFirst)
6503         return CommonResult;
6504 
6505       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6506         unsigned BuiltinID = FD->getBuiltinID();
6507         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6508             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6509           const Expr *Arg = CE->getArg(0);
6510           return checkFormatStringExpr(S, Arg, Args,
6511                                        HasVAListArg, format_idx,
6512                                        firstDataArg, Type, CallType,
6513                                        InFunctionCall, CheckedVarArgs,
6514                                        UncoveredArg, Offset);
6515         }
6516       }
6517     }
6518 
6519     return SLCT_NotALiteral;
6520   }
6521   case Stmt::ObjCMessageExprClass: {
6522     const auto *ME = cast<ObjCMessageExpr>(E);
6523     if (const auto *ND = ME->getMethodDecl()) {
6524       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6525         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6526         return checkFormatStringExpr(
6527             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6528             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6529       }
6530     }
6531 
6532     return SLCT_NotALiteral;
6533   }
6534   case Stmt::ObjCStringLiteralClass:
6535   case Stmt::StringLiteralClass: {
6536     const StringLiteral *StrE = nullptr;
6537 
6538     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6539       StrE = ObjCFExpr->getString();
6540     else
6541       StrE = cast<StringLiteral>(E);
6542 
6543     if (StrE) {
6544       if (Offset.isNegative() || Offset > StrE->getLength()) {
6545         // TODO: It would be better to have an explicit warning for out of
6546         // bounds literals.
6547         return SLCT_NotALiteral;
6548       }
6549       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6550       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6551                         firstDataArg, Type, InFunctionCall, CallType,
6552                         CheckedVarArgs, UncoveredArg);
6553       return SLCT_CheckedLiteral;
6554     }
6555 
6556     return SLCT_NotALiteral;
6557   }
6558   case Stmt::BinaryOperatorClass: {
6559     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6560 
6561     // A string literal + an int offset is still a string literal.
6562     if (BinOp->isAdditiveOp()) {
6563       Expr::EvalResult LResult, RResult;
6564 
6565       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6566       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6567 
6568       if (LIsInt != RIsInt) {
6569         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6570 
6571         if (LIsInt) {
6572           if (BinOpKind == BO_Add) {
6573             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6574             E = BinOp->getRHS();
6575             goto tryAgain;
6576           }
6577         } else {
6578           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6579           E = BinOp->getLHS();
6580           goto tryAgain;
6581         }
6582       }
6583     }
6584 
6585     return SLCT_NotALiteral;
6586   }
6587   case Stmt::UnaryOperatorClass: {
6588     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6589     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6590     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6591       Expr::EvalResult IndexResult;
6592       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6593         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6594                    /*RHS is int*/ true);
6595         E = ASE->getBase();
6596         goto tryAgain;
6597       }
6598     }
6599 
6600     return SLCT_NotALiteral;
6601   }
6602 
6603   default:
6604     return SLCT_NotALiteral;
6605   }
6606 }
6607 
6608 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6609   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6610       .Case("scanf", FST_Scanf)
6611       .Cases("printf", "printf0", FST_Printf)
6612       .Cases("NSString", "CFString", FST_NSString)
6613       .Case("strftime", FST_Strftime)
6614       .Case("strfmon", FST_Strfmon)
6615       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6616       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6617       .Case("os_trace", FST_OSLog)
6618       .Case("os_log", FST_OSLog)
6619       .Default(FST_Unknown);
6620 }
6621 
6622 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6623 /// functions) for correct use of format strings.
6624 /// Returns true if a format string has been fully checked.
6625 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6626                                 ArrayRef<const Expr *> Args,
6627                                 bool IsCXXMember,
6628                                 VariadicCallType CallType,
6629                                 SourceLocation Loc, SourceRange Range,
6630                                 llvm::SmallBitVector &CheckedVarArgs) {
6631   FormatStringInfo FSI;
6632   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6633     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6634                                 FSI.FirstDataArg, GetFormatStringType(Format),
6635                                 CallType, Loc, Range, CheckedVarArgs);
6636   return false;
6637 }
6638 
6639 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6640                                 bool HasVAListArg, unsigned format_idx,
6641                                 unsigned firstDataArg, FormatStringType Type,
6642                                 VariadicCallType CallType,
6643                                 SourceLocation Loc, SourceRange Range,
6644                                 llvm::SmallBitVector &CheckedVarArgs) {
6645   // CHECK: printf/scanf-like function is called with no format string.
6646   if (format_idx >= Args.size()) {
6647     Diag(Loc, diag::warn_missing_format_string) << Range;
6648     return false;
6649   }
6650 
6651   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6652 
6653   // CHECK: format string is not a string literal.
6654   //
6655   // Dynamically generated format strings are difficult to
6656   // automatically vet at compile time.  Requiring that format strings
6657   // are string literals: (1) permits the checking of format strings by
6658   // the compiler and thereby (2) can practically remove the source of
6659   // many format string exploits.
6660 
6661   // Format string can be either ObjC string (e.g. @"%d") or
6662   // C string (e.g. "%d")
6663   // ObjC string uses the same format specifiers as C string, so we can use
6664   // the same format string checking logic for both ObjC and C strings.
6665   UncoveredArgHandler UncoveredArg;
6666   StringLiteralCheckType CT =
6667       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6668                             format_idx, firstDataArg, Type, CallType,
6669                             /*IsFunctionCall*/ true, CheckedVarArgs,
6670                             UncoveredArg,
6671                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6672 
6673   // Generate a diagnostic where an uncovered argument is detected.
6674   if (UncoveredArg.hasUncoveredArg()) {
6675     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6676     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6677     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6678   }
6679 
6680   if (CT != SLCT_NotALiteral)
6681     // Literal format string found, check done!
6682     return CT == SLCT_CheckedLiteral;
6683 
6684   // Strftime is particular as it always uses a single 'time' argument,
6685   // so it is safe to pass a non-literal string.
6686   if (Type == FST_Strftime)
6687     return false;
6688 
6689   // Do not emit diag when the string param is a macro expansion and the
6690   // format is either NSString or CFString. This is a hack to prevent
6691   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6692   // which are usually used in place of NS and CF string literals.
6693   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6694   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6695     return false;
6696 
6697   // If there are no arguments specified, warn with -Wformat-security, otherwise
6698   // warn only with -Wformat-nonliteral.
6699   if (Args.size() == firstDataArg) {
6700     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6701       << OrigFormatExpr->getSourceRange();
6702     switch (Type) {
6703     default:
6704       break;
6705     case FST_Kprintf:
6706     case FST_FreeBSDKPrintf:
6707     case FST_Printf:
6708       Diag(FormatLoc, diag::note_format_security_fixit)
6709         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6710       break;
6711     case FST_NSString:
6712       Diag(FormatLoc, diag::note_format_security_fixit)
6713         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6714       break;
6715     }
6716   } else {
6717     Diag(FormatLoc, diag::warn_format_nonliteral)
6718       << OrigFormatExpr->getSourceRange();
6719   }
6720   return false;
6721 }
6722 
6723 namespace {
6724 
6725 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6726 protected:
6727   Sema &S;
6728   const FormatStringLiteral *FExpr;
6729   const Expr *OrigFormatExpr;
6730   const Sema::FormatStringType FSType;
6731   const unsigned FirstDataArg;
6732   const unsigned NumDataArgs;
6733   const char *Beg; // Start of format string.
6734   const bool HasVAListArg;
6735   ArrayRef<const Expr *> Args;
6736   unsigned FormatIdx;
6737   llvm::SmallBitVector CoveredArgs;
6738   bool usesPositionalArgs = false;
6739   bool atFirstArg = true;
6740   bool inFunctionCall;
6741   Sema::VariadicCallType CallType;
6742   llvm::SmallBitVector &CheckedVarArgs;
6743   UncoveredArgHandler &UncoveredArg;
6744 
6745 public:
6746   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6747                      const Expr *origFormatExpr,
6748                      const Sema::FormatStringType type, unsigned firstDataArg,
6749                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6750                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6751                      bool inFunctionCall, Sema::VariadicCallType callType,
6752                      llvm::SmallBitVector &CheckedVarArgs,
6753                      UncoveredArgHandler &UncoveredArg)
6754       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6755         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6756         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6757         inFunctionCall(inFunctionCall), CallType(callType),
6758         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6759     CoveredArgs.resize(numDataArgs);
6760     CoveredArgs.reset();
6761   }
6762 
6763   void DoneProcessing();
6764 
6765   void HandleIncompleteSpecifier(const char *startSpecifier,
6766                                  unsigned specifierLen) override;
6767 
6768   void HandleInvalidLengthModifier(
6769                            const analyze_format_string::FormatSpecifier &FS,
6770                            const analyze_format_string::ConversionSpecifier &CS,
6771                            const char *startSpecifier, unsigned specifierLen,
6772                            unsigned DiagID);
6773 
6774   void HandleNonStandardLengthModifier(
6775                     const analyze_format_string::FormatSpecifier &FS,
6776                     const char *startSpecifier, unsigned specifierLen);
6777 
6778   void HandleNonStandardConversionSpecifier(
6779                     const analyze_format_string::ConversionSpecifier &CS,
6780                     const char *startSpecifier, unsigned specifierLen);
6781 
6782   void HandlePosition(const char *startPos, unsigned posLen) override;
6783 
6784   void HandleInvalidPosition(const char *startSpecifier,
6785                              unsigned specifierLen,
6786                              analyze_format_string::PositionContext p) override;
6787 
6788   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6789 
6790   void HandleNullChar(const char *nullCharacter) override;
6791 
6792   template <typename Range>
6793   static void
6794   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6795                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6796                        bool IsStringLocation, Range StringRange,
6797                        ArrayRef<FixItHint> Fixit = None);
6798 
6799 protected:
6800   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6801                                         const char *startSpec,
6802                                         unsigned specifierLen,
6803                                         const char *csStart, unsigned csLen);
6804 
6805   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6806                                          const char *startSpec,
6807                                          unsigned specifierLen);
6808 
6809   SourceRange getFormatStringRange();
6810   CharSourceRange getSpecifierRange(const char *startSpecifier,
6811                                     unsigned specifierLen);
6812   SourceLocation getLocationOfByte(const char *x);
6813 
6814   const Expr *getDataArg(unsigned i) const;
6815 
6816   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6817                     const analyze_format_string::ConversionSpecifier &CS,
6818                     const char *startSpecifier, unsigned specifierLen,
6819                     unsigned argIndex);
6820 
6821   template <typename Range>
6822   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6823                             bool IsStringLocation, Range StringRange,
6824                             ArrayRef<FixItHint> Fixit = None);
6825 };
6826 
6827 } // namespace
6828 
6829 SourceRange CheckFormatHandler::getFormatStringRange() {
6830   return OrigFormatExpr->getSourceRange();
6831 }
6832 
6833 CharSourceRange CheckFormatHandler::
6834 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6835   SourceLocation Start = getLocationOfByte(startSpecifier);
6836   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6837 
6838   // Advance the end SourceLocation by one due to half-open ranges.
6839   End = End.getLocWithOffset(1);
6840 
6841   return CharSourceRange::getCharRange(Start, End);
6842 }
6843 
6844 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6845   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6846                                   S.getLangOpts(), S.Context.getTargetInfo());
6847 }
6848 
6849 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6850                                                    unsigned specifierLen){
6851   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6852                        getLocationOfByte(startSpecifier),
6853                        /*IsStringLocation*/true,
6854                        getSpecifierRange(startSpecifier, specifierLen));
6855 }
6856 
6857 void CheckFormatHandler::HandleInvalidLengthModifier(
6858     const analyze_format_string::FormatSpecifier &FS,
6859     const analyze_format_string::ConversionSpecifier &CS,
6860     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6861   using namespace analyze_format_string;
6862 
6863   const LengthModifier &LM = FS.getLengthModifier();
6864   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6865 
6866   // See if we know how to fix this length modifier.
6867   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6868   if (FixedLM) {
6869     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6870                          getLocationOfByte(LM.getStart()),
6871                          /*IsStringLocation*/true,
6872                          getSpecifierRange(startSpecifier, specifierLen));
6873 
6874     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6875       << FixedLM->toString()
6876       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6877 
6878   } else {
6879     FixItHint Hint;
6880     if (DiagID == diag::warn_format_nonsensical_length)
6881       Hint = FixItHint::CreateRemoval(LMRange);
6882 
6883     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6884                          getLocationOfByte(LM.getStart()),
6885                          /*IsStringLocation*/true,
6886                          getSpecifierRange(startSpecifier, specifierLen),
6887                          Hint);
6888   }
6889 }
6890 
6891 void CheckFormatHandler::HandleNonStandardLengthModifier(
6892     const analyze_format_string::FormatSpecifier &FS,
6893     const char *startSpecifier, unsigned specifierLen) {
6894   using namespace analyze_format_string;
6895 
6896   const LengthModifier &LM = FS.getLengthModifier();
6897   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6898 
6899   // See if we know how to fix this length modifier.
6900   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6901   if (FixedLM) {
6902     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6903                            << LM.toString() << 0,
6904                          getLocationOfByte(LM.getStart()),
6905                          /*IsStringLocation*/true,
6906                          getSpecifierRange(startSpecifier, specifierLen));
6907 
6908     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6909       << FixedLM->toString()
6910       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6911 
6912   } else {
6913     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6914                            << LM.toString() << 0,
6915                          getLocationOfByte(LM.getStart()),
6916                          /*IsStringLocation*/true,
6917                          getSpecifierRange(startSpecifier, specifierLen));
6918   }
6919 }
6920 
6921 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6922     const analyze_format_string::ConversionSpecifier &CS,
6923     const char *startSpecifier, unsigned specifierLen) {
6924   using namespace analyze_format_string;
6925 
6926   // See if we know how to fix this conversion specifier.
6927   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6928   if (FixedCS) {
6929     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6930                           << CS.toString() << /*conversion specifier*/1,
6931                          getLocationOfByte(CS.getStart()),
6932                          /*IsStringLocation*/true,
6933                          getSpecifierRange(startSpecifier, specifierLen));
6934 
6935     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6936     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6937       << FixedCS->toString()
6938       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6939   } else {
6940     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6941                           << CS.toString() << /*conversion specifier*/1,
6942                          getLocationOfByte(CS.getStart()),
6943                          /*IsStringLocation*/true,
6944                          getSpecifierRange(startSpecifier, specifierLen));
6945   }
6946 }
6947 
6948 void CheckFormatHandler::HandlePosition(const char *startPos,
6949                                         unsigned posLen) {
6950   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6951                                getLocationOfByte(startPos),
6952                                /*IsStringLocation*/true,
6953                                getSpecifierRange(startPos, posLen));
6954 }
6955 
6956 void
6957 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6958                                      analyze_format_string::PositionContext p) {
6959   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6960                          << (unsigned) p,
6961                        getLocationOfByte(startPos), /*IsStringLocation*/true,
6962                        getSpecifierRange(startPos, posLen));
6963 }
6964 
6965 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6966                                             unsigned posLen) {
6967   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6968                                getLocationOfByte(startPos),
6969                                /*IsStringLocation*/true,
6970                                getSpecifierRange(startPos, posLen));
6971 }
6972 
6973 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6974   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6975     // The presence of a null character is likely an error.
6976     EmitFormatDiagnostic(
6977       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6978       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6979       getFormatStringRange());
6980   }
6981 }
6982 
6983 // Note that this may return NULL if there was an error parsing or building
6984 // one of the argument expressions.
6985 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6986   return Args[FirstDataArg + i];
6987 }
6988 
6989 void CheckFormatHandler::DoneProcessing() {
6990   // Does the number of data arguments exceed the number of
6991   // format conversions in the format string?
6992   if (!HasVAListArg) {
6993       // Find any arguments that weren't covered.
6994     CoveredArgs.flip();
6995     signed notCoveredArg = CoveredArgs.find_first();
6996     if (notCoveredArg >= 0) {
6997       assert((unsigned)notCoveredArg < NumDataArgs);
6998       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6999     } else {
7000       UncoveredArg.setAllCovered();
7001     }
7002   }
7003 }
7004 
7005 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7006                                    const Expr *ArgExpr) {
7007   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7008          "Invalid state");
7009 
7010   if (!ArgExpr)
7011     return;
7012 
7013   SourceLocation Loc = ArgExpr->getBeginLoc();
7014 
7015   if (S.getSourceManager().isInSystemMacro(Loc))
7016     return;
7017 
7018   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7019   for (auto E : DiagnosticExprs)
7020     PDiag << E->getSourceRange();
7021 
7022   CheckFormatHandler::EmitFormatDiagnostic(
7023                                   S, IsFunctionCall, DiagnosticExprs[0],
7024                                   PDiag, Loc, /*IsStringLocation*/false,
7025                                   DiagnosticExprs[0]->getSourceRange());
7026 }
7027 
7028 bool
7029 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7030                                                      SourceLocation Loc,
7031                                                      const char *startSpec,
7032                                                      unsigned specifierLen,
7033                                                      const char *csStart,
7034                                                      unsigned csLen) {
7035   bool keepGoing = true;
7036   if (argIndex < NumDataArgs) {
7037     // Consider the argument coverered, even though the specifier doesn't
7038     // make sense.
7039     CoveredArgs.set(argIndex);
7040   }
7041   else {
7042     // If argIndex exceeds the number of data arguments we
7043     // don't issue a warning because that is just a cascade of warnings (and
7044     // they may have intended '%%' anyway). We don't want to continue processing
7045     // the format string after this point, however, as we will like just get
7046     // gibberish when trying to match arguments.
7047     keepGoing = false;
7048   }
7049 
7050   StringRef Specifier(csStart, csLen);
7051 
7052   // If the specifier in non-printable, it could be the first byte of a UTF-8
7053   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7054   // hex value.
7055   std::string CodePointStr;
7056   if (!llvm::sys::locale::isPrint(*csStart)) {
7057     llvm::UTF32 CodePoint;
7058     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7059     const llvm::UTF8 *E =
7060         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7061     llvm::ConversionResult Result =
7062         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7063 
7064     if (Result != llvm::conversionOK) {
7065       unsigned char FirstChar = *csStart;
7066       CodePoint = (llvm::UTF32)FirstChar;
7067     }
7068 
7069     llvm::raw_string_ostream OS(CodePointStr);
7070     if (CodePoint < 256)
7071       OS << "\\x" << llvm::format("%02x", CodePoint);
7072     else if (CodePoint <= 0xFFFF)
7073       OS << "\\u" << llvm::format("%04x", CodePoint);
7074     else
7075       OS << "\\U" << llvm::format("%08x", CodePoint);
7076     OS.flush();
7077     Specifier = CodePointStr;
7078   }
7079 
7080   EmitFormatDiagnostic(
7081       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7082       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7083 
7084   return keepGoing;
7085 }
7086 
7087 void
7088 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7089                                                       const char *startSpec,
7090                                                       unsigned specifierLen) {
7091   EmitFormatDiagnostic(
7092     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7093     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7094 }
7095 
7096 bool
7097 CheckFormatHandler::CheckNumArgs(
7098   const analyze_format_string::FormatSpecifier &FS,
7099   const analyze_format_string::ConversionSpecifier &CS,
7100   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7101 
7102   if (argIndex >= NumDataArgs) {
7103     PartialDiagnostic PDiag = FS.usesPositionalArg()
7104       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7105            << (argIndex+1) << NumDataArgs)
7106       : S.PDiag(diag::warn_printf_insufficient_data_args);
7107     EmitFormatDiagnostic(
7108       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7109       getSpecifierRange(startSpecifier, specifierLen));
7110 
7111     // Since more arguments than conversion tokens are given, by extension
7112     // all arguments are covered, so mark this as so.
7113     UncoveredArg.setAllCovered();
7114     return false;
7115   }
7116   return true;
7117 }
7118 
7119 template<typename Range>
7120 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7121                                               SourceLocation Loc,
7122                                               bool IsStringLocation,
7123                                               Range StringRange,
7124                                               ArrayRef<FixItHint> FixIt) {
7125   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7126                        Loc, IsStringLocation, StringRange, FixIt);
7127 }
7128 
7129 /// If the format string is not within the function call, emit a note
7130 /// so that the function call and string are in diagnostic messages.
7131 ///
7132 /// \param InFunctionCall if true, the format string is within the function
7133 /// call and only one diagnostic message will be produced.  Otherwise, an
7134 /// extra note will be emitted pointing to location of the format string.
7135 ///
7136 /// \param ArgumentExpr the expression that is passed as the format string
7137 /// argument in the function call.  Used for getting locations when two
7138 /// diagnostics are emitted.
7139 ///
7140 /// \param PDiag the callee should already have provided any strings for the
7141 /// diagnostic message.  This function only adds locations and fixits
7142 /// to diagnostics.
7143 ///
7144 /// \param Loc primary location for diagnostic.  If two diagnostics are
7145 /// required, one will be at Loc and a new SourceLocation will be created for
7146 /// the other one.
7147 ///
7148 /// \param IsStringLocation if true, Loc points to the format string should be
7149 /// used for the note.  Otherwise, Loc points to the argument list and will
7150 /// be used with PDiag.
7151 ///
7152 /// \param StringRange some or all of the string to highlight.  This is
7153 /// templated so it can accept either a CharSourceRange or a SourceRange.
7154 ///
7155 /// \param FixIt optional fix it hint for the format string.
7156 template <typename Range>
7157 void CheckFormatHandler::EmitFormatDiagnostic(
7158     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7159     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7160     Range StringRange, ArrayRef<FixItHint> FixIt) {
7161   if (InFunctionCall) {
7162     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7163     D << StringRange;
7164     D << FixIt;
7165   } else {
7166     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7167       << ArgumentExpr->getSourceRange();
7168 
7169     const Sema::SemaDiagnosticBuilder &Note =
7170       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7171              diag::note_format_string_defined);
7172 
7173     Note << StringRange;
7174     Note << FixIt;
7175   }
7176 }
7177 
7178 //===--- CHECK: Printf format string checking ------------------------------===//
7179 
7180 namespace {
7181 
7182 class CheckPrintfHandler : public CheckFormatHandler {
7183 public:
7184   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7185                      const Expr *origFormatExpr,
7186                      const Sema::FormatStringType type, unsigned firstDataArg,
7187                      unsigned numDataArgs, bool isObjC, const char *beg,
7188                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7189                      unsigned formatIdx, bool inFunctionCall,
7190                      Sema::VariadicCallType CallType,
7191                      llvm::SmallBitVector &CheckedVarArgs,
7192                      UncoveredArgHandler &UncoveredArg)
7193       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7194                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7195                            inFunctionCall, CallType, CheckedVarArgs,
7196                            UncoveredArg) {}
7197 
7198   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7199 
7200   /// Returns true if '%@' specifiers are allowed in the format string.
7201   bool allowsObjCArg() const {
7202     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7203            FSType == Sema::FST_OSTrace;
7204   }
7205 
7206   bool HandleInvalidPrintfConversionSpecifier(
7207                                       const analyze_printf::PrintfSpecifier &FS,
7208                                       const char *startSpecifier,
7209                                       unsigned specifierLen) override;
7210 
7211   void handleInvalidMaskType(StringRef MaskType) override;
7212 
7213   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7214                              const char *startSpecifier,
7215                              unsigned specifierLen) override;
7216   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7217                        const char *StartSpecifier,
7218                        unsigned SpecifierLen,
7219                        const Expr *E);
7220 
7221   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7222                     const char *startSpecifier, unsigned specifierLen);
7223   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7224                            const analyze_printf::OptionalAmount &Amt,
7225                            unsigned type,
7226                            const char *startSpecifier, unsigned specifierLen);
7227   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7228                   const analyze_printf::OptionalFlag &flag,
7229                   const char *startSpecifier, unsigned specifierLen);
7230   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7231                          const analyze_printf::OptionalFlag &ignoredFlag,
7232                          const analyze_printf::OptionalFlag &flag,
7233                          const char *startSpecifier, unsigned specifierLen);
7234   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7235                            const Expr *E);
7236 
7237   void HandleEmptyObjCModifierFlag(const char *startFlag,
7238                                    unsigned flagLen) override;
7239 
7240   void HandleInvalidObjCModifierFlag(const char *startFlag,
7241                                             unsigned flagLen) override;
7242 
7243   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7244                                            const char *flagsEnd,
7245                                            const char *conversionPosition)
7246                                              override;
7247 };
7248 
7249 } // namespace
7250 
7251 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7252                                       const analyze_printf::PrintfSpecifier &FS,
7253                                       const char *startSpecifier,
7254                                       unsigned specifierLen) {
7255   const analyze_printf::PrintfConversionSpecifier &CS =
7256     FS.getConversionSpecifier();
7257 
7258   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7259                                           getLocationOfByte(CS.getStart()),
7260                                           startSpecifier, specifierLen,
7261                                           CS.getStart(), CS.getLength());
7262 }
7263 
7264 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7265   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7266 }
7267 
7268 bool CheckPrintfHandler::HandleAmount(
7269                                const analyze_format_string::OptionalAmount &Amt,
7270                                unsigned k, const char *startSpecifier,
7271                                unsigned specifierLen) {
7272   if (Amt.hasDataArgument()) {
7273     if (!HasVAListArg) {
7274       unsigned argIndex = Amt.getArgIndex();
7275       if (argIndex >= NumDataArgs) {
7276         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7277                                << k,
7278                              getLocationOfByte(Amt.getStart()),
7279                              /*IsStringLocation*/true,
7280                              getSpecifierRange(startSpecifier, specifierLen));
7281         // Don't do any more checking.  We will just emit
7282         // spurious errors.
7283         return false;
7284       }
7285 
7286       // Type check the data argument.  It should be an 'int'.
7287       // Although not in conformance with C99, we also allow the argument to be
7288       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7289       // doesn't emit a warning for that case.
7290       CoveredArgs.set(argIndex);
7291       const Expr *Arg = getDataArg(argIndex);
7292       if (!Arg)
7293         return false;
7294 
7295       QualType T = Arg->getType();
7296 
7297       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7298       assert(AT.isValid());
7299 
7300       if (!AT.matchesType(S.Context, T)) {
7301         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7302                                << k << AT.getRepresentativeTypeName(S.Context)
7303                                << T << Arg->getSourceRange(),
7304                              getLocationOfByte(Amt.getStart()),
7305                              /*IsStringLocation*/true,
7306                              getSpecifierRange(startSpecifier, specifierLen));
7307         // Don't do any more checking.  We will just emit
7308         // spurious errors.
7309         return false;
7310       }
7311     }
7312   }
7313   return true;
7314 }
7315 
7316 void CheckPrintfHandler::HandleInvalidAmount(
7317                                       const analyze_printf::PrintfSpecifier &FS,
7318                                       const analyze_printf::OptionalAmount &Amt,
7319                                       unsigned type,
7320                                       const char *startSpecifier,
7321                                       unsigned specifierLen) {
7322   const analyze_printf::PrintfConversionSpecifier &CS =
7323     FS.getConversionSpecifier();
7324 
7325   FixItHint fixit =
7326     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7327       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7328                                  Amt.getConstantLength()))
7329       : FixItHint();
7330 
7331   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7332                          << type << CS.toString(),
7333                        getLocationOfByte(Amt.getStart()),
7334                        /*IsStringLocation*/true,
7335                        getSpecifierRange(startSpecifier, specifierLen),
7336                        fixit);
7337 }
7338 
7339 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7340                                     const analyze_printf::OptionalFlag &flag,
7341                                     const char *startSpecifier,
7342                                     unsigned specifierLen) {
7343   // Warn about pointless flag with a fixit removal.
7344   const analyze_printf::PrintfConversionSpecifier &CS =
7345     FS.getConversionSpecifier();
7346   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7347                          << flag.toString() << CS.toString(),
7348                        getLocationOfByte(flag.getPosition()),
7349                        /*IsStringLocation*/true,
7350                        getSpecifierRange(startSpecifier, specifierLen),
7351                        FixItHint::CreateRemoval(
7352                          getSpecifierRange(flag.getPosition(), 1)));
7353 }
7354 
7355 void CheckPrintfHandler::HandleIgnoredFlag(
7356                                 const analyze_printf::PrintfSpecifier &FS,
7357                                 const analyze_printf::OptionalFlag &ignoredFlag,
7358                                 const analyze_printf::OptionalFlag &flag,
7359                                 const char *startSpecifier,
7360                                 unsigned specifierLen) {
7361   // Warn about ignored flag with a fixit removal.
7362   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7363                          << ignoredFlag.toString() << flag.toString(),
7364                        getLocationOfByte(ignoredFlag.getPosition()),
7365                        /*IsStringLocation*/true,
7366                        getSpecifierRange(startSpecifier, specifierLen),
7367                        FixItHint::CreateRemoval(
7368                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7369 }
7370 
7371 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7372                                                      unsigned flagLen) {
7373   // Warn about an empty flag.
7374   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7375                        getLocationOfByte(startFlag),
7376                        /*IsStringLocation*/true,
7377                        getSpecifierRange(startFlag, flagLen));
7378 }
7379 
7380 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7381                                                        unsigned flagLen) {
7382   // Warn about an invalid flag.
7383   auto Range = getSpecifierRange(startFlag, flagLen);
7384   StringRef flag(startFlag, flagLen);
7385   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7386                       getLocationOfByte(startFlag),
7387                       /*IsStringLocation*/true,
7388                       Range, FixItHint::CreateRemoval(Range));
7389 }
7390 
7391 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7392     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7393     // Warn about using '[...]' without a '@' conversion.
7394     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7395     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7396     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7397                          getLocationOfByte(conversionPosition),
7398                          /*IsStringLocation*/true,
7399                          Range, FixItHint::CreateRemoval(Range));
7400 }
7401 
7402 // Determines if the specified is a C++ class or struct containing
7403 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7404 // "c_str()").
7405 template<typename MemberKind>
7406 static llvm::SmallPtrSet<MemberKind*, 1>
7407 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7408   const RecordType *RT = Ty->getAs<RecordType>();
7409   llvm::SmallPtrSet<MemberKind*, 1> Results;
7410 
7411   if (!RT)
7412     return Results;
7413   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7414   if (!RD || !RD->getDefinition())
7415     return Results;
7416 
7417   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7418                  Sema::LookupMemberName);
7419   R.suppressDiagnostics();
7420 
7421   // We just need to include all members of the right kind turned up by the
7422   // filter, at this point.
7423   if (S.LookupQualifiedName(R, RT->getDecl()))
7424     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7425       NamedDecl *decl = (*I)->getUnderlyingDecl();
7426       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7427         Results.insert(FK);
7428     }
7429   return Results;
7430 }
7431 
7432 /// Check if we could call '.c_str()' on an object.
7433 ///
7434 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7435 /// allow the call, or if it would be ambiguous).
7436 bool Sema::hasCStrMethod(const Expr *E) {
7437   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7438 
7439   MethodSet Results =
7440       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7441   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7442        MI != ME; ++MI)
7443     if ((*MI)->getMinRequiredArguments() == 0)
7444       return true;
7445   return false;
7446 }
7447 
7448 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7449 // better diagnostic if so. AT is assumed to be valid.
7450 // Returns true when a c_str() conversion method is found.
7451 bool CheckPrintfHandler::checkForCStrMembers(
7452     const analyze_printf::ArgType &AT, const Expr *E) {
7453   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7454 
7455   MethodSet Results =
7456       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7457 
7458   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7459        MI != ME; ++MI) {
7460     const CXXMethodDecl *Method = *MI;
7461     if (Method->getMinRequiredArguments() == 0 &&
7462         AT.matchesType(S.Context, Method->getReturnType())) {
7463       // FIXME: Suggest parens if the expression needs them.
7464       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7465       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7466           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7467       return true;
7468     }
7469   }
7470 
7471   return false;
7472 }
7473 
7474 bool
7475 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7476                                             &FS,
7477                                           const char *startSpecifier,
7478                                           unsigned specifierLen) {
7479   using namespace analyze_format_string;
7480   using namespace analyze_printf;
7481 
7482   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7483 
7484   if (FS.consumesDataArgument()) {
7485     if (atFirstArg) {
7486         atFirstArg = false;
7487         usesPositionalArgs = FS.usesPositionalArg();
7488     }
7489     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7490       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7491                                         startSpecifier, specifierLen);
7492       return false;
7493     }
7494   }
7495 
7496   // First check if the field width, precision, and conversion specifier
7497   // have matching data arguments.
7498   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7499                     startSpecifier, specifierLen)) {
7500     return false;
7501   }
7502 
7503   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7504                     startSpecifier, specifierLen)) {
7505     return false;
7506   }
7507 
7508   if (!CS.consumesDataArgument()) {
7509     // FIXME: Technically specifying a precision or field width here
7510     // makes no sense.  Worth issuing a warning at some point.
7511     return true;
7512   }
7513 
7514   // Consume the argument.
7515   unsigned argIndex = FS.getArgIndex();
7516   if (argIndex < NumDataArgs) {
7517     // The check to see if the argIndex is valid will come later.
7518     // We set the bit here because we may exit early from this
7519     // function if we encounter some other error.
7520     CoveredArgs.set(argIndex);
7521   }
7522 
7523   // FreeBSD kernel extensions.
7524   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7525       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7526     // We need at least two arguments.
7527     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7528       return false;
7529 
7530     // Claim the second argument.
7531     CoveredArgs.set(argIndex + 1);
7532 
7533     // Type check the first argument (int for %b, pointer for %D)
7534     const Expr *Ex = getDataArg(argIndex);
7535     const analyze_printf::ArgType &AT =
7536       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7537         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7538     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7539       EmitFormatDiagnostic(
7540           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7541               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7542               << false << Ex->getSourceRange(),
7543           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7544           getSpecifierRange(startSpecifier, specifierLen));
7545 
7546     // Type check the second argument (char * for both %b and %D)
7547     Ex = getDataArg(argIndex + 1);
7548     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7549     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7550       EmitFormatDiagnostic(
7551           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7552               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7553               << false << Ex->getSourceRange(),
7554           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7555           getSpecifierRange(startSpecifier, specifierLen));
7556 
7557      return true;
7558   }
7559 
7560   // Check for using an Objective-C specific conversion specifier
7561   // in a non-ObjC literal.
7562   if (!allowsObjCArg() && CS.isObjCArg()) {
7563     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7564                                                   specifierLen);
7565   }
7566 
7567   // %P can only be used with os_log.
7568   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7569     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7570                                                   specifierLen);
7571   }
7572 
7573   // %n is not allowed with os_log.
7574   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7575     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7576                          getLocationOfByte(CS.getStart()),
7577                          /*IsStringLocation*/ false,
7578                          getSpecifierRange(startSpecifier, specifierLen));
7579 
7580     return true;
7581   }
7582 
7583   // Only scalars are allowed for os_trace.
7584   if (FSType == Sema::FST_OSTrace &&
7585       (CS.getKind() == ConversionSpecifier::PArg ||
7586        CS.getKind() == ConversionSpecifier::sArg ||
7587        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7588     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7589                                                   specifierLen);
7590   }
7591 
7592   // Check for use of public/private annotation outside of os_log().
7593   if (FSType != Sema::FST_OSLog) {
7594     if (FS.isPublic().isSet()) {
7595       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7596                                << "public",
7597                            getLocationOfByte(FS.isPublic().getPosition()),
7598                            /*IsStringLocation*/ false,
7599                            getSpecifierRange(startSpecifier, specifierLen));
7600     }
7601     if (FS.isPrivate().isSet()) {
7602       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7603                                << "private",
7604                            getLocationOfByte(FS.isPrivate().getPosition()),
7605                            /*IsStringLocation*/ false,
7606                            getSpecifierRange(startSpecifier, specifierLen));
7607     }
7608   }
7609 
7610   // Check for invalid use of field width
7611   if (!FS.hasValidFieldWidth()) {
7612     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7613         startSpecifier, specifierLen);
7614   }
7615 
7616   // Check for invalid use of precision
7617   if (!FS.hasValidPrecision()) {
7618     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7619         startSpecifier, specifierLen);
7620   }
7621 
7622   // Precision is mandatory for %P specifier.
7623   if (CS.getKind() == ConversionSpecifier::PArg &&
7624       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7625     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7626                          getLocationOfByte(startSpecifier),
7627                          /*IsStringLocation*/ false,
7628                          getSpecifierRange(startSpecifier, specifierLen));
7629   }
7630 
7631   // Check each flag does not conflict with any other component.
7632   if (!FS.hasValidThousandsGroupingPrefix())
7633     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7634   if (!FS.hasValidLeadingZeros())
7635     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7636   if (!FS.hasValidPlusPrefix())
7637     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7638   if (!FS.hasValidSpacePrefix())
7639     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7640   if (!FS.hasValidAlternativeForm())
7641     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7642   if (!FS.hasValidLeftJustified())
7643     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7644 
7645   // Check that flags are not ignored by another flag
7646   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7647     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7648         startSpecifier, specifierLen);
7649   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7650     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7651             startSpecifier, specifierLen);
7652 
7653   // Check the length modifier is valid with the given conversion specifier.
7654   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7655                                  S.getLangOpts()))
7656     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7657                                 diag::warn_format_nonsensical_length);
7658   else if (!FS.hasStandardLengthModifier())
7659     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7660   else if (!FS.hasStandardLengthConversionCombination())
7661     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7662                                 diag::warn_format_non_standard_conversion_spec);
7663 
7664   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7665     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7666 
7667   // The remaining checks depend on the data arguments.
7668   if (HasVAListArg)
7669     return true;
7670 
7671   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7672     return false;
7673 
7674   const Expr *Arg = getDataArg(argIndex);
7675   if (!Arg)
7676     return true;
7677 
7678   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7679 }
7680 
7681 static bool requiresParensToAddCast(const Expr *E) {
7682   // FIXME: We should have a general way to reason about operator
7683   // precedence and whether parens are actually needed here.
7684   // Take care of a few common cases where they aren't.
7685   const Expr *Inside = E->IgnoreImpCasts();
7686   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7687     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7688 
7689   switch (Inside->getStmtClass()) {
7690   case Stmt::ArraySubscriptExprClass:
7691   case Stmt::CallExprClass:
7692   case Stmt::CharacterLiteralClass:
7693   case Stmt::CXXBoolLiteralExprClass:
7694   case Stmt::DeclRefExprClass:
7695   case Stmt::FloatingLiteralClass:
7696   case Stmt::IntegerLiteralClass:
7697   case Stmt::MemberExprClass:
7698   case Stmt::ObjCArrayLiteralClass:
7699   case Stmt::ObjCBoolLiteralExprClass:
7700   case Stmt::ObjCBoxedExprClass:
7701   case Stmt::ObjCDictionaryLiteralClass:
7702   case Stmt::ObjCEncodeExprClass:
7703   case Stmt::ObjCIvarRefExprClass:
7704   case Stmt::ObjCMessageExprClass:
7705   case Stmt::ObjCPropertyRefExprClass:
7706   case Stmt::ObjCStringLiteralClass:
7707   case Stmt::ObjCSubscriptRefExprClass:
7708   case Stmt::ParenExprClass:
7709   case Stmt::StringLiteralClass:
7710   case Stmt::UnaryOperatorClass:
7711     return false;
7712   default:
7713     return true;
7714   }
7715 }
7716 
7717 static std::pair<QualType, StringRef>
7718 shouldNotPrintDirectly(const ASTContext &Context,
7719                        QualType IntendedTy,
7720                        const Expr *E) {
7721   // Use a 'while' to peel off layers of typedefs.
7722   QualType TyTy = IntendedTy;
7723   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7724     StringRef Name = UserTy->getDecl()->getName();
7725     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7726       .Case("CFIndex", Context.getNSIntegerType())
7727       .Case("NSInteger", Context.getNSIntegerType())
7728       .Case("NSUInteger", Context.getNSUIntegerType())
7729       .Case("SInt32", Context.IntTy)
7730       .Case("UInt32", Context.UnsignedIntTy)
7731       .Default(QualType());
7732 
7733     if (!CastTy.isNull())
7734       return std::make_pair(CastTy, Name);
7735 
7736     TyTy = UserTy->desugar();
7737   }
7738 
7739   // Strip parens if necessary.
7740   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7741     return shouldNotPrintDirectly(Context,
7742                                   PE->getSubExpr()->getType(),
7743                                   PE->getSubExpr());
7744 
7745   // If this is a conditional expression, then its result type is constructed
7746   // via usual arithmetic conversions and thus there might be no necessary
7747   // typedef sugar there.  Recurse to operands to check for NSInteger &
7748   // Co. usage condition.
7749   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7750     QualType TrueTy, FalseTy;
7751     StringRef TrueName, FalseName;
7752 
7753     std::tie(TrueTy, TrueName) =
7754       shouldNotPrintDirectly(Context,
7755                              CO->getTrueExpr()->getType(),
7756                              CO->getTrueExpr());
7757     std::tie(FalseTy, FalseName) =
7758       shouldNotPrintDirectly(Context,
7759                              CO->getFalseExpr()->getType(),
7760                              CO->getFalseExpr());
7761 
7762     if (TrueTy == FalseTy)
7763       return std::make_pair(TrueTy, TrueName);
7764     else if (TrueTy.isNull())
7765       return std::make_pair(FalseTy, FalseName);
7766     else if (FalseTy.isNull())
7767       return std::make_pair(TrueTy, TrueName);
7768   }
7769 
7770   return std::make_pair(QualType(), StringRef());
7771 }
7772 
7773 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7774 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7775 /// type do not count.
7776 static bool
7777 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7778   QualType From = ICE->getSubExpr()->getType();
7779   QualType To = ICE->getType();
7780   // It's an integer promotion if the destination type is the promoted
7781   // source type.
7782   if (ICE->getCastKind() == CK_IntegralCast &&
7783       From->isPromotableIntegerType() &&
7784       S.Context.getPromotedIntegerType(From) == To)
7785     return true;
7786   // Look through vector types, since we do default argument promotion for
7787   // those in OpenCL.
7788   if (const auto *VecTy = From->getAs<ExtVectorType>())
7789     From = VecTy->getElementType();
7790   if (const auto *VecTy = To->getAs<ExtVectorType>())
7791     To = VecTy->getElementType();
7792   // It's a floating promotion if the source type is a lower rank.
7793   return ICE->getCastKind() == CK_FloatingCast &&
7794          S.Context.getFloatingTypeOrder(From, To) < 0;
7795 }
7796 
7797 bool
7798 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7799                                     const char *StartSpecifier,
7800                                     unsigned SpecifierLen,
7801                                     const Expr *E) {
7802   using namespace analyze_format_string;
7803   using namespace analyze_printf;
7804 
7805   // Now type check the data expression that matches the
7806   // format specifier.
7807   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7808   if (!AT.isValid())
7809     return true;
7810 
7811   QualType ExprTy = E->getType();
7812   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7813     ExprTy = TET->getUnderlyingExpr()->getType();
7814   }
7815 
7816   const analyze_printf::ArgType::MatchKind Match =
7817       AT.matchesType(S.Context, ExprTy);
7818   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7819   if (Match == analyze_printf::ArgType::Match)
7820     return true;
7821 
7822   // Look through argument promotions for our error message's reported type.
7823   // This includes the integral and floating promotions, but excludes array
7824   // and function pointer decay (seeing that an argument intended to be a
7825   // string has type 'char [6]' is probably more confusing than 'char *') and
7826   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7827   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7828     if (isArithmeticArgumentPromotion(S, ICE)) {
7829       E = ICE->getSubExpr();
7830       ExprTy = E->getType();
7831 
7832       // Check if we didn't match because of an implicit cast from a 'char'
7833       // or 'short' to an 'int'.  This is done because printf is a varargs
7834       // function.
7835       if (ICE->getType() == S.Context.IntTy ||
7836           ICE->getType() == S.Context.UnsignedIntTy) {
7837         // All further checking is done on the subexpression.
7838         if (AT.matchesType(S.Context, ExprTy))
7839           return true;
7840       }
7841     }
7842   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7843     // Special case for 'a', which has type 'int' in C.
7844     // Note, however, that we do /not/ want to treat multibyte constants like
7845     // 'MooV' as characters! This form is deprecated but still exists.
7846     if (ExprTy == S.Context.IntTy)
7847       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7848         ExprTy = S.Context.CharTy;
7849   }
7850 
7851   // Look through enums to their underlying type.
7852   bool IsEnum = false;
7853   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7854     ExprTy = EnumTy->getDecl()->getIntegerType();
7855     IsEnum = true;
7856   }
7857 
7858   // %C in an Objective-C context prints a unichar, not a wchar_t.
7859   // If the argument is an integer of some kind, believe the %C and suggest
7860   // a cast instead of changing the conversion specifier.
7861   QualType IntendedTy = ExprTy;
7862   if (isObjCContext() &&
7863       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7864     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7865         !ExprTy->isCharType()) {
7866       // 'unichar' is defined as a typedef of unsigned short, but we should
7867       // prefer using the typedef if it is visible.
7868       IntendedTy = S.Context.UnsignedShortTy;
7869 
7870       // While we are here, check if the value is an IntegerLiteral that happens
7871       // to be within the valid range.
7872       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7873         const llvm::APInt &V = IL->getValue();
7874         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7875           return true;
7876       }
7877 
7878       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7879                           Sema::LookupOrdinaryName);
7880       if (S.LookupName(Result, S.getCurScope())) {
7881         NamedDecl *ND = Result.getFoundDecl();
7882         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7883           if (TD->getUnderlyingType() == IntendedTy)
7884             IntendedTy = S.Context.getTypedefType(TD);
7885       }
7886     }
7887   }
7888 
7889   // Special-case some of Darwin's platform-independence types by suggesting
7890   // casts to primitive types that are known to be large enough.
7891   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7892   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7893     QualType CastTy;
7894     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7895     if (!CastTy.isNull()) {
7896       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7897       // (long in ASTContext). Only complain to pedants.
7898       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7899           (AT.isSizeT() || AT.isPtrdiffT()) &&
7900           AT.matchesType(S.Context, CastTy))
7901         Pedantic = true;
7902       IntendedTy = CastTy;
7903       ShouldNotPrintDirectly = true;
7904     }
7905   }
7906 
7907   // We may be able to offer a FixItHint if it is a supported type.
7908   PrintfSpecifier fixedFS = FS;
7909   bool Success =
7910       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7911 
7912   if (Success) {
7913     // Get the fix string from the fixed format specifier
7914     SmallString<16> buf;
7915     llvm::raw_svector_ostream os(buf);
7916     fixedFS.toString(os);
7917 
7918     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7919 
7920     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7921       unsigned Diag =
7922           Pedantic
7923               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7924               : diag::warn_format_conversion_argument_type_mismatch;
7925       // In this case, the specifier is wrong and should be changed to match
7926       // the argument.
7927       EmitFormatDiagnostic(S.PDiag(Diag)
7928                                << AT.getRepresentativeTypeName(S.Context)
7929                                << IntendedTy << IsEnum << E->getSourceRange(),
7930                            E->getBeginLoc(),
7931                            /*IsStringLocation*/ false, SpecRange,
7932                            FixItHint::CreateReplacement(SpecRange, os.str()));
7933     } else {
7934       // The canonical type for formatting this value is different from the
7935       // actual type of the expression. (This occurs, for example, with Darwin's
7936       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7937       // should be printed as 'long' for 64-bit compatibility.)
7938       // Rather than emitting a normal format/argument mismatch, we want to
7939       // add a cast to the recommended type (and correct the format string
7940       // if necessary).
7941       SmallString<16> CastBuf;
7942       llvm::raw_svector_ostream CastFix(CastBuf);
7943       CastFix << "(";
7944       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7945       CastFix << ")";
7946 
7947       SmallVector<FixItHint,4> Hints;
7948       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
7949         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7950 
7951       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7952         // If there's already a cast present, just replace it.
7953         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7954         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7955 
7956       } else if (!requiresParensToAddCast(E)) {
7957         // If the expression has high enough precedence,
7958         // just write the C-style cast.
7959         Hints.push_back(
7960             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7961       } else {
7962         // Otherwise, add parens around the expression as well as the cast.
7963         CastFix << "(";
7964         Hints.push_back(
7965             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7966 
7967         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
7968         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7969       }
7970 
7971       if (ShouldNotPrintDirectly) {
7972         // The expression has a type that should not be printed directly.
7973         // We extract the name from the typedef because we don't want to show
7974         // the underlying type in the diagnostic.
7975         StringRef Name;
7976         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7977           Name = TypedefTy->getDecl()->getName();
7978         else
7979           Name = CastTyName;
7980         unsigned Diag = Pedantic
7981                             ? diag::warn_format_argument_needs_cast_pedantic
7982                             : diag::warn_format_argument_needs_cast;
7983         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7984                                            << E->getSourceRange(),
7985                              E->getBeginLoc(), /*IsStringLocation=*/false,
7986                              SpecRange, Hints);
7987       } else {
7988         // In this case, the expression could be printed using a different
7989         // specifier, but we've decided that the specifier is probably correct
7990         // and we should cast instead. Just use the normal warning message.
7991         EmitFormatDiagnostic(
7992             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7993                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7994                 << E->getSourceRange(),
7995             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7996       }
7997     }
7998   } else {
7999     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8000                                                    SpecifierLen);
8001     // Since the warning for passing non-POD types to variadic functions
8002     // was deferred until now, we emit a warning for non-POD
8003     // arguments here.
8004     switch (S.isValidVarArgType(ExprTy)) {
8005     case Sema::VAK_Valid:
8006     case Sema::VAK_ValidInCXX11: {
8007       unsigned Diag =
8008           Pedantic
8009               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8010               : diag::warn_format_conversion_argument_type_mismatch;
8011 
8012       EmitFormatDiagnostic(
8013           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8014                         << IsEnum << CSR << E->getSourceRange(),
8015           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8016       break;
8017     }
8018     case Sema::VAK_Undefined:
8019     case Sema::VAK_MSVCUndefined:
8020       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8021                                << S.getLangOpts().CPlusPlus11 << ExprTy
8022                                << CallType
8023                                << AT.getRepresentativeTypeName(S.Context) << CSR
8024                                << E->getSourceRange(),
8025                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8026       checkForCStrMembers(AT, E);
8027       break;
8028 
8029     case Sema::VAK_Invalid:
8030       if (ExprTy->isObjCObjectType())
8031         EmitFormatDiagnostic(
8032             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8033                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8034                 << AT.getRepresentativeTypeName(S.Context) << CSR
8035                 << E->getSourceRange(),
8036             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8037       else
8038         // FIXME: If this is an initializer list, suggest removing the braces
8039         // or inserting a cast to the target type.
8040         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8041             << isa<InitListExpr>(E) << ExprTy << CallType
8042             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8043       break;
8044     }
8045 
8046     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8047            "format string specifier index out of range");
8048     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8049   }
8050 
8051   return true;
8052 }
8053 
8054 //===--- CHECK: Scanf format string checking ------------------------------===//
8055 
8056 namespace {
8057 
8058 class CheckScanfHandler : public CheckFormatHandler {
8059 public:
8060   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8061                     const Expr *origFormatExpr, Sema::FormatStringType type,
8062                     unsigned firstDataArg, unsigned numDataArgs,
8063                     const char *beg, bool hasVAListArg,
8064                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8065                     bool inFunctionCall, Sema::VariadicCallType CallType,
8066                     llvm::SmallBitVector &CheckedVarArgs,
8067                     UncoveredArgHandler &UncoveredArg)
8068       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8069                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8070                            inFunctionCall, CallType, CheckedVarArgs,
8071                            UncoveredArg) {}
8072 
8073   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8074                             const char *startSpecifier,
8075                             unsigned specifierLen) override;
8076 
8077   bool HandleInvalidScanfConversionSpecifier(
8078           const analyze_scanf::ScanfSpecifier &FS,
8079           const char *startSpecifier,
8080           unsigned specifierLen) override;
8081 
8082   void HandleIncompleteScanList(const char *start, const char *end) override;
8083 };
8084 
8085 } // namespace
8086 
8087 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8088                                                  const char *end) {
8089   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8090                        getLocationOfByte(end), /*IsStringLocation*/true,
8091                        getSpecifierRange(start, end - start));
8092 }
8093 
8094 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8095                                         const analyze_scanf::ScanfSpecifier &FS,
8096                                         const char *startSpecifier,
8097                                         unsigned specifierLen) {
8098   const analyze_scanf::ScanfConversionSpecifier &CS =
8099     FS.getConversionSpecifier();
8100 
8101   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8102                                           getLocationOfByte(CS.getStart()),
8103                                           startSpecifier, specifierLen,
8104                                           CS.getStart(), CS.getLength());
8105 }
8106 
8107 bool CheckScanfHandler::HandleScanfSpecifier(
8108                                        const analyze_scanf::ScanfSpecifier &FS,
8109                                        const char *startSpecifier,
8110                                        unsigned specifierLen) {
8111   using namespace analyze_scanf;
8112   using namespace analyze_format_string;
8113 
8114   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8115 
8116   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8117   // be used to decide if we are using positional arguments consistently.
8118   if (FS.consumesDataArgument()) {
8119     if (atFirstArg) {
8120       atFirstArg = false;
8121       usesPositionalArgs = FS.usesPositionalArg();
8122     }
8123     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8124       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8125                                         startSpecifier, specifierLen);
8126       return false;
8127     }
8128   }
8129 
8130   // Check if the field with is non-zero.
8131   const OptionalAmount &Amt = FS.getFieldWidth();
8132   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8133     if (Amt.getConstantAmount() == 0) {
8134       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8135                                                    Amt.getConstantLength());
8136       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8137                            getLocationOfByte(Amt.getStart()),
8138                            /*IsStringLocation*/true, R,
8139                            FixItHint::CreateRemoval(R));
8140     }
8141   }
8142 
8143   if (!FS.consumesDataArgument()) {
8144     // FIXME: Technically specifying a precision or field width here
8145     // makes no sense.  Worth issuing a warning at some point.
8146     return true;
8147   }
8148 
8149   // Consume the argument.
8150   unsigned argIndex = FS.getArgIndex();
8151   if (argIndex < NumDataArgs) {
8152       // The check to see if the argIndex is valid will come later.
8153       // We set the bit here because we may exit early from this
8154       // function if we encounter some other error.
8155     CoveredArgs.set(argIndex);
8156   }
8157 
8158   // Check the length modifier is valid with the given conversion specifier.
8159   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8160                                  S.getLangOpts()))
8161     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8162                                 diag::warn_format_nonsensical_length);
8163   else if (!FS.hasStandardLengthModifier())
8164     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8165   else if (!FS.hasStandardLengthConversionCombination())
8166     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8167                                 diag::warn_format_non_standard_conversion_spec);
8168 
8169   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8170     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8171 
8172   // The remaining checks depend on the data arguments.
8173   if (HasVAListArg)
8174     return true;
8175 
8176   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8177     return false;
8178 
8179   // Check that the argument type matches the format specifier.
8180   const Expr *Ex = getDataArg(argIndex);
8181   if (!Ex)
8182     return true;
8183 
8184   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8185 
8186   if (!AT.isValid()) {
8187     return true;
8188   }
8189 
8190   analyze_format_string::ArgType::MatchKind Match =
8191       AT.matchesType(S.Context, Ex->getType());
8192   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8193   if (Match == analyze_format_string::ArgType::Match)
8194     return true;
8195 
8196   ScanfSpecifier fixedFS = FS;
8197   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8198                                  S.getLangOpts(), S.Context);
8199 
8200   unsigned Diag =
8201       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8202                : diag::warn_format_conversion_argument_type_mismatch;
8203 
8204   if (Success) {
8205     // Get the fix string from the fixed format specifier.
8206     SmallString<128> buf;
8207     llvm::raw_svector_ostream os(buf);
8208     fixedFS.toString(os);
8209 
8210     EmitFormatDiagnostic(
8211         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8212                       << Ex->getType() << false << Ex->getSourceRange(),
8213         Ex->getBeginLoc(),
8214         /*IsStringLocation*/ false,
8215         getSpecifierRange(startSpecifier, specifierLen),
8216         FixItHint::CreateReplacement(
8217             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8218   } else {
8219     EmitFormatDiagnostic(S.PDiag(Diag)
8220                              << AT.getRepresentativeTypeName(S.Context)
8221                              << Ex->getType() << false << Ex->getSourceRange(),
8222                          Ex->getBeginLoc(),
8223                          /*IsStringLocation*/ false,
8224                          getSpecifierRange(startSpecifier, specifierLen));
8225   }
8226 
8227   return true;
8228 }
8229 
8230 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8231                               const Expr *OrigFormatExpr,
8232                               ArrayRef<const Expr *> Args,
8233                               bool HasVAListArg, unsigned format_idx,
8234                               unsigned firstDataArg,
8235                               Sema::FormatStringType Type,
8236                               bool inFunctionCall,
8237                               Sema::VariadicCallType CallType,
8238                               llvm::SmallBitVector &CheckedVarArgs,
8239                               UncoveredArgHandler &UncoveredArg) {
8240   // CHECK: is the format string a wide literal?
8241   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8242     CheckFormatHandler::EmitFormatDiagnostic(
8243         S, inFunctionCall, Args[format_idx],
8244         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8245         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8246     return;
8247   }
8248 
8249   // Str - The format string.  NOTE: this is NOT null-terminated!
8250   StringRef StrRef = FExpr->getString();
8251   const char *Str = StrRef.data();
8252   // Account for cases where the string literal is truncated in a declaration.
8253   const ConstantArrayType *T =
8254     S.Context.getAsConstantArrayType(FExpr->getType());
8255   assert(T && "String literal not of constant array type!");
8256   size_t TypeSize = T->getSize().getZExtValue();
8257   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8258   const unsigned numDataArgs = Args.size() - firstDataArg;
8259 
8260   // Emit a warning if the string literal is truncated and does not contain an
8261   // embedded null character.
8262   if (TypeSize <= StrRef.size() &&
8263       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8264     CheckFormatHandler::EmitFormatDiagnostic(
8265         S, inFunctionCall, Args[format_idx],
8266         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8267         FExpr->getBeginLoc(),
8268         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8269     return;
8270   }
8271 
8272   // CHECK: empty format string?
8273   if (StrLen == 0 && numDataArgs > 0) {
8274     CheckFormatHandler::EmitFormatDiagnostic(
8275         S, inFunctionCall, Args[format_idx],
8276         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8277         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8278     return;
8279   }
8280 
8281   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8282       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8283       Type == Sema::FST_OSTrace) {
8284     CheckPrintfHandler H(
8285         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8286         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8287         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8288         CheckedVarArgs, UncoveredArg);
8289 
8290     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8291                                                   S.getLangOpts(),
8292                                                   S.Context.getTargetInfo(),
8293                                             Type == Sema::FST_FreeBSDKPrintf))
8294       H.DoneProcessing();
8295   } else if (Type == Sema::FST_Scanf) {
8296     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8297                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8298                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8299 
8300     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8301                                                  S.getLangOpts(),
8302                                                  S.Context.getTargetInfo()))
8303       H.DoneProcessing();
8304   } // TODO: handle other formats
8305 }
8306 
8307 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8308   // Str - The format string.  NOTE: this is NOT null-terminated!
8309   StringRef StrRef = FExpr->getString();
8310   const char *Str = StrRef.data();
8311   // Account for cases where the string literal is truncated in a declaration.
8312   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8313   assert(T && "String literal not of constant array type!");
8314   size_t TypeSize = T->getSize().getZExtValue();
8315   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8316   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8317                                                          getLangOpts(),
8318                                                          Context.getTargetInfo());
8319 }
8320 
8321 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8322 
8323 // Returns the related absolute value function that is larger, of 0 if one
8324 // does not exist.
8325 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8326   switch (AbsFunction) {
8327   default:
8328     return 0;
8329 
8330   case Builtin::BI__builtin_abs:
8331     return Builtin::BI__builtin_labs;
8332   case Builtin::BI__builtin_labs:
8333     return Builtin::BI__builtin_llabs;
8334   case Builtin::BI__builtin_llabs:
8335     return 0;
8336 
8337   case Builtin::BI__builtin_fabsf:
8338     return Builtin::BI__builtin_fabs;
8339   case Builtin::BI__builtin_fabs:
8340     return Builtin::BI__builtin_fabsl;
8341   case Builtin::BI__builtin_fabsl:
8342     return 0;
8343 
8344   case Builtin::BI__builtin_cabsf:
8345     return Builtin::BI__builtin_cabs;
8346   case Builtin::BI__builtin_cabs:
8347     return Builtin::BI__builtin_cabsl;
8348   case Builtin::BI__builtin_cabsl:
8349     return 0;
8350 
8351   case Builtin::BIabs:
8352     return Builtin::BIlabs;
8353   case Builtin::BIlabs:
8354     return Builtin::BIllabs;
8355   case Builtin::BIllabs:
8356     return 0;
8357 
8358   case Builtin::BIfabsf:
8359     return Builtin::BIfabs;
8360   case Builtin::BIfabs:
8361     return Builtin::BIfabsl;
8362   case Builtin::BIfabsl:
8363     return 0;
8364 
8365   case Builtin::BIcabsf:
8366    return Builtin::BIcabs;
8367   case Builtin::BIcabs:
8368     return Builtin::BIcabsl;
8369   case Builtin::BIcabsl:
8370     return 0;
8371   }
8372 }
8373 
8374 // Returns the argument type of the absolute value function.
8375 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8376                                              unsigned AbsType) {
8377   if (AbsType == 0)
8378     return QualType();
8379 
8380   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8381   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8382   if (Error != ASTContext::GE_None)
8383     return QualType();
8384 
8385   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8386   if (!FT)
8387     return QualType();
8388 
8389   if (FT->getNumParams() != 1)
8390     return QualType();
8391 
8392   return FT->getParamType(0);
8393 }
8394 
8395 // Returns the best absolute value function, or zero, based on type and
8396 // current absolute value function.
8397 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8398                                    unsigned AbsFunctionKind) {
8399   unsigned BestKind = 0;
8400   uint64_t ArgSize = Context.getTypeSize(ArgType);
8401   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8402        Kind = getLargerAbsoluteValueFunction(Kind)) {
8403     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8404     if (Context.getTypeSize(ParamType) >= ArgSize) {
8405       if (BestKind == 0)
8406         BestKind = Kind;
8407       else if (Context.hasSameType(ParamType, ArgType)) {
8408         BestKind = Kind;
8409         break;
8410       }
8411     }
8412   }
8413   return BestKind;
8414 }
8415 
8416 enum AbsoluteValueKind {
8417   AVK_Integer,
8418   AVK_Floating,
8419   AVK_Complex
8420 };
8421 
8422 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8423   if (T->isIntegralOrEnumerationType())
8424     return AVK_Integer;
8425   if (T->isRealFloatingType())
8426     return AVK_Floating;
8427   if (T->isAnyComplexType())
8428     return AVK_Complex;
8429 
8430   llvm_unreachable("Type not integer, floating, or complex");
8431 }
8432 
8433 // Changes the absolute value function to a different type.  Preserves whether
8434 // the function is a builtin.
8435 static unsigned changeAbsFunction(unsigned AbsKind,
8436                                   AbsoluteValueKind ValueKind) {
8437   switch (ValueKind) {
8438   case AVK_Integer:
8439     switch (AbsKind) {
8440     default:
8441       return 0;
8442     case Builtin::BI__builtin_fabsf:
8443     case Builtin::BI__builtin_fabs:
8444     case Builtin::BI__builtin_fabsl:
8445     case Builtin::BI__builtin_cabsf:
8446     case Builtin::BI__builtin_cabs:
8447     case Builtin::BI__builtin_cabsl:
8448       return Builtin::BI__builtin_abs;
8449     case Builtin::BIfabsf:
8450     case Builtin::BIfabs:
8451     case Builtin::BIfabsl:
8452     case Builtin::BIcabsf:
8453     case Builtin::BIcabs:
8454     case Builtin::BIcabsl:
8455       return Builtin::BIabs;
8456     }
8457   case AVK_Floating:
8458     switch (AbsKind) {
8459     default:
8460       return 0;
8461     case Builtin::BI__builtin_abs:
8462     case Builtin::BI__builtin_labs:
8463     case Builtin::BI__builtin_llabs:
8464     case Builtin::BI__builtin_cabsf:
8465     case Builtin::BI__builtin_cabs:
8466     case Builtin::BI__builtin_cabsl:
8467       return Builtin::BI__builtin_fabsf;
8468     case Builtin::BIabs:
8469     case Builtin::BIlabs:
8470     case Builtin::BIllabs:
8471     case Builtin::BIcabsf:
8472     case Builtin::BIcabs:
8473     case Builtin::BIcabsl:
8474       return Builtin::BIfabsf;
8475     }
8476   case AVK_Complex:
8477     switch (AbsKind) {
8478     default:
8479       return 0;
8480     case Builtin::BI__builtin_abs:
8481     case Builtin::BI__builtin_labs:
8482     case Builtin::BI__builtin_llabs:
8483     case Builtin::BI__builtin_fabsf:
8484     case Builtin::BI__builtin_fabs:
8485     case Builtin::BI__builtin_fabsl:
8486       return Builtin::BI__builtin_cabsf;
8487     case Builtin::BIabs:
8488     case Builtin::BIlabs:
8489     case Builtin::BIllabs:
8490     case Builtin::BIfabsf:
8491     case Builtin::BIfabs:
8492     case Builtin::BIfabsl:
8493       return Builtin::BIcabsf;
8494     }
8495   }
8496   llvm_unreachable("Unable to convert function");
8497 }
8498 
8499 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8500   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8501   if (!FnInfo)
8502     return 0;
8503 
8504   switch (FDecl->getBuiltinID()) {
8505   default:
8506     return 0;
8507   case Builtin::BI__builtin_abs:
8508   case Builtin::BI__builtin_fabs:
8509   case Builtin::BI__builtin_fabsf:
8510   case Builtin::BI__builtin_fabsl:
8511   case Builtin::BI__builtin_labs:
8512   case Builtin::BI__builtin_llabs:
8513   case Builtin::BI__builtin_cabs:
8514   case Builtin::BI__builtin_cabsf:
8515   case Builtin::BI__builtin_cabsl:
8516   case Builtin::BIabs:
8517   case Builtin::BIlabs:
8518   case Builtin::BIllabs:
8519   case Builtin::BIfabs:
8520   case Builtin::BIfabsf:
8521   case Builtin::BIfabsl:
8522   case Builtin::BIcabs:
8523   case Builtin::BIcabsf:
8524   case Builtin::BIcabsl:
8525     return FDecl->getBuiltinID();
8526   }
8527   llvm_unreachable("Unknown Builtin type");
8528 }
8529 
8530 // If the replacement is valid, emit a note with replacement function.
8531 // Additionally, suggest including the proper header if not already included.
8532 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8533                             unsigned AbsKind, QualType ArgType) {
8534   bool EmitHeaderHint = true;
8535   const char *HeaderName = nullptr;
8536   const char *FunctionName = nullptr;
8537   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8538     FunctionName = "std::abs";
8539     if (ArgType->isIntegralOrEnumerationType()) {
8540       HeaderName = "cstdlib";
8541     } else if (ArgType->isRealFloatingType()) {
8542       HeaderName = "cmath";
8543     } else {
8544       llvm_unreachable("Invalid Type");
8545     }
8546 
8547     // Lookup all std::abs
8548     if (NamespaceDecl *Std = S.getStdNamespace()) {
8549       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8550       R.suppressDiagnostics();
8551       S.LookupQualifiedName(R, Std);
8552 
8553       for (const auto *I : R) {
8554         const FunctionDecl *FDecl = nullptr;
8555         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8556           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8557         } else {
8558           FDecl = dyn_cast<FunctionDecl>(I);
8559         }
8560         if (!FDecl)
8561           continue;
8562 
8563         // Found std::abs(), check that they are the right ones.
8564         if (FDecl->getNumParams() != 1)
8565           continue;
8566 
8567         // Check that the parameter type can handle the argument.
8568         QualType ParamType = FDecl->getParamDecl(0)->getType();
8569         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8570             S.Context.getTypeSize(ArgType) <=
8571                 S.Context.getTypeSize(ParamType)) {
8572           // Found a function, don't need the header hint.
8573           EmitHeaderHint = false;
8574           break;
8575         }
8576       }
8577     }
8578   } else {
8579     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8580     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8581 
8582     if (HeaderName) {
8583       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8584       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8585       R.suppressDiagnostics();
8586       S.LookupName(R, S.getCurScope());
8587 
8588       if (R.isSingleResult()) {
8589         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8590         if (FD && FD->getBuiltinID() == AbsKind) {
8591           EmitHeaderHint = false;
8592         } else {
8593           return;
8594         }
8595       } else if (!R.empty()) {
8596         return;
8597       }
8598     }
8599   }
8600 
8601   S.Diag(Loc, diag::note_replace_abs_function)
8602       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8603 
8604   if (!HeaderName)
8605     return;
8606 
8607   if (!EmitHeaderHint)
8608     return;
8609 
8610   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8611                                                     << FunctionName;
8612 }
8613 
8614 template <std::size_t StrLen>
8615 static bool IsStdFunction(const FunctionDecl *FDecl,
8616                           const char (&Str)[StrLen]) {
8617   if (!FDecl)
8618     return false;
8619   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8620     return false;
8621   if (!FDecl->isInStdNamespace())
8622     return false;
8623 
8624   return true;
8625 }
8626 
8627 // Warn when using the wrong abs() function.
8628 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8629                                       const FunctionDecl *FDecl) {
8630   if (Call->getNumArgs() != 1)
8631     return;
8632 
8633   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8634   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8635   if (AbsKind == 0 && !IsStdAbs)
8636     return;
8637 
8638   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8639   QualType ParamType = Call->getArg(0)->getType();
8640 
8641   // Unsigned types cannot be negative.  Suggest removing the absolute value
8642   // function call.
8643   if (ArgType->isUnsignedIntegerType()) {
8644     const char *FunctionName =
8645         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8646     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8647     Diag(Call->getExprLoc(), diag::note_remove_abs)
8648         << FunctionName
8649         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8650     return;
8651   }
8652 
8653   // Taking the absolute value of a pointer is very suspicious, they probably
8654   // wanted to index into an array, dereference a pointer, call a function, etc.
8655   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8656     unsigned DiagType = 0;
8657     if (ArgType->isFunctionType())
8658       DiagType = 1;
8659     else if (ArgType->isArrayType())
8660       DiagType = 2;
8661 
8662     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8663     return;
8664   }
8665 
8666   // std::abs has overloads which prevent most of the absolute value problems
8667   // from occurring.
8668   if (IsStdAbs)
8669     return;
8670 
8671   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8672   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8673 
8674   // The argument and parameter are the same kind.  Check if they are the right
8675   // size.
8676   if (ArgValueKind == ParamValueKind) {
8677     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8678       return;
8679 
8680     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8681     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8682         << FDecl << ArgType << ParamType;
8683 
8684     if (NewAbsKind == 0)
8685       return;
8686 
8687     emitReplacement(*this, Call->getExprLoc(),
8688                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8689     return;
8690   }
8691 
8692   // ArgValueKind != ParamValueKind
8693   // The wrong type of absolute value function was used.  Attempt to find the
8694   // proper one.
8695   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8696   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8697   if (NewAbsKind == 0)
8698     return;
8699 
8700   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8701       << FDecl << ParamValueKind << ArgValueKind;
8702 
8703   emitReplacement(*this, Call->getExprLoc(),
8704                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8705 }
8706 
8707 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8708 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8709                                 const FunctionDecl *FDecl) {
8710   if (!Call || !FDecl) return;
8711 
8712   // Ignore template specializations and macros.
8713   if (inTemplateInstantiation()) return;
8714   if (Call->getExprLoc().isMacroID()) return;
8715 
8716   // Only care about the one template argument, two function parameter std::max
8717   if (Call->getNumArgs() != 2) return;
8718   if (!IsStdFunction(FDecl, "max")) return;
8719   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8720   if (!ArgList) return;
8721   if (ArgList->size() != 1) return;
8722 
8723   // Check that template type argument is unsigned integer.
8724   const auto& TA = ArgList->get(0);
8725   if (TA.getKind() != TemplateArgument::Type) return;
8726   QualType ArgType = TA.getAsType();
8727   if (!ArgType->isUnsignedIntegerType()) return;
8728 
8729   // See if either argument is a literal zero.
8730   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8731     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8732     if (!MTE) return false;
8733     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8734     if (!Num) return false;
8735     if (Num->getValue() != 0) return false;
8736     return true;
8737   };
8738 
8739   const Expr *FirstArg = Call->getArg(0);
8740   const Expr *SecondArg = Call->getArg(1);
8741   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8742   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8743 
8744   // Only warn when exactly one argument is zero.
8745   if (IsFirstArgZero == IsSecondArgZero) return;
8746 
8747   SourceRange FirstRange = FirstArg->getSourceRange();
8748   SourceRange SecondRange = SecondArg->getSourceRange();
8749 
8750   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8751 
8752   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8753       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8754 
8755   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8756   SourceRange RemovalRange;
8757   if (IsFirstArgZero) {
8758     RemovalRange = SourceRange(FirstRange.getBegin(),
8759                                SecondRange.getBegin().getLocWithOffset(-1));
8760   } else {
8761     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8762                                SecondRange.getEnd());
8763   }
8764 
8765   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8766         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8767         << FixItHint::CreateRemoval(RemovalRange);
8768 }
8769 
8770 //===--- CHECK: Standard memory functions ---------------------------------===//
8771 
8772 /// Takes the expression passed to the size_t parameter of functions
8773 /// such as memcmp, strncat, etc and warns if it's a comparison.
8774 ///
8775 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8776 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8777                                            IdentifierInfo *FnName,
8778                                            SourceLocation FnLoc,
8779                                            SourceLocation RParenLoc) {
8780   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8781   if (!Size)
8782     return false;
8783 
8784   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8785   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8786     return false;
8787 
8788   SourceRange SizeRange = Size->getSourceRange();
8789   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8790       << SizeRange << FnName;
8791   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8792       << FnName
8793       << FixItHint::CreateInsertion(
8794              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8795       << FixItHint::CreateRemoval(RParenLoc);
8796   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8797       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8798       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8799                                     ")");
8800 
8801   return true;
8802 }
8803 
8804 /// Determine whether the given type is or contains a dynamic class type
8805 /// (e.g., whether it has a vtable).
8806 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8807                                                      bool &IsContained) {
8808   // Look through array types while ignoring qualifiers.
8809   const Type *Ty = T->getBaseElementTypeUnsafe();
8810   IsContained = false;
8811 
8812   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8813   RD = RD ? RD->getDefinition() : nullptr;
8814   if (!RD || RD->isInvalidDecl())
8815     return nullptr;
8816 
8817   if (RD->isDynamicClass())
8818     return RD;
8819 
8820   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8821   // It's impossible for a class to transitively contain itself by value, so
8822   // infinite recursion is impossible.
8823   for (auto *FD : RD->fields()) {
8824     bool SubContained;
8825     if (const CXXRecordDecl *ContainedRD =
8826             getContainedDynamicClass(FD->getType(), SubContained)) {
8827       IsContained = true;
8828       return ContainedRD;
8829     }
8830   }
8831 
8832   return nullptr;
8833 }
8834 
8835 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8836   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8837     if (Unary->getKind() == UETT_SizeOf)
8838       return Unary;
8839   return nullptr;
8840 }
8841 
8842 /// If E is a sizeof expression, returns its argument expression,
8843 /// otherwise returns NULL.
8844 static const Expr *getSizeOfExprArg(const Expr *E) {
8845   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8846     if (!SizeOf->isArgumentType())
8847       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8848   return nullptr;
8849 }
8850 
8851 /// If E is a sizeof expression, returns its argument type.
8852 static QualType getSizeOfArgType(const Expr *E) {
8853   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8854     return SizeOf->getTypeOfArgument();
8855   return QualType();
8856 }
8857 
8858 namespace {
8859 
8860 struct SearchNonTrivialToInitializeField
8861     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8862   using Super =
8863       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8864 
8865   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8866 
8867   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8868                      SourceLocation SL) {
8869     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8870       asDerived().visitArray(PDIK, AT, SL);
8871       return;
8872     }
8873 
8874     Super::visitWithKind(PDIK, FT, SL);
8875   }
8876 
8877   void visitARCStrong(QualType FT, SourceLocation SL) {
8878     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8879   }
8880   void visitARCWeak(QualType FT, SourceLocation SL) {
8881     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8882   }
8883   void visitStruct(QualType FT, SourceLocation SL) {
8884     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8885       visit(FD->getType(), FD->getLocation());
8886   }
8887   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8888                   const ArrayType *AT, SourceLocation SL) {
8889     visit(getContext().getBaseElementType(AT), SL);
8890   }
8891   void visitTrivial(QualType FT, SourceLocation SL) {}
8892 
8893   static void diag(QualType RT, const Expr *E, Sema &S) {
8894     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8895   }
8896 
8897   ASTContext &getContext() { return S.getASTContext(); }
8898 
8899   const Expr *E;
8900   Sema &S;
8901 };
8902 
8903 struct SearchNonTrivialToCopyField
8904     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8905   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8906 
8907   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8908 
8909   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8910                      SourceLocation SL) {
8911     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8912       asDerived().visitArray(PCK, AT, SL);
8913       return;
8914     }
8915 
8916     Super::visitWithKind(PCK, FT, SL);
8917   }
8918 
8919   void visitARCStrong(QualType FT, SourceLocation SL) {
8920     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8921   }
8922   void visitARCWeak(QualType FT, SourceLocation SL) {
8923     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8924   }
8925   void visitStruct(QualType FT, SourceLocation SL) {
8926     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8927       visit(FD->getType(), FD->getLocation());
8928   }
8929   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8930                   SourceLocation SL) {
8931     visit(getContext().getBaseElementType(AT), SL);
8932   }
8933   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8934                 SourceLocation SL) {}
8935   void visitTrivial(QualType FT, SourceLocation SL) {}
8936   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8937 
8938   static void diag(QualType RT, const Expr *E, Sema &S) {
8939     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8940   }
8941 
8942   ASTContext &getContext() { return S.getASTContext(); }
8943 
8944   const Expr *E;
8945   Sema &S;
8946 };
8947 
8948 }
8949 
8950 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8951 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8952   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8953 
8954   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8955     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8956       return false;
8957 
8958     return doesExprLikelyComputeSize(BO->getLHS()) ||
8959            doesExprLikelyComputeSize(BO->getRHS());
8960   }
8961 
8962   return getAsSizeOfExpr(SizeofExpr) != nullptr;
8963 }
8964 
8965 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8966 ///
8967 /// \code
8968 ///   #define MACRO 0
8969 ///   foo(MACRO);
8970 ///   foo(0);
8971 /// \endcode
8972 ///
8973 /// This should return true for the first call to foo, but not for the second
8974 /// (regardless of whether foo is a macro or function).
8975 static bool isArgumentExpandedFromMacro(SourceManager &SM,
8976                                         SourceLocation CallLoc,
8977                                         SourceLocation ArgLoc) {
8978   if (!CallLoc.isMacroID())
8979     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8980 
8981   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8982          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8983 }
8984 
8985 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8986 /// last two arguments transposed.
8987 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8988   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8989     return;
8990 
8991   const Expr *SizeArg =
8992     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8993 
8994   auto isLiteralZero = [](const Expr *E) {
8995     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8996   };
8997 
8998   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8999   SourceLocation CallLoc = Call->getRParenLoc();
9000   SourceManager &SM = S.getSourceManager();
9001   if (isLiteralZero(SizeArg) &&
9002       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9003 
9004     SourceLocation DiagLoc = SizeArg->getExprLoc();
9005 
9006     // Some platforms #define bzero to __builtin_memset. See if this is the
9007     // case, and if so, emit a better diagnostic.
9008     if (BId == Builtin::BIbzero ||
9009         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9010                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9011       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9012       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9013     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9014       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9015       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9016     }
9017     return;
9018   }
9019 
9020   // If the second argument to a memset is a sizeof expression and the third
9021   // isn't, this is also likely an error. This should catch
9022   // 'memset(buf, sizeof(buf), 0xff)'.
9023   if (BId == Builtin::BImemset &&
9024       doesExprLikelyComputeSize(Call->getArg(1)) &&
9025       !doesExprLikelyComputeSize(Call->getArg(2))) {
9026     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9027     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9028     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9029     return;
9030   }
9031 }
9032 
9033 /// Check for dangerous or invalid arguments to memset().
9034 ///
9035 /// This issues warnings on known problematic, dangerous or unspecified
9036 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9037 /// function calls.
9038 ///
9039 /// \param Call The call expression to diagnose.
9040 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9041                                    unsigned BId,
9042                                    IdentifierInfo *FnName) {
9043   assert(BId != 0);
9044 
9045   // It is possible to have a non-standard definition of memset.  Validate
9046   // we have enough arguments, and if not, abort further checking.
9047   unsigned ExpectedNumArgs =
9048       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9049   if (Call->getNumArgs() < ExpectedNumArgs)
9050     return;
9051 
9052   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9053                       BId == Builtin::BIstrndup ? 1 : 2);
9054   unsigned LenArg =
9055       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9056   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9057 
9058   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9059                                      Call->getBeginLoc(), Call->getRParenLoc()))
9060     return;
9061 
9062   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9063   CheckMemaccessSize(*this, BId, Call);
9064 
9065   // We have special checking when the length is a sizeof expression.
9066   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9067   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9068   llvm::FoldingSetNodeID SizeOfArgID;
9069 
9070   // Although widely used, 'bzero' is not a standard function. Be more strict
9071   // with the argument types before allowing diagnostics and only allow the
9072   // form bzero(ptr, sizeof(...)).
9073   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9074   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9075     return;
9076 
9077   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9078     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9079     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9080 
9081     QualType DestTy = Dest->getType();
9082     QualType PointeeTy;
9083     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9084       PointeeTy = DestPtrTy->getPointeeType();
9085 
9086       // Never warn about void type pointers. This can be used to suppress
9087       // false positives.
9088       if (PointeeTy->isVoidType())
9089         continue;
9090 
9091       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9092       // actually comparing the expressions for equality. Because computing the
9093       // expression IDs can be expensive, we only do this if the diagnostic is
9094       // enabled.
9095       if (SizeOfArg &&
9096           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9097                            SizeOfArg->getExprLoc())) {
9098         // We only compute IDs for expressions if the warning is enabled, and
9099         // cache the sizeof arg's ID.
9100         if (SizeOfArgID == llvm::FoldingSetNodeID())
9101           SizeOfArg->Profile(SizeOfArgID, Context, true);
9102         llvm::FoldingSetNodeID DestID;
9103         Dest->Profile(DestID, Context, true);
9104         if (DestID == SizeOfArgID) {
9105           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9106           //       over sizeof(src) as well.
9107           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9108           StringRef ReadableName = FnName->getName();
9109 
9110           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9111             if (UnaryOp->getOpcode() == UO_AddrOf)
9112               ActionIdx = 1; // If its an address-of operator, just remove it.
9113           if (!PointeeTy->isIncompleteType() &&
9114               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9115             ActionIdx = 2; // If the pointee's size is sizeof(char),
9116                            // suggest an explicit length.
9117 
9118           // If the function is defined as a builtin macro, do not show macro
9119           // expansion.
9120           SourceLocation SL = SizeOfArg->getExprLoc();
9121           SourceRange DSR = Dest->getSourceRange();
9122           SourceRange SSR = SizeOfArg->getSourceRange();
9123           SourceManager &SM = getSourceManager();
9124 
9125           if (SM.isMacroArgExpansion(SL)) {
9126             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9127             SL = SM.getSpellingLoc(SL);
9128             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9129                              SM.getSpellingLoc(DSR.getEnd()));
9130             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9131                              SM.getSpellingLoc(SSR.getEnd()));
9132           }
9133 
9134           DiagRuntimeBehavior(SL, SizeOfArg,
9135                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9136                                 << ReadableName
9137                                 << PointeeTy
9138                                 << DestTy
9139                                 << DSR
9140                                 << SSR);
9141           DiagRuntimeBehavior(SL, SizeOfArg,
9142                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9143                                 << ActionIdx
9144                                 << SSR);
9145 
9146           break;
9147         }
9148       }
9149 
9150       // Also check for cases where the sizeof argument is the exact same
9151       // type as the memory argument, and where it points to a user-defined
9152       // record type.
9153       if (SizeOfArgTy != QualType()) {
9154         if (PointeeTy->isRecordType() &&
9155             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9156           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9157                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9158                                 << FnName << SizeOfArgTy << ArgIdx
9159                                 << PointeeTy << Dest->getSourceRange()
9160                                 << LenExpr->getSourceRange());
9161           break;
9162         }
9163       }
9164     } else if (DestTy->isArrayType()) {
9165       PointeeTy = DestTy;
9166     }
9167 
9168     if (PointeeTy == QualType())
9169       continue;
9170 
9171     // Always complain about dynamic classes.
9172     bool IsContained;
9173     if (const CXXRecordDecl *ContainedRD =
9174             getContainedDynamicClass(PointeeTy, IsContained)) {
9175 
9176       unsigned OperationType = 0;
9177       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9178       // "overwritten" if we're warning about the destination for any call
9179       // but memcmp; otherwise a verb appropriate to the call.
9180       if (ArgIdx != 0 || IsCmp) {
9181         if (BId == Builtin::BImemcpy)
9182           OperationType = 1;
9183         else if(BId == Builtin::BImemmove)
9184           OperationType = 2;
9185         else if (IsCmp)
9186           OperationType = 3;
9187       }
9188 
9189       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9190                           PDiag(diag::warn_dyn_class_memaccess)
9191                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9192                               << IsContained << ContainedRD << OperationType
9193                               << Call->getCallee()->getSourceRange());
9194     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9195              BId != Builtin::BImemset)
9196       DiagRuntimeBehavior(
9197         Dest->getExprLoc(), Dest,
9198         PDiag(diag::warn_arc_object_memaccess)
9199           << ArgIdx << FnName << PointeeTy
9200           << Call->getCallee()->getSourceRange());
9201     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9202       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9203           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9204         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9205                             PDiag(diag::warn_cstruct_memaccess)
9206                                 << ArgIdx << FnName << PointeeTy << 0);
9207         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9208       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9209                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9210         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9211                             PDiag(diag::warn_cstruct_memaccess)
9212                                 << ArgIdx << FnName << PointeeTy << 1);
9213         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9214       } else {
9215         continue;
9216       }
9217     } else
9218       continue;
9219 
9220     DiagRuntimeBehavior(
9221       Dest->getExprLoc(), Dest,
9222       PDiag(diag::note_bad_memaccess_silence)
9223         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9224     break;
9225   }
9226 }
9227 
9228 // A little helper routine: ignore addition and subtraction of integer literals.
9229 // This intentionally does not ignore all integer constant expressions because
9230 // we don't want to remove sizeof().
9231 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9232   Ex = Ex->IgnoreParenCasts();
9233 
9234   while (true) {
9235     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9236     if (!BO || !BO->isAdditiveOp())
9237       break;
9238 
9239     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9240     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9241 
9242     if (isa<IntegerLiteral>(RHS))
9243       Ex = LHS;
9244     else if (isa<IntegerLiteral>(LHS))
9245       Ex = RHS;
9246     else
9247       break;
9248   }
9249 
9250   return Ex;
9251 }
9252 
9253 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9254                                                       ASTContext &Context) {
9255   // Only handle constant-sized or VLAs, but not flexible members.
9256   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9257     // Only issue the FIXIT for arrays of size > 1.
9258     if (CAT->getSize().getSExtValue() <= 1)
9259       return false;
9260   } else if (!Ty->isVariableArrayType()) {
9261     return false;
9262   }
9263   return true;
9264 }
9265 
9266 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9267 // be the size of the source, instead of the destination.
9268 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9269                                     IdentifierInfo *FnName) {
9270 
9271   // Don't crash if the user has the wrong number of arguments
9272   unsigned NumArgs = Call->getNumArgs();
9273   if ((NumArgs != 3) && (NumArgs != 4))
9274     return;
9275 
9276   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9277   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9278   const Expr *CompareWithSrc = nullptr;
9279 
9280   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9281                                      Call->getBeginLoc(), Call->getRParenLoc()))
9282     return;
9283 
9284   // Look for 'strlcpy(dst, x, sizeof(x))'
9285   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9286     CompareWithSrc = Ex;
9287   else {
9288     // Look for 'strlcpy(dst, x, strlen(x))'
9289     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9290       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9291           SizeCall->getNumArgs() == 1)
9292         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9293     }
9294   }
9295 
9296   if (!CompareWithSrc)
9297     return;
9298 
9299   // Determine if the argument to sizeof/strlen is equal to the source
9300   // argument.  In principle there's all kinds of things you could do
9301   // here, for instance creating an == expression and evaluating it with
9302   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9303   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9304   if (!SrcArgDRE)
9305     return;
9306 
9307   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9308   if (!CompareWithSrcDRE ||
9309       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9310     return;
9311 
9312   const Expr *OriginalSizeArg = Call->getArg(2);
9313   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9314       << OriginalSizeArg->getSourceRange() << FnName;
9315 
9316   // Output a FIXIT hint if the destination is an array (rather than a
9317   // pointer to an array).  This could be enhanced to handle some
9318   // pointers if we know the actual size, like if DstArg is 'array+2'
9319   // we could say 'sizeof(array)-2'.
9320   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9321   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9322     return;
9323 
9324   SmallString<128> sizeString;
9325   llvm::raw_svector_ostream OS(sizeString);
9326   OS << "sizeof(";
9327   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9328   OS << ")";
9329 
9330   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9331       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9332                                       OS.str());
9333 }
9334 
9335 /// Check if two expressions refer to the same declaration.
9336 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9337   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9338     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9339       return D1->getDecl() == D2->getDecl();
9340   return false;
9341 }
9342 
9343 static const Expr *getStrlenExprArg(const Expr *E) {
9344   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9345     const FunctionDecl *FD = CE->getDirectCallee();
9346     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9347       return nullptr;
9348     return CE->getArg(0)->IgnoreParenCasts();
9349   }
9350   return nullptr;
9351 }
9352 
9353 // Warn on anti-patterns as the 'size' argument to strncat.
9354 // The correct size argument should look like following:
9355 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9356 void Sema::CheckStrncatArguments(const CallExpr *CE,
9357                                  IdentifierInfo *FnName) {
9358   // Don't crash if the user has the wrong number of arguments.
9359   if (CE->getNumArgs() < 3)
9360     return;
9361   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9362   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9363   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9364 
9365   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9366                                      CE->getRParenLoc()))
9367     return;
9368 
9369   // Identify common expressions, which are wrongly used as the size argument
9370   // to strncat and may lead to buffer overflows.
9371   unsigned PatternType = 0;
9372   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9373     // - sizeof(dst)
9374     if (referToTheSameDecl(SizeOfArg, DstArg))
9375       PatternType = 1;
9376     // - sizeof(src)
9377     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9378       PatternType = 2;
9379   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9380     if (BE->getOpcode() == BO_Sub) {
9381       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9382       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9383       // - sizeof(dst) - strlen(dst)
9384       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9385           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9386         PatternType = 1;
9387       // - sizeof(src) - (anything)
9388       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9389         PatternType = 2;
9390     }
9391   }
9392 
9393   if (PatternType == 0)
9394     return;
9395 
9396   // Generate the diagnostic.
9397   SourceLocation SL = LenArg->getBeginLoc();
9398   SourceRange SR = LenArg->getSourceRange();
9399   SourceManager &SM = getSourceManager();
9400 
9401   // If the function is defined as a builtin macro, do not show macro expansion.
9402   if (SM.isMacroArgExpansion(SL)) {
9403     SL = SM.getSpellingLoc(SL);
9404     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9405                      SM.getSpellingLoc(SR.getEnd()));
9406   }
9407 
9408   // Check if the destination is an array (rather than a pointer to an array).
9409   QualType DstTy = DstArg->getType();
9410   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9411                                                                     Context);
9412   if (!isKnownSizeArray) {
9413     if (PatternType == 1)
9414       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9415     else
9416       Diag(SL, diag::warn_strncat_src_size) << SR;
9417     return;
9418   }
9419 
9420   if (PatternType == 1)
9421     Diag(SL, diag::warn_strncat_large_size) << SR;
9422   else
9423     Diag(SL, diag::warn_strncat_src_size) << SR;
9424 
9425   SmallString<128> sizeString;
9426   llvm::raw_svector_ostream OS(sizeString);
9427   OS << "sizeof(";
9428   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9429   OS << ") - ";
9430   OS << "strlen(";
9431   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9432   OS << ") - 1";
9433 
9434   Diag(SL, diag::note_strncat_wrong_size)
9435     << FixItHint::CreateReplacement(SR, OS.str());
9436 }
9437 
9438 void
9439 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9440                          SourceLocation ReturnLoc,
9441                          bool isObjCMethod,
9442                          const AttrVec *Attrs,
9443                          const FunctionDecl *FD) {
9444   // Check if the return value is null but should not be.
9445   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9446        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9447       CheckNonNullExpr(*this, RetValExp))
9448     Diag(ReturnLoc, diag::warn_null_ret)
9449       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9450 
9451   // C++11 [basic.stc.dynamic.allocation]p4:
9452   //   If an allocation function declared with a non-throwing
9453   //   exception-specification fails to allocate storage, it shall return
9454   //   a null pointer. Any other allocation function that fails to allocate
9455   //   storage shall indicate failure only by throwing an exception [...]
9456   if (FD) {
9457     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9458     if (Op == OO_New || Op == OO_Array_New) {
9459       const FunctionProtoType *Proto
9460         = FD->getType()->castAs<FunctionProtoType>();
9461       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9462           CheckNonNullExpr(*this, RetValExp))
9463         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9464           << FD << getLangOpts().CPlusPlus11;
9465     }
9466   }
9467 }
9468 
9469 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9470 
9471 /// Check for comparisons of floating point operands using != and ==.
9472 /// Issue a warning if these are no self-comparisons, as they are not likely
9473 /// to do what the programmer intended.
9474 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9475   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9476   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9477 
9478   // Special case: check for x == x (which is OK).
9479   // Do not emit warnings for such cases.
9480   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9481     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9482       if (DRL->getDecl() == DRR->getDecl())
9483         return;
9484 
9485   // Special case: check for comparisons against literals that can be exactly
9486   //  represented by APFloat.  In such cases, do not emit a warning.  This
9487   //  is a heuristic: often comparison against such literals are used to
9488   //  detect if a value in a variable has not changed.  This clearly can
9489   //  lead to false negatives.
9490   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9491     if (FLL->isExact())
9492       return;
9493   } else
9494     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9495       if (FLR->isExact())
9496         return;
9497 
9498   // Check for comparisons with builtin types.
9499   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9500     if (CL->getBuiltinCallee())
9501       return;
9502 
9503   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9504     if (CR->getBuiltinCallee())
9505       return;
9506 
9507   // Emit the diagnostic.
9508   Diag(Loc, diag::warn_floatingpoint_eq)
9509     << LHS->getSourceRange() << RHS->getSourceRange();
9510 }
9511 
9512 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9513 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9514 
9515 namespace {
9516 
9517 /// Structure recording the 'active' range of an integer-valued
9518 /// expression.
9519 struct IntRange {
9520   /// The number of bits active in the int.
9521   unsigned Width;
9522 
9523   /// True if the int is known not to have negative values.
9524   bool NonNegative;
9525 
9526   IntRange(unsigned Width, bool NonNegative)
9527       : Width(Width), NonNegative(NonNegative) {}
9528 
9529   /// Returns the range of the bool type.
9530   static IntRange forBoolType() {
9531     return IntRange(1, true);
9532   }
9533 
9534   /// Returns the range of an opaque value of the given integral type.
9535   static IntRange forValueOfType(ASTContext &C, QualType T) {
9536     return forValueOfCanonicalType(C,
9537                           T->getCanonicalTypeInternal().getTypePtr());
9538   }
9539 
9540   /// Returns the range of an opaque value of a canonical integral type.
9541   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9542     assert(T->isCanonicalUnqualified());
9543 
9544     if (const VectorType *VT = dyn_cast<VectorType>(T))
9545       T = VT->getElementType().getTypePtr();
9546     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9547       T = CT->getElementType().getTypePtr();
9548     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9549       T = AT->getValueType().getTypePtr();
9550 
9551     if (!C.getLangOpts().CPlusPlus) {
9552       // For enum types in C code, use the underlying datatype.
9553       if (const EnumType *ET = dyn_cast<EnumType>(T))
9554         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9555     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9556       // For enum types in C++, use the known bit width of the enumerators.
9557       EnumDecl *Enum = ET->getDecl();
9558       // In C++11, enums can have a fixed underlying type. Use this type to
9559       // compute the range.
9560       if (Enum->isFixed()) {
9561         return IntRange(C.getIntWidth(QualType(T, 0)),
9562                         !ET->isSignedIntegerOrEnumerationType());
9563       }
9564 
9565       unsigned NumPositive = Enum->getNumPositiveBits();
9566       unsigned NumNegative = Enum->getNumNegativeBits();
9567 
9568       if (NumNegative == 0)
9569         return IntRange(NumPositive, true/*NonNegative*/);
9570       else
9571         return IntRange(std::max(NumPositive + 1, NumNegative),
9572                         false/*NonNegative*/);
9573     }
9574 
9575     const BuiltinType *BT = cast<BuiltinType>(T);
9576     assert(BT->isInteger());
9577 
9578     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9579   }
9580 
9581   /// Returns the "target" range of a canonical integral type, i.e.
9582   /// the range of values expressible in the type.
9583   ///
9584   /// This matches forValueOfCanonicalType except that enums have the
9585   /// full range of their type, not the range of their enumerators.
9586   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9587     assert(T->isCanonicalUnqualified());
9588 
9589     if (const VectorType *VT = dyn_cast<VectorType>(T))
9590       T = VT->getElementType().getTypePtr();
9591     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9592       T = CT->getElementType().getTypePtr();
9593     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9594       T = AT->getValueType().getTypePtr();
9595     if (const EnumType *ET = dyn_cast<EnumType>(T))
9596       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9597 
9598     const BuiltinType *BT = cast<BuiltinType>(T);
9599     assert(BT->isInteger());
9600 
9601     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9602   }
9603 
9604   /// Returns the supremum of two ranges: i.e. their conservative merge.
9605   static IntRange join(IntRange L, IntRange R) {
9606     return IntRange(std::max(L.Width, R.Width),
9607                     L.NonNegative && R.NonNegative);
9608   }
9609 
9610   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9611   static IntRange meet(IntRange L, IntRange R) {
9612     return IntRange(std::min(L.Width, R.Width),
9613                     L.NonNegative || R.NonNegative);
9614   }
9615 };
9616 
9617 } // namespace
9618 
9619 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9620                               unsigned MaxWidth) {
9621   if (value.isSigned() && value.isNegative())
9622     return IntRange(value.getMinSignedBits(), false);
9623 
9624   if (value.getBitWidth() > MaxWidth)
9625     value = value.trunc(MaxWidth);
9626 
9627   // isNonNegative() just checks the sign bit without considering
9628   // signedness.
9629   return IntRange(value.getActiveBits(), true);
9630 }
9631 
9632 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9633                               unsigned MaxWidth) {
9634   if (result.isInt())
9635     return GetValueRange(C, result.getInt(), MaxWidth);
9636 
9637   if (result.isVector()) {
9638     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9639     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9640       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9641       R = IntRange::join(R, El);
9642     }
9643     return R;
9644   }
9645 
9646   if (result.isComplexInt()) {
9647     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9648     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9649     return IntRange::join(R, I);
9650   }
9651 
9652   // This can happen with lossless casts to intptr_t of "based" lvalues.
9653   // Assume it might use arbitrary bits.
9654   // FIXME: The only reason we need to pass the type in here is to get
9655   // the sign right on this one case.  It would be nice if APValue
9656   // preserved this.
9657   assert(result.isLValue() || result.isAddrLabelDiff());
9658   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9659 }
9660 
9661 static QualType GetExprType(const Expr *E) {
9662   QualType Ty = E->getType();
9663   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9664     Ty = AtomicRHS->getValueType();
9665   return Ty;
9666 }
9667 
9668 /// Pseudo-evaluate the given integer expression, estimating the
9669 /// range of values it might take.
9670 ///
9671 /// \param MaxWidth - the width to which the value will be truncated
9672 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9673   E = E->IgnoreParens();
9674 
9675   // Try a full evaluation first.
9676   Expr::EvalResult result;
9677   if (E->EvaluateAsRValue(result, C))
9678     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9679 
9680   // I think we only want to look through implicit casts here; if the
9681   // user has an explicit widening cast, we should treat the value as
9682   // being of the new, wider type.
9683   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9684     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9685       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9686 
9687     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9688 
9689     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9690                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9691 
9692     // Assume that non-integer casts can span the full range of the type.
9693     if (!isIntegerCast)
9694       return OutputTypeRange;
9695 
9696     IntRange SubRange
9697       = GetExprRange(C, CE->getSubExpr(),
9698                      std::min(MaxWidth, OutputTypeRange.Width));
9699 
9700     // Bail out if the subexpr's range is as wide as the cast type.
9701     if (SubRange.Width >= OutputTypeRange.Width)
9702       return OutputTypeRange;
9703 
9704     // Otherwise, we take the smaller width, and we're non-negative if
9705     // either the output type or the subexpr is.
9706     return IntRange(SubRange.Width,
9707                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9708   }
9709 
9710   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9711     // If we can fold the condition, just take that operand.
9712     bool CondResult;
9713     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9714       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9715                                         : CO->getFalseExpr(),
9716                           MaxWidth);
9717 
9718     // Otherwise, conservatively merge.
9719     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9720     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9721     return IntRange::join(L, R);
9722   }
9723 
9724   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9725     switch (BO->getOpcode()) {
9726     case BO_Cmp:
9727       llvm_unreachable("builtin <=> should have class type");
9728 
9729     // Boolean-valued operations are single-bit and positive.
9730     case BO_LAnd:
9731     case BO_LOr:
9732     case BO_LT:
9733     case BO_GT:
9734     case BO_LE:
9735     case BO_GE:
9736     case BO_EQ:
9737     case BO_NE:
9738       return IntRange::forBoolType();
9739 
9740     // The type of the assignments is the type of the LHS, so the RHS
9741     // is not necessarily the same type.
9742     case BO_MulAssign:
9743     case BO_DivAssign:
9744     case BO_RemAssign:
9745     case BO_AddAssign:
9746     case BO_SubAssign:
9747     case BO_XorAssign:
9748     case BO_OrAssign:
9749       // TODO: bitfields?
9750       return IntRange::forValueOfType(C, GetExprType(E));
9751 
9752     // Simple assignments just pass through the RHS, which will have
9753     // been coerced to the LHS type.
9754     case BO_Assign:
9755       // TODO: bitfields?
9756       return GetExprRange(C, BO->getRHS(), MaxWidth);
9757 
9758     // Operations with opaque sources are black-listed.
9759     case BO_PtrMemD:
9760     case BO_PtrMemI:
9761       return IntRange::forValueOfType(C, GetExprType(E));
9762 
9763     // Bitwise-and uses the *infinum* of the two source ranges.
9764     case BO_And:
9765     case BO_AndAssign:
9766       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9767                             GetExprRange(C, BO->getRHS(), MaxWidth));
9768 
9769     // Left shift gets black-listed based on a judgement call.
9770     case BO_Shl:
9771       // ...except that we want to treat '1 << (blah)' as logically
9772       // positive.  It's an important idiom.
9773       if (IntegerLiteral *I
9774             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9775         if (I->getValue() == 1) {
9776           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9777           return IntRange(R.Width, /*NonNegative*/ true);
9778         }
9779       }
9780       LLVM_FALLTHROUGH;
9781 
9782     case BO_ShlAssign:
9783       return IntRange::forValueOfType(C, GetExprType(E));
9784 
9785     // Right shift by a constant can narrow its left argument.
9786     case BO_Shr:
9787     case BO_ShrAssign: {
9788       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9789 
9790       // If the shift amount is a positive constant, drop the width by
9791       // that much.
9792       llvm::APSInt shift;
9793       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9794           shift.isNonNegative()) {
9795         unsigned zext = shift.getZExtValue();
9796         if (zext >= L.Width)
9797           L.Width = (L.NonNegative ? 0 : 1);
9798         else
9799           L.Width -= zext;
9800       }
9801 
9802       return L;
9803     }
9804 
9805     // Comma acts as its right operand.
9806     case BO_Comma:
9807       return GetExprRange(C, BO->getRHS(), MaxWidth);
9808 
9809     // Black-list pointer subtractions.
9810     case BO_Sub:
9811       if (BO->getLHS()->getType()->isPointerType())
9812         return IntRange::forValueOfType(C, GetExprType(E));
9813       break;
9814 
9815     // The width of a division result is mostly determined by the size
9816     // of the LHS.
9817     case BO_Div: {
9818       // Don't 'pre-truncate' the operands.
9819       unsigned opWidth = C.getIntWidth(GetExprType(E));
9820       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9821 
9822       // If the divisor is constant, use that.
9823       llvm::APSInt divisor;
9824       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9825         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9826         if (log2 >= L.Width)
9827           L.Width = (L.NonNegative ? 0 : 1);
9828         else
9829           L.Width = std::min(L.Width - log2, MaxWidth);
9830         return L;
9831       }
9832 
9833       // Otherwise, just use the LHS's width.
9834       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9835       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9836     }
9837 
9838     // The result of a remainder can't be larger than the result of
9839     // either side.
9840     case BO_Rem: {
9841       // Don't 'pre-truncate' the operands.
9842       unsigned opWidth = C.getIntWidth(GetExprType(E));
9843       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9844       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9845 
9846       IntRange meet = IntRange::meet(L, R);
9847       meet.Width = std::min(meet.Width, MaxWidth);
9848       return meet;
9849     }
9850 
9851     // The default behavior is okay for these.
9852     case BO_Mul:
9853     case BO_Add:
9854     case BO_Xor:
9855     case BO_Or:
9856       break;
9857     }
9858 
9859     // The default case is to treat the operation as if it were closed
9860     // on the narrowest type that encompasses both operands.
9861     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9862     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9863     return IntRange::join(L, R);
9864   }
9865 
9866   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9867     switch (UO->getOpcode()) {
9868     // Boolean-valued operations are white-listed.
9869     case UO_LNot:
9870       return IntRange::forBoolType();
9871 
9872     // Operations with opaque sources are black-listed.
9873     case UO_Deref:
9874     case UO_AddrOf: // should be impossible
9875       return IntRange::forValueOfType(C, GetExprType(E));
9876 
9877     default:
9878       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9879     }
9880   }
9881 
9882   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9883     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9884 
9885   if (const auto *BitField = E->getSourceBitField())
9886     return IntRange(BitField->getBitWidthValue(C),
9887                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9888 
9889   return IntRange::forValueOfType(C, GetExprType(E));
9890 }
9891 
9892 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9893   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9894 }
9895 
9896 /// Checks whether the given value, which currently has the given
9897 /// source semantics, has the same value when coerced through the
9898 /// target semantics.
9899 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9900                                  const llvm::fltSemantics &Src,
9901                                  const llvm::fltSemantics &Tgt) {
9902   llvm::APFloat truncated = value;
9903 
9904   bool ignored;
9905   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9906   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9907 
9908   return truncated.bitwiseIsEqual(value);
9909 }
9910 
9911 /// Checks whether the given value, which currently has the given
9912 /// source semantics, has the same value when coerced through the
9913 /// target semantics.
9914 ///
9915 /// The value might be a vector of floats (or a complex number).
9916 static bool IsSameFloatAfterCast(const APValue &value,
9917                                  const llvm::fltSemantics &Src,
9918                                  const llvm::fltSemantics &Tgt) {
9919   if (value.isFloat())
9920     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9921 
9922   if (value.isVector()) {
9923     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9924       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9925         return false;
9926     return true;
9927   }
9928 
9929   assert(value.isComplexFloat());
9930   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9931           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9932 }
9933 
9934 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9935 
9936 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9937   // Suppress cases where we are comparing against an enum constant.
9938   if (const DeclRefExpr *DR =
9939       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9940     if (isa<EnumConstantDecl>(DR->getDecl()))
9941       return true;
9942 
9943   // Suppress cases where the '0' value is expanded from a macro.
9944   if (E->getBeginLoc().isMacroID())
9945     return true;
9946 
9947   return false;
9948 }
9949 
9950 static bool isKnownToHaveUnsignedValue(Expr *E) {
9951   return E->getType()->isIntegerType() &&
9952          (!E->getType()->isSignedIntegerType() ||
9953           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9954 }
9955 
9956 namespace {
9957 /// The promoted range of values of a type. In general this has the
9958 /// following structure:
9959 ///
9960 ///     |-----------| . . . |-----------|
9961 ///     ^           ^       ^           ^
9962 ///    Min       HoleMin  HoleMax      Max
9963 ///
9964 /// ... where there is only a hole if a signed type is promoted to unsigned
9965 /// (in which case Min and Max are the smallest and largest representable
9966 /// values).
9967 struct PromotedRange {
9968   // Min, or HoleMax if there is a hole.
9969   llvm::APSInt PromotedMin;
9970   // Max, or HoleMin if there is a hole.
9971   llvm::APSInt PromotedMax;
9972 
9973   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9974     if (R.Width == 0)
9975       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9976     else if (R.Width >= BitWidth && !Unsigned) {
9977       // Promotion made the type *narrower*. This happens when promoting
9978       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9979       // Treat all values of 'signed int' as being in range for now.
9980       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9981       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9982     } else {
9983       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9984                         .extOrTrunc(BitWidth);
9985       PromotedMin.setIsUnsigned(Unsigned);
9986 
9987       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9988                         .extOrTrunc(BitWidth);
9989       PromotedMax.setIsUnsigned(Unsigned);
9990     }
9991   }
9992 
9993   // Determine whether this range is contiguous (has no hole).
9994   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9995 
9996   // Where a constant value is within the range.
9997   enum ComparisonResult {
9998     LT = 0x1,
9999     LE = 0x2,
10000     GT = 0x4,
10001     GE = 0x8,
10002     EQ = 0x10,
10003     NE = 0x20,
10004     InRangeFlag = 0x40,
10005 
10006     Less = LE | LT | NE,
10007     Min = LE | InRangeFlag,
10008     InRange = InRangeFlag,
10009     Max = GE | InRangeFlag,
10010     Greater = GE | GT | NE,
10011 
10012     OnlyValue = LE | GE | EQ | InRangeFlag,
10013     InHole = NE
10014   };
10015 
10016   ComparisonResult compare(const llvm::APSInt &Value) const {
10017     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10018            Value.isUnsigned() == PromotedMin.isUnsigned());
10019     if (!isContiguous()) {
10020       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10021       if (Value.isMinValue()) return Min;
10022       if (Value.isMaxValue()) return Max;
10023       if (Value >= PromotedMin) return InRange;
10024       if (Value <= PromotedMax) return InRange;
10025       return InHole;
10026     }
10027 
10028     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10029     case -1: return Less;
10030     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10031     case 1:
10032       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10033       case -1: return InRange;
10034       case 0: return Max;
10035       case 1: return Greater;
10036       }
10037     }
10038 
10039     llvm_unreachable("impossible compare result");
10040   }
10041 
10042   static llvm::Optional<StringRef>
10043   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10044     if (Op == BO_Cmp) {
10045       ComparisonResult LTFlag = LT, GTFlag = GT;
10046       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10047 
10048       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10049       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10050       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10051       return llvm::None;
10052     }
10053 
10054     ComparisonResult TrueFlag, FalseFlag;
10055     if (Op == BO_EQ) {
10056       TrueFlag = EQ;
10057       FalseFlag = NE;
10058     } else if (Op == BO_NE) {
10059       TrueFlag = NE;
10060       FalseFlag = EQ;
10061     } else {
10062       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10063         TrueFlag = LT;
10064         FalseFlag = GE;
10065       } else {
10066         TrueFlag = GT;
10067         FalseFlag = LE;
10068       }
10069       if (Op == BO_GE || Op == BO_LE)
10070         std::swap(TrueFlag, FalseFlag);
10071     }
10072     if (R & TrueFlag)
10073       return StringRef("true");
10074     if (R & FalseFlag)
10075       return StringRef("false");
10076     return llvm::None;
10077   }
10078 };
10079 }
10080 
10081 static bool HasEnumType(Expr *E) {
10082   // Strip off implicit integral promotions.
10083   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10084     if (ICE->getCastKind() != CK_IntegralCast &&
10085         ICE->getCastKind() != CK_NoOp)
10086       break;
10087     E = ICE->getSubExpr();
10088   }
10089 
10090   return E->getType()->isEnumeralType();
10091 }
10092 
10093 static int classifyConstantValue(Expr *Constant) {
10094   // The values of this enumeration are used in the diagnostics
10095   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10096   enum ConstantValueKind {
10097     Miscellaneous = 0,
10098     LiteralTrue,
10099     LiteralFalse
10100   };
10101   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10102     return BL->getValue() ? ConstantValueKind::LiteralTrue
10103                           : ConstantValueKind::LiteralFalse;
10104   return ConstantValueKind::Miscellaneous;
10105 }
10106 
10107 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10108                                         Expr *Constant, Expr *Other,
10109                                         const llvm::APSInt &Value,
10110                                         bool RhsConstant) {
10111   if (S.inTemplateInstantiation())
10112     return false;
10113 
10114   Expr *OriginalOther = Other;
10115 
10116   Constant = Constant->IgnoreParenImpCasts();
10117   Other = Other->IgnoreParenImpCasts();
10118 
10119   // Suppress warnings on tautological comparisons between values of the same
10120   // enumeration type. There are only two ways we could warn on this:
10121   //  - If the constant is outside the range of representable values of
10122   //    the enumeration. In such a case, we should warn about the cast
10123   //    to enumeration type, not about the comparison.
10124   //  - If the constant is the maximum / minimum in-range value. For an
10125   //    enumeratin type, such comparisons can be meaningful and useful.
10126   if (Constant->getType()->isEnumeralType() &&
10127       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10128     return false;
10129 
10130   // TODO: Investigate using GetExprRange() to get tighter bounds
10131   // on the bit ranges.
10132   QualType OtherT = Other->getType();
10133   if (const auto *AT = OtherT->getAs<AtomicType>())
10134     OtherT = AT->getValueType();
10135   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10136 
10137   // Whether we're treating Other as being a bool because of the form of
10138   // expression despite it having another type (typically 'int' in C).
10139   bool OtherIsBooleanDespiteType =
10140       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10141   if (OtherIsBooleanDespiteType)
10142     OtherRange = IntRange::forBoolType();
10143 
10144   // Determine the promoted range of the other type and see if a comparison of
10145   // the constant against that range is tautological.
10146   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10147                                    Value.isUnsigned());
10148   auto Cmp = OtherPromotedRange.compare(Value);
10149   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10150   if (!Result)
10151     return false;
10152 
10153   // Suppress the diagnostic for an in-range comparison if the constant comes
10154   // from a macro or enumerator. We don't want to diagnose
10155   //
10156   //   some_long_value <= INT_MAX
10157   //
10158   // when sizeof(int) == sizeof(long).
10159   bool InRange = Cmp & PromotedRange::InRangeFlag;
10160   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10161     return false;
10162 
10163   // If this is a comparison to an enum constant, include that
10164   // constant in the diagnostic.
10165   const EnumConstantDecl *ED = nullptr;
10166   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10167     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10168 
10169   // Should be enough for uint128 (39 decimal digits)
10170   SmallString<64> PrettySourceValue;
10171   llvm::raw_svector_ostream OS(PrettySourceValue);
10172   if (ED)
10173     OS << '\'' << *ED << "' (" << Value << ")";
10174   else
10175     OS << Value;
10176 
10177   // FIXME: We use a somewhat different formatting for the in-range cases and
10178   // cases involving boolean values for historical reasons. We should pick a
10179   // consistent way of presenting these diagnostics.
10180   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10181     S.DiagRuntimeBehavior(
10182       E->getOperatorLoc(), E,
10183       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10184                        : diag::warn_tautological_bool_compare)
10185           << OS.str() << classifyConstantValue(Constant)
10186           << OtherT << OtherIsBooleanDespiteType << *Result
10187           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10188   } else {
10189     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10190                         ? (HasEnumType(OriginalOther)
10191                                ? diag::warn_unsigned_enum_always_true_comparison
10192                                : diag::warn_unsigned_always_true_comparison)
10193                         : diag::warn_tautological_constant_compare;
10194 
10195     S.Diag(E->getOperatorLoc(), Diag)
10196         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10197         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10198   }
10199 
10200   return true;
10201 }
10202 
10203 /// Analyze the operands of the given comparison.  Implements the
10204 /// fallback case from AnalyzeComparison.
10205 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10206   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10207   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10208 }
10209 
10210 /// Implements -Wsign-compare.
10211 ///
10212 /// \param E the binary operator to check for warnings
10213 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10214   // The type the comparison is being performed in.
10215   QualType T = E->getLHS()->getType();
10216 
10217   // Only analyze comparison operators where both sides have been converted to
10218   // the same type.
10219   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10220     return AnalyzeImpConvsInComparison(S, E);
10221 
10222   // Don't analyze value-dependent comparisons directly.
10223   if (E->isValueDependent())
10224     return AnalyzeImpConvsInComparison(S, E);
10225 
10226   Expr *LHS = E->getLHS();
10227   Expr *RHS = E->getRHS();
10228 
10229   if (T->isIntegralType(S.Context)) {
10230     llvm::APSInt RHSValue;
10231     llvm::APSInt LHSValue;
10232 
10233     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10234     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10235 
10236     // We don't care about expressions whose result is a constant.
10237     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10238       return AnalyzeImpConvsInComparison(S, E);
10239 
10240     // We only care about expressions where just one side is literal
10241     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10242       // Is the constant on the RHS or LHS?
10243       const bool RhsConstant = IsRHSIntegralLiteral;
10244       Expr *Const = RhsConstant ? RHS : LHS;
10245       Expr *Other = RhsConstant ? LHS : RHS;
10246       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10247 
10248       // Check whether an integer constant comparison results in a value
10249       // of 'true' or 'false'.
10250       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10251         return AnalyzeImpConvsInComparison(S, E);
10252     }
10253   }
10254 
10255   if (!T->hasUnsignedIntegerRepresentation()) {
10256     // We don't do anything special if this isn't an unsigned integral
10257     // comparison:  we're only interested in integral comparisons, and
10258     // signed comparisons only happen in cases we don't care to warn about.
10259     return AnalyzeImpConvsInComparison(S, E);
10260   }
10261 
10262   LHS = LHS->IgnoreParenImpCasts();
10263   RHS = RHS->IgnoreParenImpCasts();
10264 
10265   if (!S.getLangOpts().CPlusPlus) {
10266     // Avoid warning about comparison of integers with different signs when
10267     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10268     // the type of `E`.
10269     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10270       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10271     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10272       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10273   }
10274 
10275   // Check to see if one of the (unmodified) operands is of different
10276   // signedness.
10277   Expr *signedOperand, *unsignedOperand;
10278   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10279     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10280            "unsigned comparison between two signed integer expressions?");
10281     signedOperand = LHS;
10282     unsignedOperand = RHS;
10283   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10284     signedOperand = RHS;
10285     unsignedOperand = LHS;
10286   } else {
10287     return AnalyzeImpConvsInComparison(S, E);
10288   }
10289 
10290   // Otherwise, calculate the effective range of the signed operand.
10291   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10292 
10293   // Go ahead and analyze implicit conversions in the operands.  Note
10294   // that we skip the implicit conversions on both sides.
10295   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10296   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10297 
10298   // If the signed range is non-negative, -Wsign-compare won't fire.
10299   if (signedRange.NonNegative)
10300     return;
10301 
10302   // For (in)equality comparisons, if the unsigned operand is a
10303   // constant which cannot collide with a overflowed signed operand,
10304   // then reinterpreting the signed operand as unsigned will not
10305   // change the result of the comparison.
10306   if (E->isEqualityOp()) {
10307     unsigned comparisonWidth = S.Context.getIntWidth(T);
10308     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10309 
10310     // We should never be unable to prove that the unsigned operand is
10311     // non-negative.
10312     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10313 
10314     if (unsignedRange.Width < comparisonWidth)
10315       return;
10316   }
10317 
10318   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10319     S.PDiag(diag::warn_mixed_sign_comparison)
10320       << LHS->getType() << RHS->getType()
10321       << LHS->getSourceRange() << RHS->getSourceRange());
10322 }
10323 
10324 /// Analyzes an attempt to assign the given value to a bitfield.
10325 ///
10326 /// Returns true if there was something fishy about the attempt.
10327 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10328                                       SourceLocation InitLoc) {
10329   assert(Bitfield->isBitField());
10330   if (Bitfield->isInvalidDecl())
10331     return false;
10332 
10333   // White-list bool bitfields.
10334   QualType BitfieldType = Bitfield->getType();
10335   if (BitfieldType->isBooleanType())
10336      return false;
10337 
10338   if (BitfieldType->isEnumeralType()) {
10339     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10340     // If the underlying enum type was not explicitly specified as an unsigned
10341     // type and the enum contain only positive values, MSVC++ will cause an
10342     // inconsistency by storing this as a signed type.
10343     if (S.getLangOpts().CPlusPlus11 &&
10344         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10345         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10346         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10347       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10348         << BitfieldEnumDecl->getNameAsString();
10349     }
10350   }
10351 
10352   if (Bitfield->getType()->isBooleanType())
10353     return false;
10354 
10355   // Ignore value- or type-dependent expressions.
10356   if (Bitfield->getBitWidth()->isValueDependent() ||
10357       Bitfield->getBitWidth()->isTypeDependent() ||
10358       Init->isValueDependent() ||
10359       Init->isTypeDependent())
10360     return false;
10361 
10362   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10363   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10364 
10365   Expr::EvalResult Result;
10366   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10367                                    Expr::SE_AllowSideEffects)) {
10368     // The RHS is not constant.  If the RHS has an enum type, make sure the
10369     // bitfield is wide enough to hold all the values of the enum without
10370     // truncation.
10371     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10372       EnumDecl *ED = EnumTy->getDecl();
10373       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10374 
10375       // Enum types are implicitly signed on Windows, so check if there are any
10376       // negative enumerators to see if the enum was intended to be signed or
10377       // not.
10378       bool SignedEnum = ED->getNumNegativeBits() > 0;
10379 
10380       // Check for surprising sign changes when assigning enum values to a
10381       // bitfield of different signedness.  If the bitfield is signed and we
10382       // have exactly the right number of bits to store this unsigned enum,
10383       // suggest changing the enum to an unsigned type. This typically happens
10384       // on Windows where unfixed enums always use an underlying type of 'int'.
10385       unsigned DiagID = 0;
10386       if (SignedEnum && !SignedBitfield) {
10387         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10388       } else if (SignedBitfield && !SignedEnum &&
10389                  ED->getNumPositiveBits() == FieldWidth) {
10390         DiagID = diag::warn_signed_bitfield_enum_conversion;
10391       }
10392 
10393       if (DiagID) {
10394         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10395         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10396         SourceRange TypeRange =
10397             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10398         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10399             << SignedEnum << TypeRange;
10400       }
10401 
10402       // Compute the required bitwidth. If the enum has negative values, we need
10403       // one more bit than the normal number of positive bits to represent the
10404       // sign bit.
10405       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10406                                                   ED->getNumNegativeBits())
10407                                        : ED->getNumPositiveBits();
10408 
10409       // Check the bitwidth.
10410       if (BitsNeeded > FieldWidth) {
10411         Expr *WidthExpr = Bitfield->getBitWidth();
10412         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10413             << Bitfield << ED;
10414         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10415             << BitsNeeded << ED << WidthExpr->getSourceRange();
10416       }
10417     }
10418 
10419     return false;
10420   }
10421 
10422   llvm::APSInt Value = Result.Val.getInt();
10423 
10424   unsigned OriginalWidth = Value.getBitWidth();
10425 
10426   if (!Value.isSigned() || Value.isNegative())
10427     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10428       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10429         OriginalWidth = Value.getMinSignedBits();
10430 
10431   if (OriginalWidth <= FieldWidth)
10432     return false;
10433 
10434   // Compute the value which the bitfield will contain.
10435   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10436   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10437 
10438   // Check whether the stored value is equal to the original value.
10439   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10440   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10441     return false;
10442 
10443   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10444   // therefore don't strictly fit into a signed bitfield of width 1.
10445   if (FieldWidth == 1 && Value == 1)
10446     return false;
10447 
10448   std::string PrettyValue = Value.toString(10);
10449   std::string PrettyTrunc = TruncatedValue.toString(10);
10450 
10451   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10452     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10453     << Init->getSourceRange();
10454 
10455   return true;
10456 }
10457 
10458 /// Analyze the given simple or compound assignment for warning-worthy
10459 /// operations.
10460 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10461   // Just recurse on the LHS.
10462   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10463 
10464   // We want to recurse on the RHS as normal unless we're assigning to
10465   // a bitfield.
10466   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10467     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10468                                   E->getOperatorLoc())) {
10469       // Recurse, ignoring any implicit conversions on the RHS.
10470       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10471                                         E->getOperatorLoc());
10472     }
10473   }
10474 
10475   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10476 
10477   // Diagnose implicitly sequentially-consistent atomic assignment.
10478   if (E->getLHS()->getType()->isAtomicType())
10479     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10480 }
10481 
10482 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10483 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10484                             SourceLocation CContext, unsigned diag,
10485                             bool pruneControlFlow = false) {
10486   if (pruneControlFlow) {
10487     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10488                           S.PDiag(diag)
10489                             << SourceType << T << E->getSourceRange()
10490                             << SourceRange(CContext));
10491     return;
10492   }
10493   S.Diag(E->getExprLoc(), diag)
10494     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10495 }
10496 
10497 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10498 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10499                             SourceLocation CContext,
10500                             unsigned diag, bool pruneControlFlow = false) {
10501   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10502 }
10503 
10504 /// Diagnose an implicit cast from a floating point value to an integer value.
10505 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10506                                     SourceLocation CContext) {
10507   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10508   const bool PruneWarnings = S.inTemplateInstantiation();
10509 
10510   Expr *InnerE = E->IgnoreParenImpCasts();
10511   // We also want to warn on, e.g., "int i = -1.234"
10512   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10513     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10514       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10515 
10516   const bool IsLiteral =
10517       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10518 
10519   llvm::APFloat Value(0.0);
10520   bool IsConstant =
10521     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10522   if (!IsConstant) {
10523     return DiagnoseImpCast(S, E, T, CContext,
10524                            diag::warn_impcast_float_integer, PruneWarnings);
10525   }
10526 
10527   bool isExact = false;
10528 
10529   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10530                             T->hasUnsignedIntegerRepresentation());
10531   llvm::APFloat::opStatus Result = Value.convertToInteger(
10532       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10533 
10534   if (Result == llvm::APFloat::opOK && isExact) {
10535     if (IsLiteral) return;
10536     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10537                            PruneWarnings);
10538   }
10539 
10540   // Conversion of a floating-point value to a non-bool integer where the
10541   // integral part cannot be represented by the integer type is undefined.
10542   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10543     return DiagnoseImpCast(
10544         S, E, T, CContext,
10545         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10546                   : diag::warn_impcast_float_to_integer_out_of_range,
10547         PruneWarnings);
10548 
10549   unsigned DiagID = 0;
10550   if (IsLiteral) {
10551     // Warn on floating point literal to integer.
10552     DiagID = diag::warn_impcast_literal_float_to_integer;
10553   } else if (IntegerValue == 0) {
10554     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10555       return DiagnoseImpCast(S, E, T, CContext,
10556                              diag::warn_impcast_float_integer, PruneWarnings);
10557     }
10558     // Warn on non-zero to zero conversion.
10559     DiagID = diag::warn_impcast_float_to_integer_zero;
10560   } else {
10561     if (IntegerValue.isUnsigned()) {
10562       if (!IntegerValue.isMaxValue()) {
10563         return DiagnoseImpCast(S, E, T, CContext,
10564                                diag::warn_impcast_float_integer, PruneWarnings);
10565       }
10566     } else {  // IntegerValue.isSigned()
10567       if (!IntegerValue.isMaxSignedValue() &&
10568           !IntegerValue.isMinSignedValue()) {
10569         return DiagnoseImpCast(S, E, T, CContext,
10570                                diag::warn_impcast_float_integer, PruneWarnings);
10571       }
10572     }
10573     // Warn on evaluatable floating point expression to integer conversion.
10574     DiagID = diag::warn_impcast_float_to_integer;
10575   }
10576 
10577   // FIXME: Force the precision of the source value down so we don't print
10578   // digits which are usually useless (we don't really care here if we
10579   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10580   // would automatically print the shortest representation, but it's a bit
10581   // tricky to implement.
10582   SmallString<16> PrettySourceValue;
10583   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10584   precision = (precision * 59 + 195) / 196;
10585   Value.toString(PrettySourceValue, precision);
10586 
10587   SmallString<16> PrettyTargetValue;
10588   if (IsBool)
10589     PrettyTargetValue = Value.isZero() ? "false" : "true";
10590   else
10591     IntegerValue.toString(PrettyTargetValue);
10592 
10593   if (PruneWarnings) {
10594     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10595                           S.PDiag(DiagID)
10596                               << E->getType() << T.getUnqualifiedType()
10597                               << PrettySourceValue << PrettyTargetValue
10598                               << E->getSourceRange() << SourceRange(CContext));
10599   } else {
10600     S.Diag(E->getExprLoc(), DiagID)
10601         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10602         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10603   }
10604 }
10605 
10606 /// Analyze the given compound assignment for the possible losing of
10607 /// floating-point precision.
10608 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10609   assert(isa<CompoundAssignOperator>(E) &&
10610          "Must be compound assignment operation");
10611   // Recurse on the LHS and RHS in here
10612   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10613   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10614 
10615   if (E->getLHS()->getType()->isAtomicType())
10616     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10617 
10618   // Now check the outermost expression
10619   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10620   const auto *RBT = cast<CompoundAssignOperator>(E)
10621                         ->getComputationResultType()
10622                         ->getAs<BuiltinType>();
10623 
10624   // The below checks assume source is floating point.
10625   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10626 
10627   // If source is floating point but target is an integer.
10628   if (ResultBT->isInteger())
10629     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10630                            E->getExprLoc(), diag::warn_impcast_float_integer);
10631 
10632   if (!ResultBT->isFloatingPoint())
10633     return;
10634 
10635   // If both source and target are floating points, warn about losing precision.
10636   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10637       QualType(ResultBT, 0), QualType(RBT, 0));
10638   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10639     // warn about dropping FP rank.
10640     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10641                     diag::warn_impcast_float_result_precision);
10642 }
10643 
10644 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10645                                       IntRange Range) {
10646   if (!Range.Width) return "0";
10647 
10648   llvm::APSInt ValueInRange = Value;
10649   ValueInRange.setIsSigned(!Range.NonNegative);
10650   ValueInRange = ValueInRange.trunc(Range.Width);
10651   return ValueInRange.toString(10);
10652 }
10653 
10654 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10655   if (!isa<ImplicitCastExpr>(Ex))
10656     return false;
10657 
10658   Expr *InnerE = Ex->IgnoreParenImpCasts();
10659   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10660   const Type *Source =
10661     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10662   if (Target->isDependentType())
10663     return false;
10664 
10665   const BuiltinType *FloatCandidateBT =
10666     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10667   const Type *BoolCandidateType = ToBool ? Target : Source;
10668 
10669   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10670           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10671 }
10672 
10673 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10674                                              SourceLocation CC) {
10675   unsigned NumArgs = TheCall->getNumArgs();
10676   for (unsigned i = 0; i < NumArgs; ++i) {
10677     Expr *CurrA = TheCall->getArg(i);
10678     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10679       continue;
10680 
10681     bool IsSwapped = ((i > 0) &&
10682         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10683     IsSwapped |= ((i < (NumArgs - 1)) &&
10684         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10685     if (IsSwapped) {
10686       // Warn on this floating-point to bool conversion.
10687       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10688                       CurrA->getType(), CC,
10689                       diag::warn_impcast_floating_point_to_bool);
10690     }
10691   }
10692 }
10693 
10694 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10695                                    SourceLocation CC) {
10696   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10697                         E->getExprLoc()))
10698     return;
10699 
10700   // Don't warn on functions which have return type nullptr_t.
10701   if (isa<CallExpr>(E))
10702     return;
10703 
10704   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10705   const Expr::NullPointerConstantKind NullKind =
10706       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10707   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10708     return;
10709 
10710   // Return if target type is a safe conversion.
10711   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10712       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10713     return;
10714 
10715   SourceLocation Loc = E->getSourceRange().getBegin();
10716 
10717   // Venture through the macro stacks to get to the source of macro arguments.
10718   // The new location is a better location than the complete location that was
10719   // passed in.
10720   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10721   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10722 
10723   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10724   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10725     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10726         Loc, S.SourceMgr, S.getLangOpts());
10727     if (MacroName == "NULL")
10728       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10729   }
10730 
10731   // Only warn if the null and context location are in the same macro expansion.
10732   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10733     return;
10734 
10735   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10736       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10737       << FixItHint::CreateReplacement(Loc,
10738                                       S.getFixItZeroLiteralForType(T, Loc));
10739 }
10740 
10741 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10742                                   ObjCArrayLiteral *ArrayLiteral);
10743 
10744 static void
10745 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10746                            ObjCDictionaryLiteral *DictionaryLiteral);
10747 
10748 /// Check a single element within a collection literal against the
10749 /// target element type.
10750 static void checkObjCCollectionLiteralElement(Sema &S,
10751                                               QualType TargetElementType,
10752                                               Expr *Element,
10753                                               unsigned ElementKind) {
10754   // Skip a bitcast to 'id' or qualified 'id'.
10755   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10756     if (ICE->getCastKind() == CK_BitCast &&
10757         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10758       Element = ICE->getSubExpr();
10759   }
10760 
10761   QualType ElementType = Element->getType();
10762   ExprResult ElementResult(Element);
10763   if (ElementType->getAs<ObjCObjectPointerType>() &&
10764       S.CheckSingleAssignmentConstraints(TargetElementType,
10765                                          ElementResult,
10766                                          false, false)
10767         != Sema::Compatible) {
10768     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10769         << ElementType << ElementKind << TargetElementType
10770         << Element->getSourceRange();
10771   }
10772 
10773   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10774     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10775   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10776     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10777 }
10778 
10779 /// Check an Objective-C array literal being converted to the given
10780 /// target type.
10781 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10782                                   ObjCArrayLiteral *ArrayLiteral) {
10783   if (!S.NSArrayDecl)
10784     return;
10785 
10786   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10787   if (!TargetObjCPtr)
10788     return;
10789 
10790   if (TargetObjCPtr->isUnspecialized() ||
10791       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10792         != S.NSArrayDecl->getCanonicalDecl())
10793     return;
10794 
10795   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10796   if (TypeArgs.size() != 1)
10797     return;
10798 
10799   QualType TargetElementType = TypeArgs[0];
10800   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10801     checkObjCCollectionLiteralElement(S, TargetElementType,
10802                                       ArrayLiteral->getElement(I),
10803                                       0);
10804   }
10805 }
10806 
10807 /// Check an Objective-C dictionary literal being converted to the given
10808 /// target type.
10809 static void
10810 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10811                            ObjCDictionaryLiteral *DictionaryLiteral) {
10812   if (!S.NSDictionaryDecl)
10813     return;
10814 
10815   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10816   if (!TargetObjCPtr)
10817     return;
10818 
10819   if (TargetObjCPtr->isUnspecialized() ||
10820       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10821         != S.NSDictionaryDecl->getCanonicalDecl())
10822     return;
10823 
10824   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10825   if (TypeArgs.size() != 2)
10826     return;
10827 
10828   QualType TargetKeyType = TypeArgs[0];
10829   QualType TargetObjectType = TypeArgs[1];
10830   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10831     auto Element = DictionaryLiteral->getKeyValueElement(I);
10832     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10833     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10834   }
10835 }
10836 
10837 // Helper function to filter out cases for constant width constant conversion.
10838 // Don't warn on char array initialization or for non-decimal values.
10839 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10840                                           SourceLocation CC) {
10841   // If initializing from a constant, and the constant starts with '0',
10842   // then it is a binary, octal, or hexadecimal.  Allow these constants
10843   // to fill all the bits, even if there is a sign change.
10844   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10845     const char FirstLiteralCharacter =
10846         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10847     if (FirstLiteralCharacter == '0')
10848       return false;
10849   }
10850 
10851   // If the CC location points to a '{', and the type is char, then assume
10852   // assume it is an array initialization.
10853   if (CC.isValid() && T->isCharType()) {
10854     const char FirstContextCharacter =
10855         S.getSourceManager().getCharacterData(CC)[0];
10856     if (FirstContextCharacter == '{')
10857       return false;
10858   }
10859 
10860   return true;
10861 }
10862 
10863 static void
10864 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10865                         bool *ICContext = nullptr) {
10866   if (E->isTypeDependent() || E->isValueDependent()) return;
10867 
10868   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10869   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10870   if (Source == Target) return;
10871   if (Target->isDependentType()) return;
10872 
10873   // If the conversion context location is invalid don't complain. We also
10874   // don't want to emit a warning if the issue occurs from the expansion of
10875   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10876   // delay this check as long as possible. Once we detect we are in that
10877   // scenario, we just return.
10878   if (CC.isInvalid())
10879     return;
10880 
10881   if (Source->isAtomicType())
10882     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10883 
10884   // Diagnose implicit casts to bool.
10885   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10886     if (isa<StringLiteral>(E))
10887       // Warn on string literal to bool.  Checks for string literals in logical
10888       // and expressions, for instance, assert(0 && "error here"), are
10889       // prevented by a check in AnalyzeImplicitConversions().
10890       return DiagnoseImpCast(S, E, T, CC,
10891                              diag::warn_impcast_string_literal_to_bool);
10892     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10893         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10894       // This covers the literal expressions that evaluate to Objective-C
10895       // objects.
10896       return DiagnoseImpCast(S, E, T, CC,
10897                              diag::warn_impcast_objective_c_literal_to_bool);
10898     }
10899     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10900       // Warn on pointer to bool conversion that is always true.
10901       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10902                                      SourceRange(CC));
10903     }
10904   }
10905 
10906   // Check implicit casts from Objective-C collection literals to specialized
10907   // collection types, e.g., NSArray<NSString *> *.
10908   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10909     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10910   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10911     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10912 
10913   // Strip vector types.
10914   if (isa<VectorType>(Source)) {
10915     if (!isa<VectorType>(Target)) {
10916       if (S.SourceMgr.isInSystemMacro(CC))
10917         return;
10918       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10919     }
10920 
10921     // If the vector cast is cast between two vectors of the same size, it is
10922     // a bitcast, not a conversion.
10923     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10924       return;
10925 
10926     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10927     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10928   }
10929   if (auto VecTy = dyn_cast<VectorType>(Target))
10930     Target = VecTy->getElementType().getTypePtr();
10931 
10932   // Strip complex types.
10933   if (isa<ComplexType>(Source)) {
10934     if (!isa<ComplexType>(Target)) {
10935       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10936         return;
10937 
10938       return DiagnoseImpCast(S, E, T, CC,
10939                              S.getLangOpts().CPlusPlus
10940                                  ? diag::err_impcast_complex_scalar
10941                                  : diag::warn_impcast_complex_scalar);
10942     }
10943 
10944     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10945     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10946   }
10947 
10948   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10949   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10950 
10951   // If the source is floating point...
10952   if (SourceBT && SourceBT->isFloatingPoint()) {
10953     // ...and the target is floating point...
10954     if (TargetBT && TargetBT->isFloatingPoint()) {
10955       // ...then warn if we're dropping FP rank.
10956 
10957       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10958           QualType(SourceBT, 0), QualType(TargetBT, 0));
10959       if (Order > 0) {
10960         // Don't warn about float constants that are precisely
10961         // representable in the target type.
10962         Expr::EvalResult result;
10963         if (E->EvaluateAsRValue(result, S.Context)) {
10964           // Value might be a float, a float vector, or a float complex.
10965           if (IsSameFloatAfterCast(result.Val,
10966                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10967                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10968             return;
10969         }
10970 
10971         if (S.SourceMgr.isInSystemMacro(CC))
10972           return;
10973 
10974         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10975       }
10976       // ... or possibly if we're increasing rank, too
10977       else if (Order < 0) {
10978         if (S.SourceMgr.isInSystemMacro(CC))
10979           return;
10980 
10981         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10982       }
10983       return;
10984     }
10985 
10986     // If the target is integral, always warn.
10987     if (TargetBT && TargetBT->isInteger()) {
10988       if (S.SourceMgr.isInSystemMacro(CC))
10989         return;
10990 
10991       DiagnoseFloatingImpCast(S, E, T, CC);
10992     }
10993 
10994     // Detect the case where a call result is converted from floating-point to
10995     // to bool, and the final argument to the call is converted from bool, to
10996     // discover this typo:
10997     //
10998     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10999     //
11000     // FIXME: This is an incredibly special case; is there some more general
11001     // way to detect this class of misplaced-parentheses bug?
11002     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11003       // Check last argument of function call to see if it is an
11004       // implicit cast from a type matching the type the result
11005       // is being cast to.
11006       CallExpr *CEx = cast<CallExpr>(E);
11007       if (unsigned NumArgs = CEx->getNumArgs()) {
11008         Expr *LastA = CEx->getArg(NumArgs - 1);
11009         Expr *InnerE = LastA->IgnoreParenImpCasts();
11010         if (isa<ImplicitCastExpr>(LastA) &&
11011             InnerE->getType()->isBooleanType()) {
11012           // Warn on this floating-point to bool conversion
11013           DiagnoseImpCast(S, E, T, CC,
11014                           diag::warn_impcast_floating_point_to_bool);
11015         }
11016       }
11017     }
11018     return;
11019   }
11020 
11021   // Valid casts involving fixed point types should be accounted for here.
11022   if (Source->isFixedPointType()) {
11023     if (Target->isUnsaturatedFixedPointType()) {
11024       Expr::EvalResult Result;
11025       if (E->EvaluateAsFixedPoint(Result, S.Context,
11026                                   Expr::SE_AllowSideEffects)) {
11027         APFixedPoint Value = Result.Val.getFixedPoint();
11028         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11029         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11030         if (Value > MaxVal || Value < MinVal) {
11031           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11032                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11033                                     << Value.toString() << T
11034                                     << E->getSourceRange()
11035                                     << clang::SourceRange(CC));
11036           return;
11037         }
11038       }
11039     } else if (Target->isIntegerType()) {
11040       Expr::EvalResult Result;
11041       if (E->EvaluateAsFixedPoint(Result, S.Context,
11042                                   Expr::SE_AllowSideEffects)) {
11043         APFixedPoint FXResult = Result.Val.getFixedPoint();
11044 
11045         bool Overflowed;
11046         llvm::APSInt IntResult = FXResult.convertToInt(
11047             S.Context.getIntWidth(T),
11048             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11049 
11050         if (Overflowed) {
11051           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11052                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11053                                     << FXResult.toString() << T
11054                                     << E->getSourceRange()
11055                                     << clang::SourceRange(CC));
11056           return;
11057         }
11058       }
11059     }
11060   } else if (Target->isUnsaturatedFixedPointType()) {
11061     if (Source->isIntegerType()) {
11062       Expr::EvalResult Result;
11063       if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11064         llvm::APSInt Value = Result.Val.getInt();
11065 
11066         bool Overflowed;
11067         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11068             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11069 
11070         if (Overflowed) {
11071           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11072                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11073                                     << Value.toString(/*radix=*/10) << T
11074                                     << E->getSourceRange()
11075                                     << clang::SourceRange(CC));
11076           return;
11077         }
11078       }
11079     }
11080   }
11081 
11082   DiagnoseNullConversion(S, E, T, CC);
11083 
11084   S.DiscardMisalignedMemberAddress(Target, E);
11085 
11086   if (!Source->isIntegerType() || !Target->isIntegerType())
11087     return;
11088 
11089   // TODO: remove this early return once the false positives for constant->bool
11090   // in templates, macros, etc, are reduced or removed.
11091   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11092     return;
11093 
11094   IntRange SourceRange = GetExprRange(S.Context, E);
11095   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11096 
11097   if (SourceRange.Width > TargetRange.Width) {
11098     // If the source is a constant, use a default-on diagnostic.
11099     // TODO: this should happen for bitfield stores, too.
11100     Expr::EvalResult Result;
11101     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11102       llvm::APSInt Value(32);
11103       Value = Result.Val.getInt();
11104 
11105       if (S.SourceMgr.isInSystemMacro(CC))
11106         return;
11107 
11108       std::string PrettySourceValue = Value.toString(10);
11109       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11110 
11111       S.DiagRuntimeBehavior(E->getExprLoc(), E,
11112         S.PDiag(diag::warn_impcast_integer_precision_constant)
11113             << PrettySourceValue << PrettyTargetValue
11114             << E->getType() << T << E->getSourceRange()
11115             << clang::SourceRange(CC));
11116       return;
11117     }
11118 
11119     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11120     if (S.SourceMgr.isInSystemMacro(CC))
11121       return;
11122 
11123     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11124       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11125                              /* pruneControlFlow */ true);
11126     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11127   }
11128 
11129   if (TargetRange.Width > SourceRange.Width) {
11130     if (auto *UO = dyn_cast<UnaryOperator>(E))
11131       if (UO->getOpcode() == UO_Minus)
11132         if (Source->isUnsignedIntegerType()) {
11133           if (Target->isUnsignedIntegerType())
11134             return DiagnoseImpCast(S, E, T, CC,
11135                                    diag::warn_impcast_high_order_zero_bits);
11136           if (Target->isSignedIntegerType())
11137             return DiagnoseImpCast(S, E, T, CC,
11138                                    diag::warn_impcast_nonnegative_result);
11139         }
11140   }
11141 
11142   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11143       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11144     // Warn when doing a signed to signed conversion, warn if the positive
11145     // source value is exactly the width of the target type, which will
11146     // cause a negative value to be stored.
11147 
11148     Expr::EvalResult Result;
11149     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11150         !S.SourceMgr.isInSystemMacro(CC)) {
11151       llvm::APSInt Value = Result.Val.getInt();
11152       if (isSameWidthConstantConversion(S, E, T, CC)) {
11153         std::string PrettySourceValue = Value.toString(10);
11154         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11155 
11156         S.DiagRuntimeBehavior(
11157             E->getExprLoc(), E,
11158             S.PDiag(diag::warn_impcast_integer_precision_constant)
11159                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11160                 << E->getSourceRange() << clang::SourceRange(CC));
11161         return;
11162       }
11163     }
11164 
11165     // Fall through for non-constants to give a sign conversion warning.
11166   }
11167 
11168   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11169       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11170        SourceRange.Width == TargetRange.Width)) {
11171     if (S.SourceMgr.isInSystemMacro(CC))
11172       return;
11173 
11174     unsigned DiagID = diag::warn_impcast_integer_sign;
11175 
11176     // Traditionally, gcc has warned about this under -Wsign-compare.
11177     // We also want to warn about it in -Wconversion.
11178     // So if -Wconversion is off, use a completely identical diagnostic
11179     // in the sign-compare group.
11180     // The conditional-checking code will
11181     if (ICContext) {
11182       DiagID = diag::warn_impcast_integer_sign_conditional;
11183       *ICContext = true;
11184     }
11185 
11186     return DiagnoseImpCast(S, E, T, CC, DiagID);
11187   }
11188 
11189   // Diagnose conversions between different enumeration types.
11190   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11191   // type, to give us better diagnostics.
11192   QualType SourceType = E->getType();
11193   if (!S.getLangOpts().CPlusPlus) {
11194     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11195       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11196         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11197         SourceType = S.Context.getTypeDeclType(Enum);
11198         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11199       }
11200   }
11201 
11202   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11203     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11204       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11205           TargetEnum->getDecl()->hasNameForLinkage() &&
11206           SourceEnum != TargetEnum) {
11207         if (S.SourceMgr.isInSystemMacro(CC))
11208           return;
11209 
11210         return DiagnoseImpCast(S, E, SourceType, T, CC,
11211                                diag::warn_impcast_different_enum_types);
11212       }
11213 }
11214 
11215 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11216                                      SourceLocation CC, QualType T);
11217 
11218 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11219                                     SourceLocation CC, bool &ICContext) {
11220   E = E->IgnoreParenImpCasts();
11221 
11222   if (isa<ConditionalOperator>(E))
11223     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11224 
11225   AnalyzeImplicitConversions(S, E, CC);
11226   if (E->getType() != T)
11227     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11228 }
11229 
11230 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11231                                      SourceLocation CC, QualType T) {
11232   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11233 
11234   bool Suspicious = false;
11235   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11236   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11237 
11238   // If -Wconversion would have warned about either of the candidates
11239   // for a signedness conversion to the context type...
11240   if (!Suspicious) return;
11241 
11242   // ...but it's currently ignored...
11243   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11244     return;
11245 
11246   // ...then check whether it would have warned about either of the
11247   // candidates for a signedness conversion to the condition type.
11248   if (E->getType() == T) return;
11249 
11250   Suspicious = false;
11251   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11252                           E->getType(), CC, &Suspicious);
11253   if (!Suspicious)
11254     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11255                             E->getType(), CC, &Suspicious);
11256 }
11257 
11258 /// Check conversion of given expression to boolean.
11259 /// Input argument E is a logical expression.
11260 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11261   if (S.getLangOpts().Bool)
11262     return;
11263   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11264     return;
11265   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11266 }
11267 
11268 /// AnalyzeImplicitConversions - Find and report any interesting
11269 /// implicit conversions in the given expression.  There are a couple
11270 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11271 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11272                                        SourceLocation CC) {
11273   QualType T = OrigE->getType();
11274   Expr *E = OrigE->IgnoreParenImpCasts();
11275 
11276   if (E->isTypeDependent() || E->isValueDependent())
11277     return;
11278 
11279   // For conditional operators, we analyze the arguments as if they
11280   // were being fed directly into the output.
11281   if (isa<ConditionalOperator>(E)) {
11282     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11283     CheckConditionalOperator(S, CO, CC, T);
11284     return;
11285   }
11286 
11287   // Check implicit argument conversions for function calls.
11288   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11289     CheckImplicitArgumentConversions(S, Call, CC);
11290 
11291   // Go ahead and check any implicit conversions we might have skipped.
11292   // The non-canonical typecheck is just an optimization;
11293   // CheckImplicitConversion will filter out dead implicit conversions.
11294   if (E->getType() != T)
11295     CheckImplicitConversion(S, E, T, CC);
11296 
11297   // Now continue drilling into this expression.
11298 
11299   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11300     // The bound subexpressions in a PseudoObjectExpr are not reachable
11301     // as transitive children.
11302     // FIXME: Use a more uniform representation for this.
11303     for (auto *SE : POE->semantics())
11304       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11305         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11306   }
11307 
11308   // Skip past explicit casts.
11309   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11310     E = CE->getSubExpr()->IgnoreParenImpCasts();
11311     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11312       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11313     return AnalyzeImplicitConversions(S, E, CC);
11314   }
11315 
11316   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11317     // Do a somewhat different check with comparison operators.
11318     if (BO->isComparisonOp())
11319       return AnalyzeComparison(S, BO);
11320 
11321     // And with simple assignments.
11322     if (BO->getOpcode() == BO_Assign)
11323       return AnalyzeAssignment(S, BO);
11324     // And with compound assignments.
11325     if (BO->isAssignmentOp())
11326       return AnalyzeCompoundAssignment(S, BO);
11327   }
11328 
11329   // These break the otherwise-useful invariant below.  Fortunately,
11330   // we don't really need to recurse into them, because any internal
11331   // expressions should have been analyzed already when they were
11332   // built into statements.
11333   if (isa<StmtExpr>(E)) return;
11334 
11335   // Don't descend into unevaluated contexts.
11336   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11337 
11338   // Now just recurse over the expression's children.
11339   CC = E->getExprLoc();
11340   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11341   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11342   for (Stmt *SubStmt : E->children()) {
11343     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11344     if (!ChildExpr)
11345       continue;
11346 
11347     if (IsLogicalAndOperator &&
11348         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11349       // Ignore checking string literals that are in logical and operators.
11350       // This is a common pattern for asserts.
11351       continue;
11352     AnalyzeImplicitConversions(S, ChildExpr, CC);
11353   }
11354 
11355   if (BO && BO->isLogicalOp()) {
11356     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11357     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11358       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11359 
11360     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11361     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11362       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11363   }
11364 
11365   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11366     if (U->getOpcode() == UO_LNot) {
11367       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11368     } else if (U->getOpcode() != UO_AddrOf) {
11369       if (U->getSubExpr()->getType()->isAtomicType())
11370         S.Diag(U->getSubExpr()->getBeginLoc(),
11371                diag::warn_atomic_implicit_seq_cst);
11372     }
11373   }
11374 }
11375 
11376 /// Diagnose integer type and any valid implicit conversion to it.
11377 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11378   // Taking into account implicit conversions,
11379   // allow any integer.
11380   if (!E->getType()->isIntegerType()) {
11381     S.Diag(E->getBeginLoc(),
11382            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11383     return true;
11384   }
11385   // Potentially emit standard warnings for implicit conversions if enabled
11386   // using -Wconversion.
11387   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11388   return false;
11389 }
11390 
11391 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11392 // Returns true when emitting a warning about taking the address of a reference.
11393 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11394                               const PartialDiagnostic &PD) {
11395   E = E->IgnoreParenImpCasts();
11396 
11397   const FunctionDecl *FD = nullptr;
11398 
11399   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11400     if (!DRE->getDecl()->getType()->isReferenceType())
11401       return false;
11402   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11403     if (!M->getMemberDecl()->getType()->isReferenceType())
11404       return false;
11405   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11406     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11407       return false;
11408     FD = Call->getDirectCallee();
11409   } else {
11410     return false;
11411   }
11412 
11413   SemaRef.Diag(E->getExprLoc(), PD);
11414 
11415   // If possible, point to location of function.
11416   if (FD) {
11417     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11418   }
11419 
11420   return true;
11421 }
11422 
11423 // Returns true if the SourceLocation is expanded from any macro body.
11424 // Returns false if the SourceLocation is invalid, is from not in a macro
11425 // expansion, or is from expanded from a top-level macro argument.
11426 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11427   if (Loc.isInvalid())
11428     return false;
11429 
11430   while (Loc.isMacroID()) {
11431     if (SM.isMacroBodyExpansion(Loc))
11432       return true;
11433     Loc = SM.getImmediateMacroCallerLoc(Loc);
11434   }
11435 
11436   return false;
11437 }
11438 
11439 /// Diagnose pointers that are always non-null.
11440 /// \param E the expression containing the pointer
11441 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11442 /// compared to a null pointer
11443 /// \param IsEqual True when the comparison is equal to a null pointer
11444 /// \param Range Extra SourceRange to highlight in the diagnostic
11445 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11446                                         Expr::NullPointerConstantKind NullKind,
11447                                         bool IsEqual, SourceRange Range) {
11448   if (!E)
11449     return;
11450 
11451   // Don't warn inside macros.
11452   if (E->getExprLoc().isMacroID()) {
11453     const SourceManager &SM = getSourceManager();
11454     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11455         IsInAnyMacroBody(SM, Range.getBegin()))
11456       return;
11457   }
11458   E = E->IgnoreImpCasts();
11459 
11460   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11461 
11462   if (isa<CXXThisExpr>(E)) {
11463     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11464                                 : diag::warn_this_bool_conversion;
11465     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11466     return;
11467   }
11468 
11469   bool IsAddressOf = false;
11470 
11471   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11472     if (UO->getOpcode() != UO_AddrOf)
11473       return;
11474     IsAddressOf = true;
11475     E = UO->getSubExpr();
11476   }
11477 
11478   if (IsAddressOf) {
11479     unsigned DiagID = IsCompare
11480                           ? diag::warn_address_of_reference_null_compare
11481                           : diag::warn_address_of_reference_bool_conversion;
11482     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11483                                          << IsEqual;
11484     if (CheckForReference(*this, E, PD)) {
11485       return;
11486     }
11487   }
11488 
11489   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11490     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11491     std::string Str;
11492     llvm::raw_string_ostream S(Str);
11493     E->printPretty(S, nullptr, getPrintingPolicy());
11494     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11495                                 : diag::warn_cast_nonnull_to_bool;
11496     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11497       << E->getSourceRange() << Range << IsEqual;
11498     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11499   };
11500 
11501   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11502   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11503     if (auto *Callee = Call->getDirectCallee()) {
11504       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11505         ComplainAboutNonnullParamOrCall(A);
11506         return;
11507       }
11508     }
11509   }
11510 
11511   // Expect to find a single Decl.  Skip anything more complicated.
11512   ValueDecl *D = nullptr;
11513   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11514     D = R->getDecl();
11515   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11516     D = M->getMemberDecl();
11517   }
11518 
11519   // Weak Decls can be null.
11520   if (!D || D->isWeak())
11521     return;
11522 
11523   // Check for parameter decl with nonnull attribute
11524   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11525     if (getCurFunction() &&
11526         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11527       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11528         ComplainAboutNonnullParamOrCall(A);
11529         return;
11530       }
11531 
11532       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11533         auto ParamIter = llvm::find(FD->parameters(), PV);
11534         assert(ParamIter != FD->param_end());
11535         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11536 
11537         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11538           if (!NonNull->args_size()) {
11539               ComplainAboutNonnullParamOrCall(NonNull);
11540               return;
11541           }
11542 
11543           for (const ParamIdx &ArgNo : NonNull->args()) {
11544             if (ArgNo.getASTIndex() == ParamNo) {
11545               ComplainAboutNonnullParamOrCall(NonNull);
11546               return;
11547             }
11548           }
11549         }
11550       }
11551     }
11552   }
11553 
11554   QualType T = D->getType();
11555   const bool IsArray = T->isArrayType();
11556   const bool IsFunction = T->isFunctionType();
11557 
11558   // Address of function is used to silence the function warning.
11559   if (IsAddressOf && IsFunction) {
11560     return;
11561   }
11562 
11563   // Found nothing.
11564   if (!IsAddressOf && !IsFunction && !IsArray)
11565     return;
11566 
11567   // Pretty print the expression for the diagnostic.
11568   std::string Str;
11569   llvm::raw_string_ostream S(Str);
11570   E->printPretty(S, nullptr, getPrintingPolicy());
11571 
11572   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11573                               : diag::warn_impcast_pointer_to_bool;
11574   enum {
11575     AddressOf,
11576     FunctionPointer,
11577     ArrayPointer
11578   } DiagType;
11579   if (IsAddressOf)
11580     DiagType = AddressOf;
11581   else if (IsFunction)
11582     DiagType = FunctionPointer;
11583   else if (IsArray)
11584     DiagType = ArrayPointer;
11585   else
11586     llvm_unreachable("Could not determine diagnostic.");
11587   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11588                                 << Range << IsEqual;
11589 
11590   if (!IsFunction)
11591     return;
11592 
11593   // Suggest '&' to silence the function warning.
11594   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11595       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11596 
11597   // Check to see if '()' fixit should be emitted.
11598   QualType ReturnType;
11599   UnresolvedSet<4> NonTemplateOverloads;
11600   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11601   if (ReturnType.isNull())
11602     return;
11603 
11604   if (IsCompare) {
11605     // There are two cases here.  If there is null constant, the only suggest
11606     // for a pointer return type.  If the null is 0, then suggest if the return
11607     // type is a pointer or an integer type.
11608     if (!ReturnType->isPointerType()) {
11609       if (NullKind == Expr::NPCK_ZeroExpression ||
11610           NullKind == Expr::NPCK_ZeroLiteral) {
11611         if (!ReturnType->isIntegerType())
11612           return;
11613       } else {
11614         return;
11615       }
11616     }
11617   } else { // !IsCompare
11618     // For function to bool, only suggest if the function pointer has bool
11619     // return type.
11620     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11621       return;
11622   }
11623   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11624       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11625 }
11626 
11627 /// Diagnoses "dangerous" implicit conversions within the given
11628 /// expression (which is a full expression).  Implements -Wconversion
11629 /// and -Wsign-compare.
11630 ///
11631 /// \param CC the "context" location of the implicit conversion, i.e.
11632 ///   the most location of the syntactic entity requiring the implicit
11633 ///   conversion
11634 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11635   // Don't diagnose in unevaluated contexts.
11636   if (isUnevaluatedContext())
11637     return;
11638 
11639   // Don't diagnose for value- or type-dependent expressions.
11640   if (E->isTypeDependent() || E->isValueDependent())
11641     return;
11642 
11643   // Check for array bounds violations in cases where the check isn't triggered
11644   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11645   // ArraySubscriptExpr is on the RHS of a variable initialization.
11646   CheckArrayAccess(E);
11647 
11648   // This is not the right CC for (e.g.) a variable initialization.
11649   AnalyzeImplicitConversions(*this, E, CC);
11650 }
11651 
11652 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11653 /// Input argument E is a logical expression.
11654 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11655   ::CheckBoolLikeConversion(*this, E, CC);
11656 }
11657 
11658 /// Diagnose when expression is an integer constant expression and its evaluation
11659 /// results in integer overflow
11660 void Sema::CheckForIntOverflow (Expr *E) {
11661   // Use a work list to deal with nested struct initializers.
11662   SmallVector<Expr *, 2> Exprs(1, E);
11663 
11664   do {
11665     Expr *OriginalE = Exprs.pop_back_val();
11666     Expr *E = OriginalE->IgnoreParenCasts();
11667 
11668     if (isa<BinaryOperator>(E)) {
11669       E->EvaluateForOverflow(Context);
11670       continue;
11671     }
11672 
11673     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11674       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11675     else if (isa<ObjCBoxedExpr>(OriginalE))
11676       E->EvaluateForOverflow(Context);
11677     else if (auto Call = dyn_cast<CallExpr>(E))
11678       Exprs.append(Call->arg_begin(), Call->arg_end());
11679     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11680       Exprs.append(Message->arg_begin(), Message->arg_end());
11681   } while (!Exprs.empty());
11682 }
11683 
11684 namespace {
11685 
11686 /// Visitor for expressions which looks for unsequenced operations on the
11687 /// same object.
11688 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11689   using Base = EvaluatedExprVisitor<SequenceChecker>;
11690 
11691   /// A tree of sequenced regions within an expression. Two regions are
11692   /// unsequenced if one is an ancestor or a descendent of the other. When we
11693   /// finish processing an expression with sequencing, such as a comma
11694   /// expression, we fold its tree nodes into its parent, since they are
11695   /// unsequenced with respect to nodes we will visit later.
11696   class SequenceTree {
11697     struct Value {
11698       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11699       unsigned Parent : 31;
11700       unsigned Merged : 1;
11701     };
11702     SmallVector<Value, 8> Values;
11703 
11704   public:
11705     /// A region within an expression which may be sequenced with respect
11706     /// to some other region.
11707     class Seq {
11708       friend class SequenceTree;
11709 
11710       unsigned Index;
11711 
11712       explicit Seq(unsigned N) : Index(N) {}
11713 
11714     public:
11715       Seq() : Index(0) {}
11716     };
11717 
11718     SequenceTree() { Values.push_back(Value(0)); }
11719     Seq root() const { return Seq(0); }
11720 
11721     /// Create a new sequence of operations, which is an unsequenced
11722     /// subset of \p Parent. This sequence of operations is sequenced with
11723     /// respect to other children of \p Parent.
11724     Seq allocate(Seq Parent) {
11725       Values.push_back(Value(Parent.Index));
11726       return Seq(Values.size() - 1);
11727     }
11728 
11729     /// Merge a sequence of operations into its parent.
11730     void merge(Seq S) {
11731       Values[S.Index].Merged = true;
11732     }
11733 
11734     /// Determine whether two operations are unsequenced. This operation
11735     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11736     /// should have been merged into its parent as appropriate.
11737     bool isUnsequenced(Seq Cur, Seq Old) {
11738       unsigned C = representative(Cur.Index);
11739       unsigned Target = representative(Old.Index);
11740       while (C >= Target) {
11741         if (C == Target)
11742           return true;
11743         C = Values[C].Parent;
11744       }
11745       return false;
11746     }
11747 
11748   private:
11749     /// Pick a representative for a sequence.
11750     unsigned representative(unsigned K) {
11751       if (Values[K].Merged)
11752         // Perform path compression as we go.
11753         return Values[K].Parent = representative(Values[K].Parent);
11754       return K;
11755     }
11756   };
11757 
11758   /// An object for which we can track unsequenced uses.
11759   using Object = NamedDecl *;
11760 
11761   /// Different flavors of object usage which we track. We only track the
11762   /// least-sequenced usage of each kind.
11763   enum UsageKind {
11764     /// A read of an object. Multiple unsequenced reads are OK.
11765     UK_Use,
11766 
11767     /// A modification of an object which is sequenced before the value
11768     /// computation of the expression, such as ++n in C++.
11769     UK_ModAsValue,
11770 
11771     /// A modification of an object which is not sequenced before the value
11772     /// computation of the expression, such as n++.
11773     UK_ModAsSideEffect,
11774 
11775     UK_Count = UK_ModAsSideEffect + 1
11776   };
11777 
11778   struct Usage {
11779     Expr *Use;
11780     SequenceTree::Seq Seq;
11781 
11782     Usage() : Use(nullptr), Seq() {}
11783   };
11784 
11785   struct UsageInfo {
11786     Usage Uses[UK_Count];
11787 
11788     /// Have we issued a diagnostic for this variable already?
11789     bool Diagnosed;
11790 
11791     UsageInfo() : Uses(), Diagnosed(false) {}
11792   };
11793   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11794 
11795   Sema &SemaRef;
11796 
11797   /// Sequenced regions within the expression.
11798   SequenceTree Tree;
11799 
11800   /// Declaration modifications and references which we have seen.
11801   UsageInfoMap UsageMap;
11802 
11803   /// The region we are currently within.
11804   SequenceTree::Seq Region;
11805 
11806   /// Filled in with declarations which were modified as a side-effect
11807   /// (that is, post-increment operations).
11808   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11809 
11810   /// Expressions to check later. We defer checking these to reduce
11811   /// stack usage.
11812   SmallVectorImpl<Expr *> &WorkList;
11813 
11814   /// RAII object wrapping the visitation of a sequenced subexpression of an
11815   /// expression. At the end of this process, the side-effects of the evaluation
11816   /// become sequenced with respect to the value computation of the result, so
11817   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11818   /// UK_ModAsValue.
11819   struct SequencedSubexpression {
11820     SequencedSubexpression(SequenceChecker &Self)
11821       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11822       Self.ModAsSideEffect = &ModAsSideEffect;
11823     }
11824 
11825     ~SequencedSubexpression() {
11826       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11827         UsageInfo &U = Self.UsageMap[M.first];
11828         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11829         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11830         SideEffectUsage = M.second;
11831       }
11832       Self.ModAsSideEffect = OldModAsSideEffect;
11833     }
11834 
11835     SequenceChecker &Self;
11836     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11837     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11838   };
11839 
11840   /// RAII object wrapping the visitation of a subexpression which we might
11841   /// choose to evaluate as a constant. If any subexpression is evaluated and
11842   /// found to be non-constant, this allows us to suppress the evaluation of
11843   /// the outer expression.
11844   class EvaluationTracker {
11845   public:
11846     EvaluationTracker(SequenceChecker &Self)
11847         : Self(Self), Prev(Self.EvalTracker) {
11848       Self.EvalTracker = this;
11849     }
11850 
11851     ~EvaluationTracker() {
11852       Self.EvalTracker = Prev;
11853       if (Prev)
11854         Prev->EvalOK &= EvalOK;
11855     }
11856 
11857     bool evaluate(const Expr *E, bool &Result) {
11858       if (!EvalOK || E->isValueDependent())
11859         return false;
11860       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11861       return EvalOK;
11862     }
11863 
11864   private:
11865     SequenceChecker &Self;
11866     EvaluationTracker *Prev;
11867     bool EvalOK = true;
11868   } *EvalTracker = nullptr;
11869 
11870   /// Find the object which is produced by the specified expression,
11871   /// if any.
11872   Object getObject(Expr *E, bool Mod) const {
11873     E = E->IgnoreParenCasts();
11874     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11875       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11876         return getObject(UO->getSubExpr(), Mod);
11877     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11878       if (BO->getOpcode() == BO_Comma)
11879         return getObject(BO->getRHS(), Mod);
11880       if (Mod && BO->isAssignmentOp())
11881         return getObject(BO->getLHS(), Mod);
11882     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11883       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11884       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11885         return ME->getMemberDecl();
11886     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11887       // FIXME: If this is a reference, map through to its value.
11888       return DRE->getDecl();
11889     return nullptr;
11890   }
11891 
11892   /// Note that an object was modified or used by an expression.
11893   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11894     Usage &U = UI.Uses[UK];
11895     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11896       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11897         ModAsSideEffect->push_back(std::make_pair(O, U));
11898       U.Use = Ref;
11899       U.Seq = Region;
11900     }
11901   }
11902 
11903   /// Check whether a modification or use conflicts with a prior usage.
11904   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11905                   bool IsModMod) {
11906     if (UI.Diagnosed)
11907       return;
11908 
11909     const Usage &U = UI.Uses[OtherKind];
11910     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11911       return;
11912 
11913     Expr *Mod = U.Use;
11914     Expr *ModOrUse = Ref;
11915     if (OtherKind == UK_Use)
11916       std::swap(Mod, ModOrUse);
11917 
11918     SemaRef.Diag(Mod->getExprLoc(),
11919                  IsModMod ? diag::warn_unsequenced_mod_mod
11920                           : diag::warn_unsequenced_mod_use)
11921       << O << SourceRange(ModOrUse->getExprLoc());
11922     UI.Diagnosed = true;
11923   }
11924 
11925   void notePreUse(Object O, Expr *Use) {
11926     UsageInfo &U = UsageMap[O];
11927     // Uses conflict with other modifications.
11928     checkUsage(O, U, Use, UK_ModAsValue, false);
11929   }
11930 
11931   void notePostUse(Object O, Expr *Use) {
11932     UsageInfo &U = UsageMap[O];
11933     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11934     addUsage(U, O, Use, UK_Use);
11935   }
11936 
11937   void notePreMod(Object O, Expr *Mod) {
11938     UsageInfo &U = UsageMap[O];
11939     // Modifications conflict with other modifications and with uses.
11940     checkUsage(O, U, Mod, UK_ModAsValue, true);
11941     checkUsage(O, U, Mod, UK_Use, false);
11942   }
11943 
11944   void notePostMod(Object O, Expr *Use, UsageKind UK) {
11945     UsageInfo &U = UsageMap[O];
11946     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11947     addUsage(U, O, Use, UK);
11948   }
11949 
11950 public:
11951   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
11952       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
11953     Visit(E);
11954   }
11955 
11956   void VisitStmt(Stmt *S) {
11957     // Skip all statements which aren't expressions for now.
11958   }
11959 
11960   void VisitExpr(Expr *E) {
11961     // By default, just recurse to evaluated subexpressions.
11962     Base::VisitStmt(E);
11963   }
11964 
11965   void VisitCastExpr(CastExpr *E) {
11966     Object O = Object();
11967     if (E->getCastKind() == CK_LValueToRValue)
11968       O = getObject(E->getSubExpr(), false);
11969 
11970     if (O)
11971       notePreUse(O, E);
11972     VisitExpr(E);
11973     if (O)
11974       notePostUse(O, E);
11975   }
11976 
11977   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
11978     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
11979     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
11980     SequenceTree::Seq OldRegion = Region;
11981 
11982     {
11983       SequencedSubexpression SeqBefore(*this);
11984       Region = BeforeRegion;
11985       Visit(SequencedBefore);
11986     }
11987 
11988     Region = AfterRegion;
11989     Visit(SequencedAfter);
11990 
11991     Region = OldRegion;
11992 
11993     Tree.merge(BeforeRegion);
11994     Tree.merge(AfterRegion);
11995   }
11996 
11997   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
11998     // C++17 [expr.sub]p1:
11999     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12000     //   expression E1 is sequenced before the expression E2.
12001     if (SemaRef.getLangOpts().CPlusPlus17)
12002       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12003     else
12004       Base::VisitStmt(ASE);
12005   }
12006 
12007   void VisitBinComma(BinaryOperator *BO) {
12008     // C++11 [expr.comma]p1:
12009     //   Every value computation and side effect associated with the left
12010     //   expression is sequenced before every value computation and side
12011     //   effect associated with the right expression.
12012     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12013   }
12014 
12015   void VisitBinAssign(BinaryOperator *BO) {
12016     // The modification is sequenced after the value computation of the LHS
12017     // and RHS, so check it before inspecting the operands and update the
12018     // map afterwards.
12019     Object O = getObject(BO->getLHS(), true);
12020     if (!O)
12021       return VisitExpr(BO);
12022 
12023     notePreMod(O, BO);
12024 
12025     // C++11 [expr.ass]p7:
12026     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12027     //   only once.
12028     //
12029     // Therefore, for a compound assignment operator, O is considered used
12030     // everywhere except within the evaluation of E1 itself.
12031     if (isa<CompoundAssignOperator>(BO))
12032       notePreUse(O, BO);
12033 
12034     Visit(BO->getLHS());
12035 
12036     if (isa<CompoundAssignOperator>(BO))
12037       notePostUse(O, BO);
12038 
12039     Visit(BO->getRHS());
12040 
12041     // C++11 [expr.ass]p1:
12042     //   the assignment is sequenced [...] before the value computation of the
12043     //   assignment expression.
12044     // C11 6.5.16/3 has no such rule.
12045     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12046                                                        : UK_ModAsSideEffect);
12047   }
12048 
12049   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12050     VisitBinAssign(CAO);
12051   }
12052 
12053   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12054   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12055   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12056     Object O = getObject(UO->getSubExpr(), true);
12057     if (!O)
12058       return VisitExpr(UO);
12059 
12060     notePreMod(O, UO);
12061     Visit(UO->getSubExpr());
12062     // C++11 [expr.pre.incr]p1:
12063     //   the expression ++x is equivalent to x+=1
12064     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12065                                                        : UK_ModAsSideEffect);
12066   }
12067 
12068   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12069   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12070   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12071     Object O = getObject(UO->getSubExpr(), true);
12072     if (!O)
12073       return VisitExpr(UO);
12074 
12075     notePreMod(O, UO);
12076     Visit(UO->getSubExpr());
12077     notePostMod(O, UO, UK_ModAsSideEffect);
12078   }
12079 
12080   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12081   void VisitBinLOr(BinaryOperator *BO) {
12082     // The side-effects of the LHS of an '&&' are sequenced before the
12083     // value computation of the RHS, and hence before the value computation
12084     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12085     // as if they were unconditionally sequenced.
12086     EvaluationTracker Eval(*this);
12087     {
12088       SequencedSubexpression Sequenced(*this);
12089       Visit(BO->getLHS());
12090     }
12091 
12092     bool Result;
12093     if (Eval.evaluate(BO->getLHS(), Result)) {
12094       if (!Result)
12095         Visit(BO->getRHS());
12096     } else {
12097       // Check for unsequenced operations in the RHS, treating it as an
12098       // entirely separate evaluation.
12099       //
12100       // FIXME: If there are operations in the RHS which are unsequenced
12101       // with respect to operations outside the RHS, and those operations
12102       // are unconditionally evaluated, diagnose them.
12103       WorkList.push_back(BO->getRHS());
12104     }
12105   }
12106   void VisitBinLAnd(BinaryOperator *BO) {
12107     EvaluationTracker Eval(*this);
12108     {
12109       SequencedSubexpression Sequenced(*this);
12110       Visit(BO->getLHS());
12111     }
12112 
12113     bool Result;
12114     if (Eval.evaluate(BO->getLHS(), Result)) {
12115       if (Result)
12116         Visit(BO->getRHS());
12117     } else {
12118       WorkList.push_back(BO->getRHS());
12119     }
12120   }
12121 
12122   // Only visit the condition, unless we can be sure which subexpression will
12123   // be chosen.
12124   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12125     EvaluationTracker Eval(*this);
12126     {
12127       SequencedSubexpression Sequenced(*this);
12128       Visit(CO->getCond());
12129     }
12130 
12131     bool Result;
12132     if (Eval.evaluate(CO->getCond(), Result))
12133       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12134     else {
12135       WorkList.push_back(CO->getTrueExpr());
12136       WorkList.push_back(CO->getFalseExpr());
12137     }
12138   }
12139 
12140   void VisitCallExpr(CallExpr *CE) {
12141     // C++11 [intro.execution]p15:
12142     //   When calling a function [...], every value computation and side effect
12143     //   associated with any argument expression, or with the postfix expression
12144     //   designating the called function, is sequenced before execution of every
12145     //   expression or statement in the body of the function [and thus before
12146     //   the value computation of its result].
12147     SequencedSubexpression Sequenced(*this);
12148     Base::VisitCallExpr(CE);
12149 
12150     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12151   }
12152 
12153   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12154     // This is a call, so all subexpressions are sequenced before the result.
12155     SequencedSubexpression Sequenced(*this);
12156 
12157     if (!CCE->isListInitialization())
12158       return VisitExpr(CCE);
12159 
12160     // In C++11, list initializations are sequenced.
12161     SmallVector<SequenceTree::Seq, 32> Elts;
12162     SequenceTree::Seq Parent = Region;
12163     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12164                                         E = CCE->arg_end();
12165          I != E; ++I) {
12166       Region = Tree.allocate(Parent);
12167       Elts.push_back(Region);
12168       Visit(*I);
12169     }
12170 
12171     // Forget that the initializers are sequenced.
12172     Region = Parent;
12173     for (unsigned I = 0; I < Elts.size(); ++I)
12174       Tree.merge(Elts[I]);
12175   }
12176 
12177   void VisitInitListExpr(InitListExpr *ILE) {
12178     if (!SemaRef.getLangOpts().CPlusPlus11)
12179       return VisitExpr(ILE);
12180 
12181     // In C++11, list initializations are sequenced.
12182     SmallVector<SequenceTree::Seq, 32> Elts;
12183     SequenceTree::Seq Parent = Region;
12184     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12185       Expr *E = ILE->getInit(I);
12186       if (!E) continue;
12187       Region = Tree.allocate(Parent);
12188       Elts.push_back(Region);
12189       Visit(E);
12190     }
12191 
12192     // Forget that the initializers are sequenced.
12193     Region = Parent;
12194     for (unsigned I = 0; I < Elts.size(); ++I)
12195       Tree.merge(Elts[I]);
12196   }
12197 };
12198 
12199 } // namespace
12200 
12201 void Sema::CheckUnsequencedOperations(Expr *E) {
12202   SmallVector<Expr *, 8> WorkList;
12203   WorkList.push_back(E);
12204   while (!WorkList.empty()) {
12205     Expr *Item = WorkList.pop_back_val();
12206     SequenceChecker(*this, Item, WorkList);
12207   }
12208 }
12209 
12210 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12211                               bool IsConstexpr) {
12212   CheckImplicitConversions(E, CheckLoc);
12213   if (!E->isInstantiationDependent())
12214     CheckUnsequencedOperations(E);
12215   if (!IsConstexpr && !E->isValueDependent())
12216     CheckForIntOverflow(E);
12217   DiagnoseMisalignedMembers();
12218 }
12219 
12220 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12221                                        FieldDecl *BitField,
12222                                        Expr *Init) {
12223   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12224 }
12225 
12226 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12227                                          SourceLocation Loc) {
12228   if (!PType->isVariablyModifiedType())
12229     return;
12230   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12231     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12232     return;
12233   }
12234   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12235     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12236     return;
12237   }
12238   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12239     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12240     return;
12241   }
12242 
12243   const ArrayType *AT = S.Context.getAsArrayType(PType);
12244   if (!AT)
12245     return;
12246 
12247   if (AT->getSizeModifier() != ArrayType::Star) {
12248     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12249     return;
12250   }
12251 
12252   S.Diag(Loc, diag::err_array_star_in_function_definition);
12253 }
12254 
12255 /// CheckParmsForFunctionDef - Check that the parameters of the given
12256 /// function are appropriate for the definition of a function. This
12257 /// takes care of any checks that cannot be performed on the
12258 /// declaration itself, e.g., that the types of each of the function
12259 /// parameters are complete.
12260 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12261                                     bool CheckParameterNames) {
12262   bool HasInvalidParm = false;
12263   for (ParmVarDecl *Param : Parameters) {
12264     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12265     // function declarator that is part of a function definition of
12266     // that function shall not have incomplete type.
12267     //
12268     // This is also C++ [dcl.fct]p6.
12269     if (!Param->isInvalidDecl() &&
12270         RequireCompleteType(Param->getLocation(), Param->getType(),
12271                             diag::err_typecheck_decl_incomplete_type)) {
12272       Param->setInvalidDecl();
12273       HasInvalidParm = true;
12274     }
12275 
12276     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12277     // declaration of each parameter shall include an identifier.
12278     if (CheckParameterNames &&
12279         Param->getIdentifier() == nullptr &&
12280         !Param->isImplicit() &&
12281         !getLangOpts().CPlusPlus)
12282       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12283 
12284     // C99 6.7.5.3p12:
12285     //   If the function declarator is not part of a definition of that
12286     //   function, parameters may have incomplete type and may use the [*]
12287     //   notation in their sequences of declarator specifiers to specify
12288     //   variable length array types.
12289     QualType PType = Param->getOriginalType();
12290     // FIXME: This diagnostic should point the '[*]' if source-location
12291     // information is added for it.
12292     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12293 
12294     // If the parameter is a c++ class type and it has to be destructed in the
12295     // callee function, declare the destructor so that it can be called by the
12296     // callee function. Do not perform any direct access check on the dtor here.
12297     if (!Param->isInvalidDecl()) {
12298       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12299         if (!ClassDecl->isInvalidDecl() &&
12300             !ClassDecl->hasIrrelevantDestructor() &&
12301             !ClassDecl->isDependentContext() &&
12302             ClassDecl->isParamDestroyedInCallee()) {
12303           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12304           MarkFunctionReferenced(Param->getLocation(), Destructor);
12305           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12306         }
12307       }
12308     }
12309 
12310     // Parameters with the pass_object_size attribute only need to be marked
12311     // constant at function definitions. Because we lack information about
12312     // whether we're on a declaration or definition when we're instantiating the
12313     // attribute, we need to check for constness here.
12314     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12315       if (!Param->getType().isConstQualified())
12316         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12317             << Attr->getSpelling() << 1;
12318 
12319     // Check for parameter names shadowing fields from the class.
12320     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12321       // The owning context for the parameter should be the function, but we
12322       // want to see if this function's declaration context is a record.
12323       DeclContext *DC = Param->getDeclContext();
12324       if (DC && DC->isFunctionOrMethod()) {
12325         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12326           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12327                                      RD, /*DeclIsField*/ false);
12328       }
12329     }
12330   }
12331 
12332   return HasInvalidParm;
12333 }
12334 
12335 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12336 /// or MemberExpr.
12337 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12338                               ASTContext &Context) {
12339   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12340     return Context.getDeclAlign(DRE->getDecl());
12341 
12342   if (const auto *ME = dyn_cast<MemberExpr>(E))
12343     return Context.getDeclAlign(ME->getMemberDecl());
12344 
12345   return TypeAlign;
12346 }
12347 
12348 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12349 /// pointer cast increases the alignment requirements.
12350 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12351   // This is actually a lot of work to potentially be doing on every
12352   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12353   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12354     return;
12355 
12356   // Ignore dependent types.
12357   if (T->isDependentType() || Op->getType()->isDependentType())
12358     return;
12359 
12360   // Require that the destination be a pointer type.
12361   const PointerType *DestPtr = T->getAs<PointerType>();
12362   if (!DestPtr) return;
12363 
12364   // If the destination has alignment 1, we're done.
12365   QualType DestPointee = DestPtr->getPointeeType();
12366   if (DestPointee->isIncompleteType()) return;
12367   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12368   if (DestAlign.isOne()) return;
12369 
12370   // Require that the source be a pointer type.
12371   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12372   if (!SrcPtr) return;
12373   QualType SrcPointee = SrcPtr->getPointeeType();
12374 
12375   // Whitelist casts from cv void*.  We already implicitly
12376   // whitelisted casts to cv void*, since they have alignment 1.
12377   // Also whitelist casts involving incomplete types, which implicitly
12378   // includes 'void'.
12379   if (SrcPointee->isIncompleteType()) return;
12380 
12381   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12382 
12383   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12384     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12385       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12386   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12387     if (UO->getOpcode() == UO_AddrOf)
12388       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12389   }
12390 
12391   if (SrcAlign >= DestAlign) return;
12392 
12393   Diag(TRange.getBegin(), diag::warn_cast_align)
12394     << Op->getType() << T
12395     << static_cast<unsigned>(SrcAlign.getQuantity())
12396     << static_cast<unsigned>(DestAlign.getQuantity())
12397     << TRange << Op->getSourceRange();
12398 }
12399 
12400 /// Check whether this array fits the idiom of a size-one tail padded
12401 /// array member of a struct.
12402 ///
12403 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12404 /// commonly used to emulate flexible arrays in C89 code.
12405 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12406                                     const NamedDecl *ND) {
12407   if (Size != 1 || !ND) return false;
12408 
12409   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12410   if (!FD) return false;
12411 
12412   // Don't consider sizes resulting from macro expansions or template argument
12413   // substitution to form C89 tail-padded arrays.
12414 
12415   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12416   while (TInfo) {
12417     TypeLoc TL = TInfo->getTypeLoc();
12418     // Look through typedefs.
12419     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12420       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12421       TInfo = TDL->getTypeSourceInfo();
12422       continue;
12423     }
12424     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12425       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12426       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12427         return false;
12428     }
12429     break;
12430   }
12431 
12432   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12433   if (!RD) return false;
12434   if (RD->isUnion()) return false;
12435   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12436     if (!CRD->isStandardLayout()) return false;
12437   }
12438 
12439   // See if this is the last field decl in the record.
12440   const Decl *D = FD;
12441   while ((D = D->getNextDeclInContext()))
12442     if (isa<FieldDecl>(D))
12443       return false;
12444   return true;
12445 }
12446 
12447 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12448                             const ArraySubscriptExpr *ASE,
12449                             bool AllowOnePastEnd, bool IndexNegated) {
12450   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12451   if (IndexExpr->isValueDependent())
12452     return;
12453 
12454   const Type *EffectiveType =
12455       BaseExpr->getType()->getPointeeOrArrayElementType();
12456   BaseExpr = BaseExpr->IgnoreParenCasts();
12457   const ConstantArrayType *ArrayTy =
12458       Context.getAsConstantArrayType(BaseExpr->getType());
12459 
12460   if (!ArrayTy)
12461     return;
12462 
12463   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12464 
12465   Expr::EvalResult Result;
12466   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12467     return;
12468 
12469   llvm::APSInt index = Result.Val.getInt();
12470   if (IndexNegated)
12471     index = -index;
12472 
12473   const NamedDecl *ND = nullptr;
12474   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12475     ND = DRE->getDecl();
12476   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12477     ND = ME->getMemberDecl();
12478 
12479   if (index.isUnsigned() || !index.isNegative()) {
12480     // It is possible that the type of the base expression after
12481     // IgnoreParenCasts is incomplete, even though the type of the base
12482     // expression before IgnoreParenCasts is complete (see PR39746 for an
12483     // example). In this case we have no information about whether the array
12484     // access exceeds the array bounds. However we can still diagnose an array
12485     // access which precedes the array bounds.
12486     if (BaseType->isIncompleteType())
12487       return;
12488 
12489     llvm::APInt size = ArrayTy->getSize();
12490     if (!size.isStrictlyPositive())
12491       return;
12492 
12493     if (BaseType != EffectiveType) {
12494       // Make sure we're comparing apples to apples when comparing index to size
12495       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12496       uint64_t array_typesize = Context.getTypeSize(BaseType);
12497       // Handle ptrarith_typesize being zero, such as when casting to void*
12498       if (!ptrarith_typesize) ptrarith_typesize = 1;
12499       if (ptrarith_typesize != array_typesize) {
12500         // There's a cast to a different size type involved
12501         uint64_t ratio = array_typesize / ptrarith_typesize;
12502         // TODO: Be smarter about handling cases where array_typesize is not a
12503         // multiple of ptrarith_typesize
12504         if (ptrarith_typesize * ratio == array_typesize)
12505           size *= llvm::APInt(size.getBitWidth(), ratio);
12506       }
12507     }
12508 
12509     if (size.getBitWidth() > index.getBitWidth())
12510       index = index.zext(size.getBitWidth());
12511     else if (size.getBitWidth() < index.getBitWidth())
12512       size = size.zext(index.getBitWidth());
12513 
12514     // For array subscripting the index must be less than size, but for pointer
12515     // arithmetic also allow the index (offset) to be equal to size since
12516     // computing the next address after the end of the array is legal and
12517     // commonly done e.g. in C++ iterators and range-based for loops.
12518     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12519       return;
12520 
12521     // Also don't warn for arrays of size 1 which are members of some
12522     // structure. These are often used to approximate flexible arrays in C89
12523     // code.
12524     if (IsTailPaddedMemberArray(*this, size, ND))
12525       return;
12526 
12527     // Suppress the warning if the subscript expression (as identified by the
12528     // ']' location) and the index expression are both from macro expansions
12529     // within a system header.
12530     if (ASE) {
12531       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12532           ASE->getRBracketLoc());
12533       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12534         SourceLocation IndexLoc =
12535             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12536         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12537           return;
12538       }
12539     }
12540 
12541     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12542     if (ASE)
12543       DiagID = diag::warn_array_index_exceeds_bounds;
12544 
12545     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12546                         PDiag(DiagID) << index.toString(10, true)
12547                                       << size.toString(10, true)
12548                                       << (unsigned)size.getLimitedValue(~0U)
12549                                       << IndexExpr->getSourceRange());
12550   } else {
12551     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12552     if (!ASE) {
12553       DiagID = diag::warn_ptr_arith_precedes_bounds;
12554       if (index.isNegative()) index = -index;
12555     }
12556 
12557     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12558                         PDiag(DiagID) << index.toString(10, true)
12559                                       << IndexExpr->getSourceRange());
12560   }
12561 
12562   if (!ND) {
12563     // Try harder to find a NamedDecl to point at in the note.
12564     while (const ArraySubscriptExpr *ASE =
12565            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12566       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12567     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12568       ND = DRE->getDecl();
12569     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12570       ND = ME->getMemberDecl();
12571   }
12572 
12573   if (ND)
12574     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12575                         PDiag(diag::note_array_index_out_of_bounds)
12576                             << ND->getDeclName());
12577 }
12578 
12579 void Sema::CheckArrayAccess(const Expr *expr) {
12580   int AllowOnePastEnd = 0;
12581   while (expr) {
12582     expr = expr->IgnoreParenImpCasts();
12583     switch (expr->getStmtClass()) {
12584       case Stmt::ArraySubscriptExprClass: {
12585         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12586         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12587                          AllowOnePastEnd > 0);
12588         expr = ASE->getBase();
12589         break;
12590       }
12591       case Stmt::MemberExprClass: {
12592         expr = cast<MemberExpr>(expr)->getBase();
12593         break;
12594       }
12595       case Stmt::OMPArraySectionExprClass: {
12596         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12597         if (ASE->getLowerBound())
12598           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12599                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12600         return;
12601       }
12602       case Stmt::UnaryOperatorClass: {
12603         // Only unwrap the * and & unary operators
12604         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12605         expr = UO->getSubExpr();
12606         switch (UO->getOpcode()) {
12607           case UO_AddrOf:
12608             AllowOnePastEnd++;
12609             break;
12610           case UO_Deref:
12611             AllowOnePastEnd--;
12612             break;
12613           default:
12614             return;
12615         }
12616         break;
12617       }
12618       case Stmt::ConditionalOperatorClass: {
12619         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12620         if (const Expr *lhs = cond->getLHS())
12621           CheckArrayAccess(lhs);
12622         if (const Expr *rhs = cond->getRHS())
12623           CheckArrayAccess(rhs);
12624         return;
12625       }
12626       case Stmt::CXXOperatorCallExprClass: {
12627         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12628         for (const auto *Arg : OCE->arguments())
12629           CheckArrayAccess(Arg);
12630         return;
12631       }
12632       default:
12633         return;
12634     }
12635   }
12636 }
12637 
12638 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12639 
12640 namespace {
12641 
12642 struct RetainCycleOwner {
12643   VarDecl *Variable = nullptr;
12644   SourceRange Range;
12645   SourceLocation Loc;
12646   bool Indirect = false;
12647 
12648   RetainCycleOwner() = default;
12649 
12650   void setLocsFrom(Expr *e) {
12651     Loc = e->getExprLoc();
12652     Range = e->getSourceRange();
12653   }
12654 };
12655 
12656 } // namespace
12657 
12658 /// Consider whether capturing the given variable can possibly lead to
12659 /// a retain cycle.
12660 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12661   // In ARC, it's captured strongly iff the variable has __strong
12662   // lifetime.  In MRR, it's captured strongly if the variable is
12663   // __block and has an appropriate type.
12664   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12665     return false;
12666 
12667   owner.Variable = var;
12668   if (ref)
12669     owner.setLocsFrom(ref);
12670   return true;
12671 }
12672 
12673 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12674   while (true) {
12675     e = e->IgnoreParens();
12676     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12677       switch (cast->getCastKind()) {
12678       case CK_BitCast:
12679       case CK_LValueBitCast:
12680       case CK_LValueToRValue:
12681       case CK_ARCReclaimReturnedObject:
12682         e = cast->getSubExpr();
12683         continue;
12684 
12685       default:
12686         return false;
12687       }
12688     }
12689 
12690     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12691       ObjCIvarDecl *ivar = ref->getDecl();
12692       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12693         return false;
12694 
12695       // Try to find a retain cycle in the base.
12696       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12697         return false;
12698 
12699       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12700       owner.Indirect = true;
12701       return true;
12702     }
12703 
12704     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12705       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12706       if (!var) return false;
12707       return considerVariable(var, ref, owner);
12708     }
12709 
12710     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12711       if (member->isArrow()) return false;
12712 
12713       // Don't count this as an indirect ownership.
12714       e = member->getBase();
12715       continue;
12716     }
12717 
12718     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12719       // Only pay attention to pseudo-objects on property references.
12720       ObjCPropertyRefExpr *pre
12721         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12722                                               ->IgnoreParens());
12723       if (!pre) return false;
12724       if (pre->isImplicitProperty()) return false;
12725       ObjCPropertyDecl *property = pre->getExplicitProperty();
12726       if (!property->isRetaining() &&
12727           !(property->getPropertyIvarDecl() &&
12728             property->getPropertyIvarDecl()->getType()
12729               .getObjCLifetime() == Qualifiers::OCL_Strong))
12730           return false;
12731 
12732       owner.Indirect = true;
12733       if (pre->isSuperReceiver()) {
12734         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12735         if (!owner.Variable)
12736           return false;
12737         owner.Loc = pre->getLocation();
12738         owner.Range = pre->getSourceRange();
12739         return true;
12740       }
12741       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12742                               ->getSourceExpr());
12743       continue;
12744     }
12745 
12746     // Array ivars?
12747 
12748     return false;
12749   }
12750 }
12751 
12752 namespace {
12753 
12754   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12755     ASTContext &Context;
12756     VarDecl *Variable;
12757     Expr *Capturer = nullptr;
12758     bool VarWillBeReased = false;
12759 
12760     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12761         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12762           Context(Context), Variable(variable) {}
12763 
12764     void VisitDeclRefExpr(DeclRefExpr *ref) {
12765       if (ref->getDecl() == Variable && !Capturer)
12766         Capturer = ref;
12767     }
12768 
12769     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12770       if (Capturer) return;
12771       Visit(ref->getBase());
12772       if (Capturer && ref->isFreeIvar())
12773         Capturer = ref;
12774     }
12775 
12776     void VisitBlockExpr(BlockExpr *block) {
12777       // Look inside nested blocks
12778       if (block->getBlockDecl()->capturesVariable(Variable))
12779         Visit(block->getBlockDecl()->getBody());
12780     }
12781 
12782     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12783       if (Capturer) return;
12784       if (OVE->getSourceExpr())
12785         Visit(OVE->getSourceExpr());
12786     }
12787 
12788     void VisitBinaryOperator(BinaryOperator *BinOp) {
12789       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12790         return;
12791       Expr *LHS = BinOp->getLHS();
12792       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12793         if (DRE->getDecl() != Variable)
12794           return;
12795         if (Expr *RHS = BinOp->getRHS()) {
12796           RHS = RHS->IgnoreParenCasts();
12797           llvm::APSInt Value;
12798           VarWillBeReased =
12799             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12800         }
12801       }
12802     }
12803   };
12804 
12805 } // namespace
12806 
12807 /// Check whether the given argument is a block which captures a
12808 /// variable.
12809 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12810   assert(owner.Variable && owner.Loc.isValid());
12811 
12812   e = e->IgnoreParenCasts();
12813 
12814   // Look through [^{...} copy] and Block_copy(^{...}).
12815   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12816     Selector Cmd = ME->getSelector();
12817     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12818       e = ME->getInstanceReceiver();
12819       if (!e)
12820         return nullptr;
12821       e = e->IgnoreParenCasts();
12822     }
12823   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12824     if (CE->getNumArgs() == 1) {
12825       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12826       if (Fn) {
12827         const IdentifierInfo *FnI = Fn->getIdentifier();
12828         if (FnI && FnI->isStr("_Block_copy")) {
12829           e = CE->getArg(0)->IgnoreParenCasts();
12830         }
12831       }
12832     }
12833   }
12834 
12835   BlockExpr *block = dyn_cast<BlockExpr>(e);
12836   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12837     return nullptr;
12838 
12839   FindCaptureVisitor visitor(S.Context, owner.Variable);
12840   visitor.Visit(block->getBlockDecl()->getBody());
12841   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12842 }
12843 
12844 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12845                                 RetainCycleOwner &owner) {
12846   assert(capturer);
12847   assert(owner.Variable && owner.Loc.isValid());
12848 
12849   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12850     << owner.Variable << capturer->getSourceRange();
12851   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12852     << owner.Indirect << owner.Range;
12853 }
12854 
12855 /// Check for a keyword selector that starts with the word 'add' or
12856 /// 'set'.
12857 static bool isSetterLikeSelector(Selector sel) {
12858   if (sel.isUnarySelector()) return false;
12859 
12860   StringRef str = sel.getNameForSlot(0);
12861   while (!str.empty() && str.front() == '_') str = str.substr(1);
12862   if (str.startswith("set"))
12863     str = str.substr(3);
12864   else if (str.startswith("add")) {
12865     // Specially whitelist 'addOperationWithBlock:'.
12866     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12867       return false;
12868     str = str.substr(3);
12869   }
12870   else
12871     return false;
12872 
12873   if (str.empty()) return true;
12874   return !isLowercase(str.front());
12875 }
12876 
12877 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12878                                                     ObjCMessageExpr *Message) {
12879   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12880                                                 Message->getReceiverInterface(),
12881                                                 NSAPI::ClassId_NSMutableArray);
12882   if (!IsMutableArray) {
12883     return None;
12884   }
12885 
12886   Selector Sel = Message->getSelector();
12887 
12888   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12889     S.NSAPIObj->getNSArrayMethodKind(Sel);
12890   if (!MKOpt) {
12891     return None;
12892   }
12893 
12894   NSAPI::NSArrayMethodKind MK = *MKOpt;
12895 
12896   switch (MK) {
12897     case NSAPI::NSMutableArr_addObject:
12898     case NSAPI::NSMutableArr_insertObjectAtIndex:
12899     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12900       return 0;
12901     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12902       return 1;
12903 
12904     default:
12905       return None;
12906   }
12907 
12908   return None;
12909 }
12910 
12911 static
12912 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12913                                                   ObjCMessageExpr *Message) {
12914   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12915                                             Message->getReceiverInterface(),
12916                                             NSAPI::ClassId_NSMutableDictionary);
12917   if (!IsMutableDictionary) {
12918     return None;
12919   }
12920 
12921   Selector Sel = Message->getSelector();
12922 
12923   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12924     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12925   if (!MKOpt) {
12926     return None;
12927   }
12928 
12929   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12930 
12931   switch (MK) {
12932     case NSAPI::NSMutableDict_setObjectForKey:
12933     case NSAPI::NSMutableDict_setValueForKey:
12934     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12935       return 0;
12936 
12937     default:
12938       return None;
12939   }
12940 
12941   return None;
12942 }
12943 
12944 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
12945   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12946                                                 Message->getReceiverInterface(),
12947                                                 NSAPI::ClassId_NSMutableSet);
12948 
12949   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12950                                             Message->getReceiverInterface(),
12951                                             NSAPI::ClassId_NSMutableOrderedSet);
12952   if (!IsMutableSet && !IsMutableOrderedSet) {
12953     return None;
12954   }
12955 
12956   Selector Sel = Message->getSelector();
12957 
12958   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12959   if (!MKOpt) {
12960     return None;
12961   }
12962 
12963   NSAPI::NSSetMethodKind MK = *MKOpt;
12964 
12965   switch (MK) {
12966     case NSAPI::NSMutableSet_addObject:
12967     case NSAPI::NSOrderedSet_setObjectAtIndex:
12968     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12969     case NSAPI::NSOrderedSet_insertObjectAtIndex:
12970       return 0;
12971     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12972       return 1;
12973   }
12974 
12975   return None;
12976 }
12977 
12978 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12979   if (!Message->isInstanceMessage()) {
12980     return;
12981   }
12982 
12983   Optional<int> ArgOpt;
12984 
12985   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12986       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12987       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12988     return;
12989   }
12990 
12991   int ArgIndex = *ArgOpt;
12992 
12993   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12994   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12995     Arg = OE->getSourceExpr()->IgnoreImpCasts();
12996   }
12997 
12998   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12999     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13000       if (ArgRE->isObjCSelfExpr()) {
13001         Diag(Message->getSourceRange().getBegin(),
13002              diag::warn_objc_circular_container)
13003           << ArgRE->getDecl() << StringRef("'super'");
13004       }
13005     }
13006   } else {
13007     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13008 
13009     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13010       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13011     }
13012 
13013     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13014       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13015         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13016           ValueDecl *Decl = ReceiverRE->getDecl();
13017           Diag(Message->getSourceRange().getBegin(),
13018                diag::warn_objc_circular_container)
13019             << Decl << Decl;
13020           if (!ArgRE->isObjCSelfExpr()) {
13021             Diag(Decl->getLocation(),
13022                  diag::note_objc_circular_container_declared_here)
13023               << Decl;
13024           }
13025         }
13026       }
13027     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13028       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13029         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13030           ObjCIvarDecl *Decl = IvarRE->getDecl();
13031           Diag(Message->getSourceRange().getBegin(),
13032                diag::warn_objc_circular_container)
13033             << Decl << Decl;
13034           Diag(Decl->getLocation(),
13035                diag::note_objc_circular_container_declared_here)
13036             << Decl;
13037         }
13038       }
13039     }
13040   }
13041 }
13042 
13043 /// Check a message send to see if it's likely to cause a retain cycle.
13044 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13045   // Only check instance methods whose selector looks like a setter.
13046   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13047     return;
13048 
13049   // Try to find a variable that the receiver is strongly owned by.
13050   RetainCycleOwner owner;
13051   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13052     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13053       return;
13054   } else {
13055     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13056     owner.Variable = getCurMethodDecl()->getSelfDecl();
13057     owner.Loc = msg->getSuperLoc();
13058     owner.Range = msg->getSuperLoc();
13059   }
13060 
13061   // Check whether the receiver is captured by any of the arguments.
13062   const ObjCMethodDecl *MD = msg->getMethodDecl();
13063   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13064     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13065       // noescape blocks should not be retained by the method.
13066       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13067         continue;
13068       return diagnoseRetainCycle(*this, capturer, owner);
13069     }
13070   }
13071 }
13072 
13073 /// Check a property assign to see if it's likely to cause a retain cycle.
13074 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13075   RetainCycleOwner owner;
13076   if (!findRetainCycleOwner(*this, receiver, owner))
13077     return;
13078 
13079   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13080     diagnoseRetainCycle(*this, capturer, owner);
13081 }
13082 
13083 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13084   RetainCycleOwner Owner;
13085   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13086     return;
13087 
13088   // Because we don't have an expression for the variable, we have to set the
13089   // location explicitly here.
13090   Owner.Loc = Var->getLocation();
13091   Owner.Range = Var->getSourceRange();
13092 
13093   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13094     diagnoseRetainCycle(*this, Capturer, Owner);
13095 }
13096 
13097 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13098                                      Expr *RHS, bool isProperty) {
13099   // Check if RHS is an Objective-C object literal, which also can get
13100   // immediately zapped in a weak reference.  Note that we explicitly
13101   // allow ObjCStringLiterals, since those are designed to never really die.
13102   RHS = RHS->IgnoreParenImpCasts();
13103 
13104   // This enum needs to match with the 'select' in
13105   // warn_objc_arc_literal_assign (off-by-1).
13106   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13107   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13108     return false;
13109 
13110   S.Diag(Loc, diag::warn_arc_literal_assign)
13111     << (unsigned) Kind
13112     << (isProperty ? 0 : 1)
13113     << RHS->getSourceRange();
13114 
13115   return true;
13116 }
13117 
13118 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13119                                     Qualifiers::ObjCLifetime LT,
13120                                     Expr *RHS, bool isProperty) {
13121   // Strip off any implicit cast added to get to the one ARC-specific.
13122   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13123     if (cast->getCastKind() == CK_ARCConsumeObject) {
13124       S.Diag(Loc, diag::warn_arc_retained_assign)
13125         << (LT == Qualifiers::OCL_ExplicitNone)
13126         << (isProperty ? 0 : 1)
13127         << RHS->getSourceRange();
13128       return true;
13129     }
13130     RHS = cast->getSubExpr();
13131   }
13132 
13133   if (LT == Qualifiers::OCL_Weak &&
13134       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13135     return true;
13136 
13137   return false;
13138 }
13139 
13140 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13141                               QualType LHS, Expr *RHS) {
13142   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13143 
13144   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13145     return false;
13146 
13147   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13148     return true;
13149 
13150   return false;
13151 }
13152 
13153 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13154                               Expr *LHS, Expr *RHS) {
13155   QualType LHSType;
13156   // PropertyRef on LHS type need be directly obtained from
13157   // its declaration as it has a PseudoType.
13158   ObjCPropertyRefExpr *PRE
13159     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13160   if (PRE && !PRE->isImplicitProperty()) {
13161     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13162     if (PD)
13163       LHSType = PD->getType();
13164   }
13165 
13166   if (LHSType.isNull())
13167     LHSType = LHS->getType();
13168 
13169   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13170 
13171   if (LT == Qualifiers::OCL_Weak) {
13172     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13173       getCurFunction()->markSafeWeakUse(LHS);
13174   }
13175 
13176   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13177     return;
13178 
13179   // FIXME. Check for other life times.
13180   if (LT != Qualifiers::OCL_None)
13181     return;
13182 
13183   if (PRE) {
13184     if (PRE->isImplicitProperty())
13185       return;
13186     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13187     if (!PD)
13188       return;
13189 
13190     unsigned Attributes = PD->getPropertyAttributes();
13191     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13192       // when 'assign' attribute was not explicitly specified
13193       // by user, ignore it and rely on property type itself
13194       // for lifetime info.
13195       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13196       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13197           LHSType->isObjCRetainableType())
13198         return;
13199 
13200       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13201         if (cast->getCastKind() == CK_ARCConsumeObject) {
13202           Diag(Loc, diag::warn_arc_retained_property_assign)
13203           << RHS->getSourceRange();
13204           return;
13205         }
13206         RHS = cast->getSubExpr();
13207       }
13208     }
13209     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13210       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13211         return;
13212     }
13213   }
13214 }
13215 
13216 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13217 
13218 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13219                                         SourceLocation StmtLoc,
13220                                         const NullStmt *Body) {
13221   // Do not warn if the body is a macro that expands to nothing, e.g:
13222   //
13223   // #define CALL(x)
13224   // if (condition)
13225   //   CALL(0);
13226   if (Body->hasLeadingEmptyMacro())
13227     return false;
13228 
13229   // Get line numbers of statement and body.
13230   bool StmtLineInvalid;
13231   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13232                                                       &StmtLineInvalid);
13233   if (StmtLineInvalid)
13234     return false;
13235 
13236   bool BodyLineInvalid;
13237   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13238                                                       &BodyLineInvalid);
13239   if (BodyLineInvalid)
13240     return false;
13241 
13242   // Warn if null statement and body are on the same line.
13243   if (StmtLine != BodyLine)
13244     return false;
13245 
13246   return true;
13247 }
13248 
13249 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13250                                  const Stmt *Body,
13251                                  unsigned DiagID) {
13252   // Since this is a syntactic check, don't emit diagnostic for template
13253   // instantiations, this just adds noise.
13254   if (CurrentInstantiationScope)
13255     return;
13256 
13257   // The body should be a null statement.
13258   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13259   if (!NBody)
13260     return;
13261 
13262   // Do the usual checks.
13263   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13264     return;
13265 
13266   Diag(NBody->getSemiLoc(), DiagID);
13267   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13268 }
13269 
13270 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13271                                  const Stmt *PossibleBody) {
13272   assert(!CurrentInstantiationScope); // Ensured by caller
13273 
13274   SourceLocation StmtLoc;
13275   const Stmt *Body;
13276   unsigned DiagID;
13277   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13278     StmtLoc = FS->getRParenLoc();
13279     Body = FS->getBody();
13280     DiagID = diag::warn_empty_for_body;
13281   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13282     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13283     Body = WS->getBody();
13284     DiagID = diag::warn_empty_while_body;
13285   } else
13286     return; // Neither `for' nor `while'.
13287 
13288   // The body should be a null statement.
13289   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13290   if (!NBody)
13291     return;
13292 
13293   // Skip expensive checks if diagnostic is disabled.
13294   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13295     return;
13296 
13297   // Do the usual checks.
13298   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13299     return;
13300 
13301   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13302   // noise level low, emit diagnostics only if for/while is followed by a
13303   // CompoundStmt, e.g.:
13304   //    for (int i = 0; i < n; i++);
13305   //    {
13306   //      a(i);
13307   //    }
13308   // or if for/while is followed by a statement with more indentation
13309   // than for/while itself:
13310   //    for (int i = 0; i < n; i++);
13311   //      a(i);
13312   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13313   if (!ProbableTypo) {
13314     bool BodyColInvalid;
13315     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13316         PossibleBody->getBeginLoc(), &BodyColInvalid);
13317     if (BodyColInvalid)
13318       return;
13319 
13320     bool StmtColInvalid;
13321     unsigned StmtCol =
13322         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13323     if (StmtColInvalid)
13324       return;
13325 
13326     if (BodyCol > StmtCol)
13327       ProbableTypo = true;
13328   }
13329 
13330   if (ProbableTypo) {
13331     Diag(NBody->getSemiLoc(), DiagID);
13332     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13333   }
13334 }
13335 
13336 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13337 
13338 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13339 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13340                              SourceLocation OpLoc) {
13341   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13342     return;
13343 
13344   if (inTemplateInstantiation())
13345     return;
13346 
13347   // Strip parens and casts away.
13348   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13349   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13350 
13351   // Check for a call expression
13352   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13353   if (!CE || CE->getNumArgs() != 1)
13354     return;
13355 
13356   // Check for a call to std::move
13357   if (!CE->isCallToStdMove())
13358     return;
13359 
13360   // Get argument from std::move
13361   RHSExpr = CE->getArg(0);
13362 
13363   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13364   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13365 
13366   // Two DeclRefExpr's, check that the decls are the same.
13367   if (LHSDeclRef && RHSDeclRef) {
13368     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13369       return;
13370     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13371         RHSDeclRef->getDecl()->getCanonicalDecl())
13372       return;
13373 
13374     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13375                                         << LHSExpr->getSourceRange()
13376                                         << RHSExpr->getSourceRange();
13377     return;
13378   }
13379 
13380   // Member variables require a different approach to check for self moves.
13381   // MemberExpr's are the same if every nested MemberExpr refers to the same
13382   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13383   // the base Expr's are CXXThisExpr's.
13384   const Expr *LHSBase = LHSExpr;
13385   const Expr *RHSBase = RHSExpr;
13386   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13387   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13388   if (!LHSME || !RHSME)
13389     return;
13390 
13391   while (LHSME && RHSME) {
13392     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13393         RHSME->getMemberDecl()->getCanonicalDecl())
13394       return;
13395 
13396     LHSBase = LHSME->getBase();
13397     RHSBase = RHSME->getBase();
13398     LHSME = dyn_cast<MemberExpr>(LHSBase);
13399     RHSME = dyn_cast<MemberExpr>(RHSBase);
13400   }
13401 
13402   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13403   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13404   if (LHSDeclRef && RHSDeclRef) {
13405     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13406       return;
13407     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13408         RHSDeclRef->getDecl()->getCanonicalDecl())
13409       return;
13410 
13411     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13412                                         << LHSExpr->getSourceRange()
13413                                         << RHSExpr->getSourceRange();
13414     return;
13415   }
13416 
13417   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13418     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13419                                         << LHSExpr->getSourceRange()
13420                                         << RHSExpr->getSourceRange();
13421 }
13422 
13423 //===--- Layout compatibility ----------------------------------------------//
13424 
13425 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13426 
13427 /// Check if two enumeration types are layout-compatible.
13428 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13429   // C++11 [dcl.enum] p8:
13430   // Two enumeration types are layout-compatible if they have the same
13431   // underlying type.
13432   return ED1->isComplete() && ED2->isComplete() &&
13433          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13434 }
13435 
13436 /// Check if two fields are layout-compatible.
13437 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13438                                FieldDecl *Field2) {
13439   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13440     return false;
13441 
13442   if (Field1->isBitField() != Field2->isBitField())
13443     return false;
13444 
13445   if (Field1->isBitField()) {
13446     // Make sure that the bit-fields are the same length.
13447     unsigned Bits1 = Field1->getBitWidthValue(C);
13448     unsigned Bits2 = Field2->getBitWidthValue(C);
13449 
13450     if (Bits1 != Bits2)
13451       return false;
13452   }
13453 
13454   return true;
13455 }
13456 
13457 /// Check if two standard-layout structs are layout-compatible.
13458 /// (C++11 [class.mem] p17)
13459 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13460                                      RecordDecl *RD2) {
13461   // If both records are C++ classes, check that base classes match.
13462   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13463     // If one of records is a CXXRecordDecl we are in C++ mode,
13464     // thus the other one is a CXXRecordDecl, too.
13465     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13466     // Check number of base classes.
13467     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13468       return false;
13469 
13470     // Check the base classes.
13471     for (CXXRecordDecl::base_class_const_iterator
13472                Base1 = D1CXX->bases_begin(),
13473            BaseEnd1 = D1CXX->bases_end(),
13474               Base2 = D2CXX->bases_begin();
13475          Base1 != BaseEnd1;
13476          ++Base1, ++Base2) {
13477       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13478         return false;
13479     }
13480   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13481     // If only RD2 is a C++ class, it should have zero base classes.
13482     if (D2CXX->getNumBases() > 0)
13483       return false;
13484   }
13485 
13486   // Check the fields.
13487   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13488                              Field2End = RD2->field_end(),
13489                              Field1 = RD1->field_begin(),
13490                              Field1End = RD1->field_end();
13491   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13492     if (!isLayoutCompatible(C, *Field1, *Field2))
13493       return false;
13494   }
13495   if (Field1 != Field1End || Field2 != Field2End)
13496     return false;
13497 
13498   return true;
13499 }
13500 
13501 /// Check if two standard-layout unions are layout-compatible.
13502 /// (C++11 [class.mem] p18)
13503 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13504                                     RecordDecl *RD2) {
13505   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13506   for (auto *Field2 : RD2->fields())
13507     UnmatchedFields.insert(Field2);
13508 
13509   for (auto *Field1 : RD1->fields()) {
13510     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13511         I = UnmatchedFields.begin(),
13512         E = UnmatchedFields.end();
13513 
13514     for ( ; I != E; ++I) {
13515       if (isLayoutCompatible(C, Field1, *I)) {
13516         bool Result = UnmatchedFields.erase(*I);
13517         (void) Result;
13518         assert(Result);
13519         break;
13520       }
13521     }
13522     if (I == E)
13523       return false;
13524   }
13525 
13526   return UnmatchedFields.empty();
13527 }
13528 
13529 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13530                                RecordDecl *RD2) {
13531   if (RD1->isUnion() != RD2->isUnion())
13532     return false;
13533 
13534   if (RD1->isUnion())
13535     return isLayoutCompatibleUnion(C, RD1, RD2);
13536   else
13537     return isLayoutCompatibleStruct(C, RD1, RD2);
13538 }
13539 
13540 /// Check if two types are layout-compatible in C++11 sense.
13541 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13542   if (T1.isNull() || T2.isNull())
13543     return false;
13544 
13545   // C++11 [basic.types] p11:
13546   // If two types T1 and T2 are the same type, then T1 and T2 are
13547   // layout-compatible types.
13548   if (C.hasSameType(T1, T2))
13549     return true;
13550 
13551   T1 = T1.getCanonicalType().getUnqualifiedType();
13552   T2 = T2.getCanonicalType().getUnqualifiedType();
13553 
13554   const Type::TypeClass TC1 = T1->getTypeClass();
13555   const Type::TypeClass TC2 = T2->getTypeClass();
13556 
13557   if (TC1 != TC2)
13558     return false;
13559 
13560   if (TC1 == Type::Enum) {
13561     return isLayoutCompatible(C,
13562                               cast<EnumType>(T1)->getDecl(),
13563                               cast<EnumType>(T2)->getDecl());
13564   } else if (TC1 == Type::Record) {
13565     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13566       return false;
13567 
13568     return isLayoutCompatible(C,
13569                               cast<RecordType>(T1)->getDecl(),
13570                               cast<RecordType>(T2)->getDecl());
13571   }
13572 
13573   return false;
13574 }
13575 
13576 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13577 
13578 /// Given a type tag expression find the type tag itself.
13579 ///
13580 /// \param TypeExpr Type tag expression, as it appears in user's code.
13581 ///
13582 /// \param VD Declaration of an identifier that appears in a type tag.
13583 ///
13584 /// \param MagicValue Type tag magic value.
13585 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13586                             const ValueDecl **VD, uint64_t *MagicValue) {
13587   while(true) {
13588     if (!TypeExpr)
13589       return false;
13590 
13591     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13592 
13593     switch (TypeExpr->getStmtClass()) {
13594     case Stmt::UnaryOperatorClass: {
13595       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13596       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13597         TypeExpr = UO->getSubExpr();
13598         continue;
13599       }
13600       return false;
13601     }
13602 
13603     case Stmt::DeclRefExprClass: {
13604       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13605       *VD = DRE->getDecl();
13606       return true;
13607     }
13608 
13609     case Stmt::IntegerLiteralClass: {
13610       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13611       llvm::APInt MagicValueAPInt = IL->getValue();
13612       if (MagicValueAPInt.getActiveBits() <= 64) {
13613         *MagicValue = MagicValueAPInt.getZExtValue();
13614         return true;
13615       } else
13616         return false;
13617     }
13618 
13619     case Stmt::BinaryConditionalOperatorClass:
13620     case Stmt::ConditionalOperatorClass: {
13621       const AbstractConditionalOperator *ACO =
13622           cast<AbstractConditionalOperator>(TypeExpr);
13623       bool Result;
13624       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13625         if (Result)
13626           TypeExpr = ACO->getTrueExpr();
13627         else
13628           TypeExpr = ACO->getFalseExpr();
13629         continue;
13630       }
13631       return false;
13632     }
13633 
13634     case Stmt::BinaryOperatorClass: {
13635       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13636       if (BO->getOpcode() == BO_Comma) {
13637         TypeExpr = BO->getRHS();
13638         continue;
13639       }
13640       return false;
13641     }
13642 
13643     default:
13644       return false;
13645     }
13646   }
13647 }
13648 
13649 /// Retrieve the C type corresponding to type tag TypeExpr.
13650 ///
13651 /// \param TypeExpr Expression that specifies a type tag.
13652 ///
13653 /// \param MagicValues Registered magic values.
13654 ///
13655 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13656 ///        kind.
13657 ///
13658 /// \param TypeInfo Information about the corresponding C type.
13659 ///
13660 /// \returns true if the corresponding C type was found.
13661 static bool GetMatchingCType(
13662         const IdentifierInfo *ArgumentKind,
13663         const Expr *TypeExpr, const ASTContext &Ctx,
13664         const llvm::DenseMap<Sema::TypeTagMagicValue,
13665                              Sema::TypeTagData> *MagicValues,
13666         bool &FoundWrongKind,
13667         Sema::TypeTagData &TypeInfo) {
13668   FoundWrongKind = false;
13669 
13670   // Variable declaration that has type_tag_for_datatype attribute.
13671   const ValueDecl *VD = nullptr;
13672 
13673   uint64_t MagicValue;
13674 
13675   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13676     return false;
13677 
13678   if (VD) {
13679     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13680       if (I->getArgumentKind() != ArgumentKind) {
13681         FoundWrongKind = true;
13682         return false;
13683       }
13684       TypeInfo.Type = I->getMatchingCType();
13685       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13686       TypeInfo.MustBeNull = I->getMustBeNull();
13687       return true;
13688     }
13689     return false;
13690   }
13691 
13692   if (!MagicValues)
13693     return false;
13694 
13695   llvm::DenseMap<Sema::TypeTagMagicValue,
13696                  Sema::TypeTagData>::const_iterator I =
13697       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13698   if (I == MagicValues->end())
13699     return false;
13700 
13701   TypeInfo = I->second;
13702   return true;
13703 }
13704 
13705 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13706                                       uint64_t MagicValue, QualType Type,
13707                                       bool LayoutCompatible,
13708                                       bool MustBeNull) {
13709   if (!TypeTagForDatatypeMagicValues)
13710     TypeTagForDatatypeMagicValues.reset(
13711         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13712 
13713   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13714   (*TypeTagForDatatypeMagicValues)[Magic] =
13715       TypeTagData(Type, LayoutCompatible, MustBeNull);
13716 }
13717 
13718 static bool IsSameCharType(QualType T1, QualType T2) {
13719   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13720   if (!BT1)
13721     return false;
13722 
13723   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13724   if (!BT2)
13725     return false;
13726 
13727   BuiltinType::Kind T1Kind = BT1->getKind();
13728   BuiltinType::Kind T2Kind = BT2->getKind();
13729 
13730   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13731          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13732          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13733          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13734 }
13735 
13736 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13737                                     const ArrayRef<const Expr *> ExprArgs,
13738                                     SourceLocation CallSiteLoc) {
13739   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13740   bool IsPointerAttr = Attr->getIsPointer();
13741 
13742   // Retrieve the argument representing the 'type_tag'.
13743   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13744   if (TypeTagIdxAST >= ExprArgs.size()) {
13745     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13746         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13747     return;
13748   }
13749   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13750   bool FoundWrongKind;
13751   TypeTagData TypeInfo;
13752   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13753                         TypeTagForDatatypeMagicValues.get(),
13754                         FoundWrongKind, TypeInfo)) {
13755     if (FoundWrongKind)
13756       Diag(TypeTagExpr->getExprLoc(),
13757            diag::warn_type_tag_for_datatype_wrong_kind)
13758         << TypeTagExpr->getSourceRange();
13759     return;
13760   }
13761 
13762   // Retrieve the argument representing the 'arg_idx'.
13763   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13764   if (ArgumentIdxAST >= ExprArgs.size()) {
13765     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13766         << 1 << Attr->getArgumentIdx().getSourceIndex();
13767     return;
13768   }
13769   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13770   if (IsPointerAttr) {
13771     // Skip implicit cast of pointer to `void *' (as a function argument).
13772     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13773       if (ICE->getType()->isVoidPointerType() &&
13774           ICE->getCastKind() == CK_BitCast)
13775         ArgumentExpr = ICE->getSubExpr();
13776   }
13777   QualType ArgumentType = ArgumentExpr->getType();
13778 
13779   // Passing a `void*' pointer shouldn't trigger a warning.
13780   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13781     return;
13782 
13783   if (TypeInfo.MustBeNull) {
13784     // Type tag with matching void type requires a null pointer.
13785     if (!ArgumentExpr->isNullPointerConstant(Context,
13786                                              Expr::NPC_ValueDependentIsNotNull)) {
13787       Diag(ArgumentExpr->getExprLoc(),
13788            diag::warn_type_safety_null_pointer_required)
13789           << ArgumentKind->getName()
13790           << ArgumentExpr->getSourceRange()
13791           << TypeTagExpr->getSourceRange();
13792     }
13793     return;
13794   }
13795 
13796   QualType RequiredType = TypeInfo.Type;
13797   if (IsPointerAttr)
13798     RequiredType = Context.getPointerType(RequiredType);
13799 
13800   bool mismatch = false;
13801   if (!TypeInfo.LayoutCompatible) {
13802     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13803 
13804     // C++11 [basic.fundamental] p1:
13805     // Plain char, signed char, and unsigned char are three distinct types.
13806     //
13807     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13808     // char' depending on the current char signedness mode.
13809     if (mismatch)
13810       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13811                                            RequiredType->getPointeeType())) ||
13812           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13813         mismatch = false;
13814   } else
13815     if (IsPointerAttr)
13816       mismatch = !isLayoutCompatible(Context,
13817                                      ArgumentType->getPointeeType(),
13818                                      RequiredType->getPointeeType());
13819     else
13820       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13821 
13822   if (mismatch)
13823     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13824         << ArgumentType << ArgumentKind
13825         << TypeInfo.LayoutCompatible << RequiredType
13826         << ArgumentExpr->getSourceRange()
13827         << TypeTagExpr->getSourceRange();
13828 }
13829 
13830 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13831                                          CharUnits Alignment) {
13832   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13833 }
13834 
13835 void Sema::DiagnoseMisalignedMembers() {
13836   for (MisalignedMember &m : MisalignedMembers) {
13837     const NamedDecl *ND = m.RD;
13838     if (ND->getName().empty()) {
13839       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13840         ND = TD;
13841     }
13842     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
13843         << m.MD << ND << m.E->getSourceRange();
13844   }
13845   MisalignedMembers.clear();
13846 }
13847 
13848 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13849   E = E->IgnoreParens();
13850   if (!T->isPointerType() && !T->isIntegerType())
13851     return;
13852   if (isa<UnaryOperator>(E) &&
13853       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13854     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13855     if (isa<MemberExpr>(Op)) {
13856       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13857                           MisalignedMember(Op));
13858       if (MA != MisalignedMembers.end() &&
13859           (T->isIntegerType() ||
13860            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13861                                    Context.getTypeAlignInChars(
13862                                        T->getPointeeType()) <= MA->Alignment))))
13863         MisalignedMembers.erase(MA);
13864     }
13865   }
13866 }
13867 
13868 void Sema::RefersToMemberWithReducedAlignment(
13869     Expr *E,
13870     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13871         Action) {
13872   const auto *ME = dyn_cast<MemberExpr>(E);
13873   if (!ME)
13874     return;
13875 
13876   // No need to check expressions with an __unaligned-qualified type.
13877   if (E->getType().getQualifiers().hasUnaligned())
13878     return;
13879 
13880   // For a chain of MemberExpr like "a.b.c.d" this list
13881   // will keep FieldDecl's like [d, c, b].
13882   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13883   const MemberExpr *TopME = nullptr;
13884   bool AnyIsPacked = false;
13885   do {
13886     QualType BaseType = ME->getBase()->getType();
13887     if (ME->isArrow())
13888       BaseType = BaseType->getPointeeType();
13889     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13890     if (RD->isInvalidDecl())
13891       return;
13892 
13893     ValueDecl *MD = ME->getMemberDecl();
13894     auto *FD = dyn_cast<FieldDecl>(MD);
13895     // We do not care about non-data members.
13896     if (!FD || FD->isInvalidDecl())
13897       return;
13898 
13899     AnyIsPacked =
13900         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13901     ReverseMemberChain.push_back(FD);
13902 
13903     TopME = ME;
13904     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13905   } while (ME);
13906   assert(TopME && "We did not compute a topmost MemberExpr!");
13907 
13908   // Not the scope of this diagnostic.
13909   if (!AnyIsPacked)
13910     return;
13911 
13912   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13913   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13914   // TODO: The innermost base of the member expression may be too complicated.
13915   // For now, just disregard these cases. This is left for future
13916   // improvement.
13917   if (!DRE && !isa<CXXThisExpr>(TopBase))
13918       return;
13919 
13920   // Alignment expected by the whole expression.
13921   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13922 
13923   // No need to do anything else with this case.
13924   if (ExpectedAlignment.isOne())
13925     return;
13926 
13927   // Synthesize offset of the whole access.
13928   CharUnits Offset;
13929   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13930        I++) {
13931     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13932   }
13933 
13934   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13935   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13936       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13937 
13938   // The base expression of the innermost MemberExpr may give
13939   // stronger guarantees than the class containing the member.
13940   if (DRE && !TopME->isArrow()) {
13941     const ValueDecl *VD = DRE->getDecl();
13942     if (!VD->getType()->isReferenceType())
13943       CompleteObjectAlignment =
13944           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13945   }
13946 
13947   // Check if the synthesized offset fulfills the alignment.
13948   if (Offset % ExpectedAlignment != 0 ||
13949       // It may fulfill the offset it but the effective alignment may still be
13950       // lower than the expected expression alignment.
13951       CompleteObjectAlignment < ExpectedAlignment) {
13952     // If this happens, we want to determine a sensible culprit of this.
13953     // Intuitively, watching the chain of member expressions from right to
13954     // left, we start with the required alignment (as required by the field
13955     // type) but some packed attribute in that chain has reduced the alignment.
13956     // It may happen that another packed structure increases it again. But if
13957     // we are here such increase has not been enough. So pointing the first
13958     // FieldDecl that either is packed or else its RecordDecl is,
13959     // seems reasonable.
13960     FieldDecl *FD = nullptr;
13961     CharUnits Alignment;
13962     for (FieldDecl *FDI : ReverseMemberChain) {
13963       if (FDI->hasAttr<PackedAttr>() ||
13964           FDI->getParent()->hasAttr<PackedAttr>()) {
13965         FD = FDI;
13966         Alignment = std::min(
13967             Context.getTypeAlignInChars(FD->getType()),
13968             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13969         break;
13970       }
13971     }
13972     assert(FD && "We did not find a packed FieldDecl!");
13973     Action(E, FD->getParent(), FD, Alignment);
13974   }
13975 }
13976 
13977 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13978   using namespace std::placeholders;
13979 
13980   RefersToMemberWithReducedAlignment(
13981       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13982                      _2, _3, _4));
13983 }
13984