1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.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/Analysis/Analyses/FormatString.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195   if (checkArgCount(S, TheCall, 3))
196     return true;
197 
198   // First two arguments should be integers.
199   for (unsigned I = 0; I < 2; ++I) {
200     ExprResult Arg = TheCall->getArg(I);
201     QualType Ty = Arg.get()->getType();
202     if (!Ty->isIntegerType()) {
203       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
204           << Ty << Arg.get()->getSourceRange();
205       return true;
206     }
207     InitializedEntity Entity = InitializedEntity::InitializeParameter(
208         S.getASTContext(), Ty, /*consume*/ false);
209     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210     if (Arg.isInvalid())
211       return true;
212     TheCall->setArg(I, Arg.get());
213   }
214 
215   // Third argument should be a pointer to a non-const integer.
216   // IRGen correctly handles volatile, restrict, and address spaces, and
217   // the other qualifiers aren't possible.
218   {
219     ExprResult Arg = TheCall->getArg(2);
220     QualType Ty = Arg.get()->getType();
221     const auto *PtrTy = Ty->getAs<PointerType>();
222     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223           !PtrTy->getPointeeType().isConstQualified())) {
224       S.Diag(Arg.get()->getBeginLoc(),
225              diag::err_overflow_builtin_must_be_ptr_int)
226           << Ty << Arg.get()->getSourceRange();
227       return true;
228     }
229     InitializedEntity Entity = InitializedEntity::InitializeParameter(
230         S.getASTContext(), Ty, /*consume*/ false);
231     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232     if (Arg.isInvalid())
233       return true;
234     TheCall->setArg(2, Arg.get());
235   }
236   return false;
237 }
238 
239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
240                                   CallExpr *TheCall, unsigned SizeIdx,
241                                   unsigned DstSizeIdx,
242                                   StringRef LikelyMacroName) {
243   if (TheCall->getNumArgs() <= SizeIdx ||
244       TheCall->getNumArgs() <= DstSizeIdx)
245     return;
246 
247   const Expr *SizeArg = TheCall->getArg(SizeIdx);
248   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
249 
250   llvm::APSInt Size, DstSize;
251 
252   // find out if both sizes are known at compile time
253   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
254       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
255     return;
256 
257   if (Size.ule(DstSize))
258     return;
259 
260   // Confirmed overflow, so generate the diagnostic.
261   StringRef FunctionName = FDecl->getName();
262   SourceLocation SL = TheCall->getBeginLoc();
263   SourceManager &SM = S.getSourceManager();
264   // If we're in an expansion of a macro whose name corresponds to this builtin,
265   // use the simple macro name and location.
266   if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
267                             LikelyMacroName) {
268     FunctionName = LikelyMacroName;
269     SL = SM.getImmediateMacroCallerLoc(SL);
270   }
271 
272   S.Diag(SL, diag::warn_memcpy_chk_overflow)
273       << FunctionName << DstSize.toString(/*Radix=*/10)
274       << Size.toString(/*Radix=*/10);
275 }
276 
277 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
278   if (checkArgCount(S, BuiltinCall, 2))
279     return true;
280 
281   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
282   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
283   Expr *Call = BuiltinCall->getArg(0);
284   Expr *Chain = BuiltinCall->getArg(1);
285 
286   if (Call->getStmtClass() != Stmt::CallExprClass) {
287     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
288         << Call->getSourceRange();
289     return true;
290   }
291 
292   auto CE = cast<CallExpr>(Call);
293   if (CE->getCallee()->getType()->isBlockPointerType()) {
294     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
295         << Call->getSourceRange();
296     return true;
297   }
298 
299   const Decl *TargetDecl = CE->getCalleeDecl();
300   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
301     if (FD->getBuiltinID()) {
302       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
303           << Call->getSourceRange();
304       return true;
305     }
306 
307   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
308     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
309         << Call->getSourceRange();
310     return true;
311   }
312 
313   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
314   if (ChainResult.isInvalid())
315     return true;
316   if (!ChainResult.get()->getType()->isPointerType()) {
317     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
318         << Chain->getSourceRange();
319     return true;
320   }
321 
322   QualType ReturnTy = CE->getCallReturnType(S.Context);
323   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
324   QualType BuiltinTy = S.Context.getFunctionType(
325       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
326   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
327 
328   Builtin =
329       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
330 
331   BuiltinCall->setType(CE->getType());
332   BuiltinCall->setValueKind(CE->getValueKind());
333   BuiltinCall->setObjectKind(CE->getObjectKind());
334   BuiltinCall->setCallee(Builtin);
335   BuiltinCall->setArg(1, ChainResult.get());
336 
337   return false;
338 }
339 
340 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
341                                      Scope::ScopeFlags NeededScopeFlags,
342                                      unsigned DiagID) {
343   // Scopes aren't available during instantiation. Fortunately, builtin
344   // functions cannot be template args so they cannot be formed through template
345   // instantiation. Therefore checking once during the parse is sufficient.
346   if (SemaRef.inTemplateInstantiation())
347     return false;
348 
349   Scope *S = SemaRef.getCurScope();
350   while (S && !S->isSEHExceptScope())
351     S = S->getParent();
352   if (!S || !(S->getFlags() & NeededScopeFlags)) {
353     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
354     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
355         << DRE->getDecl()->getIdentifier();
356     return true;
357   }
358 
359   return false;
360 }
361 
362 static inline bool isBlockPointer(Expr *Arg) {
363   return Arg->getType()->isBlockPointerType();
364 }
365 
366 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
367 /// void*, which is a requirement of device side enqueue.
368 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
369   const BlockPointerType *BPT =
370       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
371   ArrayRef<QualType> Params =
372       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
373   unsigned ArgCounter = 0;
374   bool IllegalParams = false;
375   // Iterate through the block parameters until either one is found that is not
376   // a local void*, or the block is valid.
377   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
378        I != E; ++I, ++ArgCounter) {
379     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
380         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
381             LangAS::opencl_local) {
382       // Get the location of the error. If a block literal has been passed
383       // (BlockExpr) then we can point straight to the offending argument,
384       // else we just point to the variable reference.
385       SourceLocation ErrorLoc;
386       if (isa<BlockExpr>(BlockArg)) {
387         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
388         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
389       } else if (isa<DeclRefExpr>(BlockArg)) {
390         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
391       }
392       S.Diag(ErrorLoc,
393              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
394       IllegalParams = true;
395     }
396   }
397 
398   return IllegalParams;
399 }
400 
401 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
402   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
403     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
404         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
405     return true;
406   }
407   return false;
408 }
409 
410 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
411   if (checkArgCount(S, TheCall, 2))
412     return true;
413 
414   if (checkOpenCLSubgroupExt(S, TheCall))
415     return true;
416 
417   // First argument is an ndrange_t type.
418   Expr *NDRangeArg = TheCall->getArg(0);
419   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
420     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
421         << TheCall->getDirectCallee() << "'ndrange_t'";
422     return true;
423   }
424 
425   Expr *BlockArg = TheCall->getArg(1);
426   if (!isBlockPointer(BlockArg)) {
427     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
428         << TheCall->getDirectCallee() << "block";
429     return true;
430   }
431   return checkOpenCLBlockArgs(S, BlockArg);
432 }
433 
434 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
435 /// get_kernel_work_group_size
436 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
437 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
438   if (checkArgCount(S, TheCall, 1))
439     return true;
440 
441   Expr *BlockArg = TheCall->getArg(0);
442   if (!isBlockPointer(BlockArg)) {
443     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
444         << TheCall->getDirectCallee() << "block";
445     return true;
446   }
447   return checkOpenCLBlockArgs(S, BlockArg);
448 }
449 
450 /// Diagnose integer type and any valid implicit conversion to it.
451 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
452                                       const QualType &IntType);
453 
454 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
455                                             unsigned Start, unsigned End) {
456   bool IllegalParams = false;
457   for (unsigned I = Start; I <= End; ++I)
458     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
459                                               S.Context.getSizeType());
460   return IllegalParams;
461 }
462 
463 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
464 /// 'local void*' parameter of passed block.
465 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
466                                            Expr *BlockArg,
467                                            unsigned NumNonVarArgs) {
468   const BlockPointerType *BPT =
469       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
470   unsigned NumBlockParams =
471       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
472   unsigned TotalNumArgs = TheCall->getNumArgs();
473 
474   // For each argument passed to the block, a corresponding uint needs to
475   // be passed to describe the size of the local memory.
476   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
477     S.Diag(TheCall->getBeginLoc(),
478            diag::err_opencl_enqueue_kernel_local_size_args);
479     return true;
480   }
481 
482   // Check that the sizes of the local memory are specified by integers.
483   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
484                                          TotalNumArgs - 1);
485 }
486 
487 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
488 /// overload formats specified in Table 6.13.17.1.
489 /// int enqueue_kernel(queue_t queue,
490 ///                    kernel_enqueue_flags_t flags,
491 ///                    const ndrange_t ndrange,
492 ///                    void (^block)(void))
493 /// int enqueue_kernel(queue_t queue,
494 ///                    kernel_enqueue_flags_t flags,
495 ///                    const ndrange_t ndrange,
496 ///                    uint num_events_in_wait_list,
497 ///                    clk_event_t *event_wait_list,
498 ///                    clk_event_t *event_ret,
499 ///                    void (^block)(void))
500 /// int enqueue_kernel(queue_t queue,
501 ///                    kernel_enqueue_flags_t flags,
502 ///                    const ndrange_t ndrange,
503 ///                    void (^block)(local void*, ...),
504 ///                    uint size0, ...)
505 /// int enqueue_kernel(queue_t queue,
506 ///                    kernel_enqueue_flags_t flags,
507 ///                    const ndrange_t ndrange,
508 ///                    uint num_events_in_wait_list,
509 ///                    clk_event_t *event_wait_list,
510 ///                    clk_event_t *event_ret,
511 ///                    void (^block)(local void*, ...),
512 ///                    uint size0, ...)
513 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
514   unsigned NumArgs = TheCall->getNumArgs();
515 
516   if (NumArgs < 4) {
517     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
518     return true;
519   }
520 
521   Expr *Arg0 = TheCall->getArg(0);
522   Expr *Arg1 = TheCall->getArg(1);
523   Expr *Arg2 = TheCall->getArg(2);
524   Expr *Arg3 = TheCall->getArg(3);
525 
526   // First argument always needs to be a queue_t type.
527   if (!Arg0->getType()->isQueueT()) {
528     S.Diag(TheCall->getArg(0)->getBeginLoc(),
529            diag::err_opencl_builtin_expected_type)
530         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
531     return true;
532   }
533 
534   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
535   if (!Arg1->getType()->isIntegerType()) {
536     S.Diag(TheCall->getArg(1)->getBeginLoc(),
537            diag::err_opencl_builtin_expected_type)
538         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
539     return true;
540   }
541 
542   // Third argument is always an ndrange_t type.
543   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
544     S.Diag(TheCall->getArg(2)->getBeginLoc(),
545            diag::err_opencl_builtin_expected_type)
546         << TheCall->getDirectCallee() << "'ndrange_t'";
547     return true;
548   }
549 
550   // With four arguments, there is only one form that the function could be
551   // called in: no events and no variable arguments.
552   if (NumArgs == 4) {
553     // check that the last argument is the right block type.
554     if (!isBlockPointer(Arg3)) {
555       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
556           << TheCall->getDirectCallee() << "block";
557       return true;
558     }
559     // we have a block type, check the prototype
560     const BlockPointerType *BPT =
561         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
562     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
563       S.Diag(Arg3->getBeginLoc(),
564              diag::err_opencl_enqueue_kernel_blocks_no_args);
565       return true;
566     }
567     return false;
568   }
569   // we can have block + varargs.
570   if (isBlockPointer(Arg3))
571     return (checkOpenCLBlockArgs(S, Arg3) ||
572             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
573   // last two cases with either exactly 7 args or 7 args and varargs.
574   if (NumArgs >= 7) {
575     // check common block argument.
576     Expr *Arg6 = TheCall->getArg(6);
577     if (!isBlockPointer(Arg6)) {
578       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
579           << TheCall->getDirectCallee() << "block";
580       return true;
581     }
582     if (checkOpenCLBlockArgs(S, Arg6))
583       return true;
584 
585     // Forth argument has to be any integer type.
586     if (!Arg3->getType()->isIntegerType()) {
587       S.Diag(TheCall->getArg(3)->getBeginLoc(),
588              diag::err_opencl_builtin_expected_type)
589           << TheCall->getDirectCallee() << "integer";
590       return true;
591     }
592     // check remaining common arguments.
593     Expr *Arg4 = TheCall->getArg(4);
594     Expr *Arg5 = TheCall->getArg(5);
595 
596     // Fifth argument is always passed as a pointer to clk_event_t.
597     if (!Arg4->isNullPointerConstant(S.Context,
598                                      Expr::NPC_ValueDependentIsNotNull) &&
599         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
600       S.Diag(TheCall->getArg(4)->getBeginLoc(),
601              diag::err_opencl_builtin_expected_type)
602           << TheCall->getDirectCallee()
603           << S.Context.getPointerType(S.Context.OCLClkEventTy);
604       return true;
605     }
606 
607     // Sixth argument is always passed as a pointer to clk_event_t.
608     if (!Arg5->isNullPointerConstant(S.Context,
609                                      Expr::NPC_ValueDependentIsNotNull) &&
610         !(Arg5->getType()->isPointerType() &&
611           Arg5->getType()->getPointeeType()->isClkEventT())) {
612       S.Diag(TheCall->getArg(5)->getBeginLoc(),
613              diag::err_opencl_builtin_expected_type)
614           << TheCall->getDirectCallee()
615           << S.Context.getPointerType(S.Context.OCLClkEventTy);
616       return true;
617     }
618 
619     if (NumArgs == 7)
620       return false;
621 
622     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
623   }
624 
625   // None of the specific case has been detected, give generic error
626   S.Diag(TheCall->getBeginLoc(),
627          diag::err_opencl_enqueue_kernel_incorrect_args);
628   return true;
629 }
630 
631 /// Returns OpenCL access qual.
632 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
633     return D->getAttr<OpenCLAccessAttr>();
634 }
635 
636 /// Returns true if pipe element type is different from the pointer.
637 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
638   const Expr *Arg0 = Call->getArg(0);
639   // First argument type should always be pipe.
640   if (!Arg0->getType()->isPipeType()) {
641     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
642         << Call->getDirectCallee() << Arg0->getSourceRange();
643     return true;
644   }
645   OpenCLAccessAttr *AccessQual =
646       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
647   // Validates the access qualifier is compatible with the call.
648   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
649   // read_only and write_only, and assumed to be read_only if no qualifier is
650   // specified.
651   switch (Call->getDirectCallee()->getBuiltinID()) {
652   case Builtin::BIread_pipe:
653   case Builtin::BIreserve_read_pipe:
654   case Builtin::BIcommit_read_pipe:
655   case Builtin::BIwork_group_reserve_read_pipe:
656   case Builtin::BIsub_group_reserve_read_pipe:
657   case Builtin::BIwork_group_commit_read_pipe:
658   case Builtin::BIsub_group_commit_read_pipe:
659     if (!(!AccessQual || AccessQual->isReadOnly())) {
660       S.Diag(Arg0->getBeginLoc(),
661              diag::err_opencl_builtin_pipe_invalid_access_modifier)
662           << "read_only" << Arg0->getSourceRange();
663       return true;
664     }
665     break;
666   case Builtin::BIwrite_pipe:
667   case Builtin::BIreserve_write_pipe:
668   case Builtin::BIcommit_write_pipe:
669   case Builtin::BIwork_group_reserve_write_pipe:
670   case Builtin::BIsub_group_reserve_write_pipe:
671   case Builtin::BIwork_group_commit_write_pipe:
672   case Builtin::BIsub_group_commit_write_pipe:
673     if (!(AccessQual && AccessQual->isWriteOnly())) {
674       S.Diag(Arg0->getBeginLoc(),
675              diag::err_opencl_builtin_pipe_invalid_access_modifier)
676           << "write_only" << Arg0->getSourceRange();
677       return true;
678     }
679     break;
680   default:
681     break;
682   }
683   return false;
684 }
685 
686 /// Returns true if pipe element type is different from the pointer.
687 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
688   const Expr *Arg0 = Call->getArg(0);
689   const Expr *ArgIdx = Call->getArg(Idx);
690   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
691   const QualType EltTy = PipeTy->getElementType();
692   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
693   // The Idx argument should be a pointer and the type of the pointer and
694   // the type of pipe element should also be the same.
695   if (!ArgTy ||
696       !S.Context.hasSameType(
697           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
698     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
699         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
700         << ArgIdx->getType() << ArgIdx->getSourceRange();
701     return true;
702   }
703   return false;
704 }
705 
706 // Performs semantic analysis for the read/write_pipe call.
707 // \param S Reference to the semantic analyzer.
708 // \param Call A pointer to the builtin call.
709 // \return True if a semantic error has been found, false otherwise.
710 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
711   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
712   // functions have two forms.
713   switch (Call->getNumArgs()) {
714   case 2:
715     if (checkOpenCLPipeArg(S, Call))
716       return true;
717     // The call with 2 arguments should be
718     // read/write_pipe(pipe T, T*).
719     // Check packet type T.
720     if (checkOpenCLPipePacketType(S, Call, 1))
721       return true;
722     break;
723 
724   case 4: {
725     if (checkOpenCLPipeArg(S, Call))
726       return true;
727     // The call with 4 arguments should be
728     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
729     // Check reserve_id_t.
730     if (!Call->getArg(1)->getType()->isReserveIDT()) {
731       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
732           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
733           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
734       return true;
735     }
736 
737     // Check the index.
738     const Expr *Arg2 = Call->getArg(2);
739     if (!Arg2->getType()->isIntegerType() &&
740         !Arg2->getType()->isUnsignedIntegerType()) {
741       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
742           << Call->getDirectCallee() << S.Context.UnsignedIntTy
743           << Arg2->getType() << Arg2->getSourceRange();
744       return true;
745     }
746 
747     // Check packet type T.
748     if (checkOpenCLPipePacketType(S, Call, 3))
749       return true;
750   } break;
751   default:
752     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
753         << Call->getDirectCallee() << Call->getSourceRange();
754     return true;
755   }
756 
757   return false;
758 }
759 
760 // Performs a semantic analysis on the {work_group_/sub_group_
761 //        /_}reserve_{read/write}_pipe
762 // \param S Reference to the semantic analyzer.
763 // \param Call The call to the builtin function to be analyzed.
764 // \return True if a semantic error was found, false otherwise.
765 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
766   if (checkArgCount(S, Call, 2))
767     return true;
768 
769   if (checkOpenCLPipeArg(S, Call))
770     return true;
771 
772   // Check the reserve size.
773   if (!Call->getArg(1)->getType()->isIntegerType() &&
774       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
775     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
776         << Call->getDirectCallee() << S.Context.UnsignedIntTy
777         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
778     return true;
779   }
780 
781   // Since return type of reserve_read/write_pipe built-in function is
782   // reserve_id_t, which is not defined in the builtin def file , we used int
783   // as return type and need to override the return type of these functions.
784   Call->setType(S.Context.OCLReserveIDTy);
785 
786   return false;
787 }
788 
789 // Performs a semantic analysis on {work_group_/sub_group_
790 //        /_}commit_{read/write}_pipe
791 // \param S Reference to the semantic analyzer.
792 // \param Call The call to the builtin function to be analyzed.
793 // \return True if a semantic error was found, false otherwise.
794 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
795   if (checkArgCount(S, Call, 2))
796     return true;
797 
798   if (checkOpenCLPipeArg(S, Call))
799     return true;
800 
801   // Check reserve_id_t.
802   if (!Call->getArg(1)->getType()->isReserveIDT()) {
803     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
804         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
805         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
806     return true;
807   }
808 
809   return false;
810 }
811 
812 // Performs a semantic analysis on the call to built-in Pipe
813 //        Query Functions.
814 // \param S Reference to the semantic analyzer.
815 // \param Call The call to the builtin function to be analyzed.
816 // \return True if a semantic error was found, false otherwise.
817 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
818   if (checkArgCount(S, Call, 1))
819     return true;
820 
821   if (!Call->getArg(0)->getType()->isPipeType()) {
822     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
823         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
824     return true;
825   }
826 
827   return false;
828 }
829 
830 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
831 // Performs semantic analysis for the to_global/local/private call.
832 // \param S Reference to the semantic analyzer.
833 // \param BuiltinID ID of the builtin function.
834 // \param Call A pointer to the builtin call.
835 // \return True if a semantic error has been found, false otherwise.
836 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
837                                     CallExpr *Call) {
838   if (Call->getNumArgs() != 1) {
839     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
840         << Call->getDirectCallee() << Call->getSourceRange();
841     return true;
842   }
843 
844   auto RT = Call->getArg(0)->getType();
845   if (!RT->isPointerType() || RT->getPointeeType()
846       .getAddressSpace() == LangAS::opencl_constant) {
847     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
848         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
849     return true;
850   }
851 
852   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
853     S.Diag(Call->getArg(0)->getBeginLoc(),
854            diag::warn_opencl_generic_address_space_arg)
855         << Call->getDirectCallee()->getNameInfo().getAsString()
856         << Call->getArg(0)->getSourceRange();
857   }
858 
859   RT = RT->getPointeeType();
860   auto Qual = RT.getQualifiers();
861   switch (BuiltinID) {
862   case Builtin::BIto_global:
863     Qual.setAddressSpace(LangAS::opencl_global);
864     break;
865   case Builtin::BIto_local:
866     Qual.setAddressSpace(LangAS::opencl_local);
867     break;
868   case Builtin::BIto_private:
869     Qual.setAddressSpace(LangAS::opencl_private);
870     break;
871   default:
872     llvm_unreachable("Invalid builtin function");
873   }
874   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
875       RT.getUnqualifiedType(), Qual)));
876 
877   return false;
878 }
879 
880 // Emit an error and return true if the current architecture is not in the list
881 // of supported architectures.
882 static bool
883 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
884                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
885   llvm::Triple::ArchType CurArch =
886       S.getASTContext().getTargetInfo().getTriple().getArch();
887   if (llvm::is_contained(SupportedArchs, CurArch))
888     return false;
889   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
890       << TheCall->getSourceRange();
891   return true;
892 }
893 
894 ExprResult
895 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
896                                CallExpr *TheCall) {
897   ExprResult TheCallResult(TheCall);
898 
899   // Find out if any arguments are required to be integer constant expressions.
900   unsigned ICEArguments = 0;
901   ASTContext::GetBuiltinTypeError Error;
902   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
903   if (Error != ASTContext::GE_None)
904     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
905 
906   // If any arguments are required to be ICE's, check and diagnose.
907   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
908     // Skip arguments not required to be ICE's.
909     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
910 
911     llvm::APSInt Result;
912     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
913       return true;
914     ICEArguments &= ~(1 << ArgNo);
915   }
916 
917   switch (BuiltinID) {
918   case Builtin::BI__builtin___CFStringMakeConstantString:
919     assert(TheCall->getNumArgs() == 1 &&
920            "Wrong # arguments to builtin CFStringMakeConstantString");
921     if (CheckObjCString(TheCall->getArg(0)))
922       return ExprError();
923     break;
924   case Builtin::BI__builtin_ms_va_start:
925   case Builtin::BI__builtin_stdarg_start:
926   case Builtin::BI__builtin_va_start:
927     if (SemaBuiltinVAStart(BuiltinID, TheCall))
928       return ExprError();
929     break;
930   case Builtin::BI__va_start: {
931     switch (Context.getTargetInfo().getTriple().getArch()) {
932     case llvm::Triple::aarch64:
933     case llvm::Triple::arm:
934     case llvm::Triple::thumb:
935       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
936         return ExprError();
937       break;
938     default:
939       if (SemaBuiltinVAStart(BuiltinID, TheCall))
940         return ExprError();
941       break;
942     }
943     break;
944   }
945 
946   // The acquire, release, and no fence variants are ARM and AArch64 only.
947   case Builtin::BI_interlockedbittestandset_acq:
948   case Builtin::BI_interlockedbittestandset_rel:
949   case Builtin::BI_interlockedbittestandset_nf:
950   case Builtin::BI_interlockedbittestandreset_acq:
951   case Builtin::BI_interlockedbittestandreset_rel:
952   case Builtin::BI_interlockedbittestandreset_nf:
953     if (CheckBuiltinTargetSupport(
954             *this, BuiltinID, TheCall,
955             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
956       return ExprError();
957     break;
958 
959   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
960   case Builtin::BI_bittest64:
961   case Builtin::BI_bittestandcomplement64:
962   case Builtin::BI_bittestandreset64:
963   case Builtin::BI_bittestandset64:
964   case Builtin::BI_interlockedbittestandreset64:
965   case Builtin::BI_interlockedbittestandset64:
966     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
967                                   {llvm::Triple::x86_64, llvm::Triple::arm,
968                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
969       return ExprError();
970     break;
971 
972   case Builtin::BI__builtin_isgreater:
973   case Builtin::BI__builtin_isgreaterequal:
974   case Builtin::BI__builtin_isless:
975   case Builtin::BI__builtin_islessequal:
976   case Builtin::BI__builtin_islessgreater:
977   case Builtin::BI__builtin_isunordered:
978     if (SemaBuiltinUnorderedCompare(TheCall))
979       return ExprError();
980     break;
981   case Builtin::BI__builtin_fpclassify:
982     if (SemaBuiltinFPClassification(TheCall, 6))
983       return ExprError();
984     break;
985   case Builtin::BI__builtin_isfinite:
986   case Builtin::BI__builtin_isinf:
987   case Builtin::BI__builtin_isinf_sign:
988   case Builtin::BI__builtin_isnan:
989   case Builtin::BI__builtin_isnormal:
990   case Builtin::BI__builtin_signbit:
991   case Builtin::BI__builtin_signbitf:
992   case Builtin::BI__builtin_signbitl:
993     if (SemaBuiltinFPClassification(TheCall, 1))
994       return ExprError();
995     break;
996   case Builtin::BI__builtin_shufflevector:
997     return SemaBuiltinShuffleVector(TheCall);
998     // TheCall will be freed by the smart pointer here, but that's fine, since
999     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1000   case Builtin::BI__builtin_prefetch:
1001     if (SemaBuiltinPrefetch(TheCall))
1002       return ExprError();
1003     break;
1004   case Builtin::BI__builtin_alloca_with_align:
1005     if (SemaBuiltinAllocaWithAlign(TheCall))
1006       return ExprError();
1007     break;
1008   case Builtin::BI__assume:
1009   case Builtin::BI__builtin_assume:
1010     if (SemaBuiltinAssume(TheCall))
1011       return ExprError();
1012     break;
1013   case Builtin::BI__builtin_assume_aligned:
1014     if (SemaBuiltinAssumeAligned(TheCall))
1015       return ExprError();
1016     break;
1017   case Builtin::BI__builtin_object_size:
1018     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1019       return ExprError();
1020     break;
1021   case Builtin::BI__builtin_longjmp:
1022     if (SemaBuiltinLongjmp(TheCall))
1023       return ExprError();
1024     break;
1025   case Builtin::BI__builtin_setjmp:
1026     if (SemaBuiltinSetjmp(TheCall))
1027       return ExprError();
1028     break;
1029   case Builtin::BI_setjmp:
1030   case Builtin::BI_setjmpex:
1031     if (checkArgCount(*this, TheCall, 1))
1032       return true;
1033     break;
1034   case Builtin::BI__builtin_classify_type:
1035     if (checkArgCount(*this, TheCall, 1)) return true;
1036     TheCall->setType(Context.IntTy);
1037     break;
1038   case Builtin::BI__builtin_constant_p:
1039     if (checkArgCount(*this, TheCall, 1)) return true;
1040     TheCall->setType(Context.IntTy);
1041     break;
1042   case Builtin::BI__sync_fetch_and_add:
1043   case Builtin::BI__sync_fetch_and_add_1:
1044   case Builtin::BI__sync_fetch_and_add_2:
1045   case Builtin::BI__sync_fetch_and_add_4:
1046   case Builtin::BI__sync_fetch_and_add_8:
1047   case Builtin::BI__sync_fetch_and_add_16:
1048   case Builtin::BI__sync_fetch_and_sub:
1049   case Builtin::BI__sync_fetch_and_sub_1:
1050   case Builtin::BI__sync_fetch_and_sub_2:
1051   case Builtin::BI__sync_fetch_and_sub_4:
1052   case Builtin::BI__sync_fetch_and_sub_8:
1053   case Builtin::BI__sync_fetch_and_sub_16:
1054   case Builtin::BI__sync_fetch_and_or:
1055   case Builtin::BI__sync_fetch_and_or_1:
1056   case Builtin::BI__sync_fetch_and_or_2:
1057   case Builtin::BI__sync_fetch_and_or_4:
1058   case Builtin::BI__sync_fetch_and_or_8:
1059   case Builtin::BI__sync_fetch_and_or_16:
1060   case Builtin::BI__sync_fetch_and_and:
1061   case Builtin::BI__sync_fetch_and_and_1:
1062   case Builtin::BI__sync_fetch_and_and_2:
1063   case Builtin::BI__sync_fetch_and_and_4:
1064   case Builtin::BI__sync_fetch_and_and_8:
1065   case Builtin::BI__sync_fetch_and_and_16:
1066   case Builtin::BI__sync_fetch_and_xor:
1067   case Builtin::BI__sync_fetch_and_xor_1:
1068   case Builtin::BI__sync_fetch_and_xor_2:
1069   case Builtin::BI__sync_fetch_and_xor_4:
1070   case Builtin::BI__sync_fetch_and_xor_8:
1071   case Builtin::BI__sync_fetch_and_xor_16:
1072   case Builtin::BI__sync_fetch_and_nand:
1073   case Builtin::BI__sync_fetch_and_nand_1:
1074   case Builtin::BI__sync_fetch_and_nand_2:
1075   case Builtin::BI__sync_fetch_and_nand_4:
1076   case Builtin::BI__sync_fetch_and_nand_8:
1077   case Builtin::BI__sync_fetch_and_nand_16:
1078   case Builtin::BI__sync_add_and_fetch:
1079   case Builtin::BI__sync_add_and_fetch_1:
1080   case Builtin::BI__sync_add_and_fetch_2:
1081   case Builtin::BI__sync_add_and_fetch_4:
1082   case Builtin::BI__sync_add_and_fetch_8:
1083   case Builtin::BI__sync_add_and_fetch_16:
1084   case Builtin::BI__sync_sub_and_fetch:
1085   case Builtin::BI__sync_sub_and_fetch_1:
1086   case Builtin::BI__sync_sub_and_fetch_2:
1087   case Builtin::BI__sync_sub_and_fetch_4:
1088   case Builtin::BI__sync_sub_and_fetch_8:
1089   case Builtin::BI__sync_sub_and_fetch_16:
1090   case Builtin::BI__sync_and_and_fetch:
1091   case Builtin::BI__sync_and_and_fetch_1:
1092   case Builtin::BI__sync_and_and_fetch_2:
1093   case Builtin::BI__sync_and_and_fetch_4:
1094   case Builtin::BI__sync_and_and_fetch_8:
1095   case Builtin::BI__sync_and_and_fetch_16:
1096   case Builtin::BI__sync_or_and_fetch:
1097   case Builtin::BI__sync_or_and_fetch_1:
1098   case Builtin::BI__sync_or_and_fetch_2:
1099   case Builtin::BI__sync_or_and_fetch_4:
1100   case Builtin::BI__sync_or_and_fetch_8:
1101   case Builtin::BI__sync_or_and_fetch_16:
1102   case Builtin::BI__sync_xor_and_fetch:
1103   case Builtin::BI__sync_xor_and_fetch_1:
1104   case Builtin::BI__sync_xor_and_fetch_2:
1105   case Builtin::BI__sync_xor_and_fetch_4:
1106   case Builtin::BI__sync_xor_and_fetch_8:
1107   case Builtin::BI__sync_xor_and_fetch_16:
1108   case Builtin::BI__sync_nand_and_fetch:
1109   case Builtin::BI__sync_nand_and_fetch_1:
1110   case Builtin::BI__sync_nand_and_fetch_2:
1111   case Builtin::BI__sync_nand_and_fetch_4:
1112   case Builtin::BI__sync_nand_and_fetch_8:
1113   case Builtin::BI__sync_nand_and_fetch_16:
1114   case Builtin::BI__sync_val_compare_and_swap:
1115   case Builtin::BI__sync_val_compare_and_swap_1:
1116   case Builtin::BI__sync_val_compare_and_swap_2:
1117   case Builtin::BI__sync_val_compare_and_swap_4:
1118   case Builtin::BI__sync_val_compare_and_swap_8:
1119   case Builtin::BI__sync_val_compare_and_swap_16:
1120   case Builtin::BI__sync_bool_compare_and_swap:
1121   case Builtin::BI__sync_bool_compare_and_swap_1:
1122   case Builtin::BI__sync_bool_compare_and_swap_2:
1123   case Builtin::BI__sync_bool_compare_and_swap_4:
1124   case Builtin::BI__sync_bool_compare_and_swap_8:
1125   case Builtin::BI__sync_bool_compare_and_swap_16:
1126   case Builtin::BI__sync_lock_test_and_set:
1127   case Builtin::BI__sync_lock_test_and_set_1:
1128   case Builtin::BI__sync_lock_test_and_set_2:
1129   case Builtin::BI__sync_lock_test_and_set_4:
1130   case Builtin::BI__sync_lock_test_and_set_8:
1131   case Builtin::BI__sync_lock_test_and_set_16:
1132   case Builtin::BI__sync_lock_release:
1133   case Builtin::BI__sync_lock_release_1:
1134   case Builtin::BI__sync_lock_release_2:
1135   case Builtin::BI__sync_lock_release_4:
1136   case Builtin::BI__sync_lock_release_8:
1137   case Builtin::BI__sync_lock_release_16:
1138   case Builtin::BI__sync_swap:
1139   case Builtin::BI__sync_swap_1:
1140   case Builtin::BI__sync_swap_2:
1141   case Builtin::BI__sync_swap_4:
1142   case Builtin::BI__sync_swap_8:
1143   case Builtin::BI__sync_swap_16:
1144     return SemaBuiltinAtomicOverloaded(TheCallResult);
1145   case Builtin::BI__sync_synchronize:
1146     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1147         << TheCall->getCallee()->getSourceRange();
1148     break;
1149   case Builtin::BI__builtin_nontemporal_load:
1150   case Builtin::BI__builtin_nontemporal_store:
1151     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1152 #define BUILTIN(ID, TYPE, ATTRS)
1153 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1154   case Builtin::BI##ID: \
1155     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1156 #include "clang/Basic/Builtins.def"
1157   case Builtin::BI__annotation:
1158     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1159       return ExprError();
1160     break;
1161   case Builtin::BI__builtin_annotation:
1162     if (SemaBuiltinAnnotation(*this, TheCall))
1163       return ExprError();
1164     break;
1165   case Builtin::BI__builtin_addressof:
1166     if (SemaBuiltinAddressof(*this, TheCall))
1167       return ExprError();
1168     break;
1169   case Builtin::BI__builtin_add_overflow:
1170   case Builtin::BI__builtin_sub_overflow:
1171   case Builtin::BI__builtin_mul_overflow:
1172     if (SemaBuiltinOverflow(*this, TheCall))
1173       return ExprError();
1174     break;
1175   case Builtin::BI__builtin_operator_new:
1176   case Builtin::BI__builtin_operator_delete: {
1177     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1178     ExprResult Res =
1179         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1180     if (Res.isInvalid())
1181       CorrectDelayedTyposInExpr(TheCallResult.get());
1182     return Res;
1183   }
1184   case Builtin::BI__builtin_dump_struct: {
1185     // We first want to ensure we are called with 2 arguments
1186     if (checkArgCount(*this, TheCall, 2))
1187       return ExprError();
1188     // Ensure that the first argument is of type 'struct XX *'
1189     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1190     const QualType PtrArgType = PtrArg->getType();
1191     if (!PtrArgType->isPointerType() ||
1192         !PtrArgType->getPointeeType()->isRecordType()) {
1193       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1194           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1195           << "structure pointer";
1196       return ExprError();
1197     }
1198 
1199     // Ensure that the second argument is of type 'FunctionType'
1200     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1201     const QualType FnPtrArgType = FnPtrArg->getType();
1202     if (!FnPtrArgType->isPointerType()) {
1203       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1204           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1205           << FnPtrArgType << "'int (*)(const char *, ...)'";
1206       return ExprError();
1207     }
1208 
1209     const auto *FuncType =
1210         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1211 
1212     if (!FuncType) {
1213       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1214           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1215           << FnPtrArgType << "'int (*)(const char *, ...)'";
1216       return ExprError();
1217     }
1218 
1219     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1220       if (!FT->getNumParams()) {
1221         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1222             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1223             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1224         return ExprError();
1225       }
1226       QualType PT = FT->getParamType(0);
1227       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1228           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1229           !PT->getPointeeType().isConstQualified()) {
1230         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1231             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1232             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1233         return ExprError();
1234       }
1235     }
1236 
1237     TheCall->setType(Context.IntTy);
1238     break;
1239   }
1240 
1241   // check secure string manipulation functions where overflows
1242   // are detectable at compile time
1243   case Builtin::BI__builtin___memcpy_chk:
1244     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
1245     break;
1246   case Builtin::BI__builtin___memmove_chk:
1247     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
1248     break;
1249   case Builtin::BI__builtin___memset_chk:
1250     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
1251     break;
1252   case Builtin::BI__builtin___strlcat_chk:
1253     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
1254     break;
1255   case Builtin::BI__builtin___strlcpy_chk:
1256     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
1257     break;
1258   case Builtin::BI__builtin___strncat_chk:
1259     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
1260     break;
1261   case Builtin::BI__builtin___strncpy_chk:
1262     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
1263     break;
1264   case Builtin::BI__builtin___stpncpy_chk:
1265     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
1266     break;
1267   case Builtin::BI__builtin___memccpy_chk:
1268     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
1269     break;
1270   case Builtin::BI__builtin___snprintf_chk:
1271     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
1272     break;
1273   case Builtin::BI__builtin___vsnprintf_chk:
1274     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
1275     break;
1276   case Builtin::BI__builtin_call_with_static_chain:
1277     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1278       return ExprError();
1279     break;
1280   case Builtin::BI__exception_code:
1281   case Builtin::BI_exception_code:
1282     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1283                                  diag::err_seh___except_block))
1284       return ExprError();
1285     break;
1286   case Builtin::BI__exception_info:
1287   case Builtin::BI_exception_info:
1288     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1289                                  diag::err_seh___except_filter))
1290       return ExprError();
1291     break;
1292   case Builtin::BI__GetExceptionInfo:
1293     if (checkArgCount(*this, TheCall, 1))
1294       return ExprError();
1295 
1296     if (CheckCXXThrowOperand(
1297             TheCall->getBeginLoc(),
1298             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1299             TheCall))
1300       return ExprError();
1301 
1302     TheCall->setType(Context.VoidPtrTy);
1303     break;
1304   // OpenCL v2.0, s6.13.16 - Pipe functions
1305   case Builtin::BIread_pipe:
1306   case Builtin::BIwrite_pipe:
1307     // Since those two functions are declared with var args, we need a semantic
1308     // check for the argument.
1309     if (SemaBuiltinRWPipe(*this, TheCall))
1310       return ExprError();
1311     TheCall->setType(Context.IntTy);
1312     break;
1313   case Builtin::BIreserve_read_pipe:
1314   case Builtin::BIreserve_write_pipe:
1315   case Builtin::BIwork_group_reserve_read_pipe:
1316   case Builtin::BIwork_group_reserve_write_pipe:
1317     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1318       return ExprError();
1319     break;
1320   case Builtin::BIsub_group_reserve_read_pipe:
1321   case Builtin::BIsub_group_reserve_write_pipe:
1322     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1323         SemaBuiltinReserveRWPipe(*this, TheCall))
1324       return ExprError();
1325     break;
1326   case Builtin::BIcommit_read_pipe:
1327   case Builtin::BIcommit_write_pipe:
1328   case Builtin::BIwork_group_commit_read_pipe:
1329   case Builtin::BIwork_group_commit_write_pipe:
1330     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1331       return ExprError();
1332     break;
1333   case Builtin::BIsub_group_commit_read_pipe:
1334   case Builtin::BIsub_group_commit_write_pipe:
1335     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1336         SemaBuiltinCommitRWPipe(*this, TheCall))
1337       return ExprError();
1338     break;
1339   case Builtin::BIget_pipe_num_packets:
1340   case Builtin::BIget_pipe_max_packets:
1341     if (SemaBuiltinPipePackets(*this, TheCall))
1342       return ExprError();
1343     TheCall->setType(Context.UnsignedIntTy);
1344     break;
1345   case Builtin::BIto_global:
1346   case Builtin::BIto_local:
1347   case Builtin::BIto_private:
1348     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1349       return ExprError();
1350     break;
1351   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1352   case Builtin::BIenqueue_kernel:
1353     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1354       return ExprError();
1355     break;
1356   case Builtin::BIget_kernel_work_group_size:
1357   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1358     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1359       return ExprError();
1360     break;
1361   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1362   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1363     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1364       return ExprError();
1365     break;
1366   case Builtin::BI__builtin_os_log_format:
1367   case Builtin::BI__builtin_os_log_format_buffer_size:
1368     if (SemaBuiltinOSLogFormat(TheCall))
1369       return ExprError();
1370     break;
1371   }
1372 
1373   // Since the target specific builtins for each arch overlap, only check those
1374   // of the arch we are compiling for.
1375   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1376     switch (Context.getTargetInfo().getTriple().getArch()) {
1377       case llvm::Triple::arm:
1378       case llvm::Triple::armeb:
1379       case llvm::Triple::thumb:
1380       case llvm::Triple::thumbeb:
1381         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1382           return ExprError();
1383         break;
1384       case llvm::Triple::aarch64:
1385       case llvm::Triple::aarch64_be:
1386         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1387           return ExprError();
1388         break;
1389       case llvm::Triple::hexagon:
1390         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1391           return ExprError();
1392         break;
1393       case llvm::Triple::mips:
1394       case llvm::Triple::mipsel:
1395       case llvm::Triple::mips64:
1396       case llvm::Triple::mips64el:
1397         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1398           return ExprError();
1399         break;
1400       case llvm::Triple::systemz:
1401         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1402           return ExprError();
1403         break;
1404       case llvm::Triple::x86:
1405       case llvm::Triple::x86_64:
1406         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1407           return ExprError();
1408         break;
1409       case llvm::Triple::ppc:
1410       case llvm::Triple::ppc64:
1411       case llvm::Triple::ppc64le:
1412         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1413           return ExprError();
1414         break;
1415       default:
1416         break;
1417     }
1418   }
1419 
1420   return TheCallResult;
1421 }
1422 
1423 // Get the valid immediate range for the specified NEON type code.
1424 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1425   NeonTypeFlags Type(t);
1426   int IsQuad = ForceQuad ? true : Type.isQuad();
1427   switch (Type.getEltType()) {
1428   case NeonTypeFlags::Int8:
1429   case NeonTypeFlags::Poly8:
1430     return shift ? 7 : (8 << IsQuad) - 1;
1431   case NeonTypeFlags::Int16:
1432   case NeonTypeFlags::Poly16:
1433     return shift ? 15 : (4 << IsQuad) - 1;
1434   case NeonTypeFlags::Int32:
1435     return shift ? 31 : (2 << IsQuad) - 1;
1436   case NeonTypeFlags::Int64:
1437   case NeonTypeFlags::Poly64:
1438     return shift ? 63 : (1 << IsQuad) - 1;
1439   case NeonTypeFlags::Poly128:
1440     return shift ? 127 : (1 << IsQuad) - 1;
1441   case NeonTypeFlags::Float16:
1442     assert(!shift && "cannot shift float types!");
1443     return (4 << IsQuad) - 1;
1444   case NeonTypeFlags::Float32:
1445     assert(!shift && "cannot shift float types!");
1446     return (2 << IsQuad) - 1;
1447   case NeonTypeFlags::Float64:
1448     assert(!shift && "cannot shift float types!");
1449     return (1 << IsQuad) - 1;
1450   }
1451   llvm_unreachable("Invalid NeonTypeFlag!");
1452 }
1453 
1454 /// getNeonEltType - Return the QualType corresponding to the elements of
1455 /// the vector type specified by the NeonTypeFlags.  This is used to check
1456 /// the pointer arguments for Neon load/store intrinsics.
1457 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1458                                bool IsPolyUnsigned, bool IsInt64Long) {
1459   switch (Flags.getEltType()) {
1460   case NeonTypeFlags::Int8:
1461     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1462   case NeonTypeFlags::Int16:
1463     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1464   case NeonTypeFlags::Int32:
1465     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1466   case NeonTypeFlags::Int64:
1467     if (IsInt64Long)
1468       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1469     else
1470       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1471                                 : Context.LongLongTy;
1472   case NeonTypeFlags::Poly8:
1473     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1474   case NeonTypeFlags::Poly16:
1475     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1476   case NeonTypeFlags::Poly64:
1477     if (IsInt64Long)
1478       return Context.UnsignedLongTy;
1479     else
1480       return Context.UnsignedLongLongTy;
1481   case NeonTypeFlags::Poly128:
1482     break;
1483   case NeonTypeFlags::Float16:
1484     return Context.HalfTy;
1485   case NeonTypeFlags::Float32:
1486     return Context.FloatTy;
1487   case NeonTypeFlags::Float64:
1488     return Context.DoubleTy;
1489   }
1490   llvm_unreachable("Invalid NeonTypeFlag!");
1491 }
1492 
1493 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1494   llvm::APSInt Result;
1495   uint64_t mask = 0;
1496   unsigned TV = 0;
1497   int PtrArgNum = -1;
1498   bool HasConstPtr = false;
1499   switch (BuiltinID) {
1500 #define GET_NEON_OVERLOAD_CHECK
1501 #include "clang/Basic/arm_neon.inc"
1502 #include "clang/Basic/arm_fp16.inc"
1503 #undef GET_NEON_OVERLOAD_CHECK
1504   }
1505 
1506   // For NEON intrinsics which are overloaded on vector element type, validate
1507   // the immediate which specifies which variant to emit.
1508   unsigned ImmArg = TheCall->getNumArgs()-1;
1509   if (mask) {
1510     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1511       return true;
1512 
1513     TV = Result.getLimitedValue(64);
1514     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1515       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1516              << TheCall->getArg(ImmArg)->getSourceRange();
1517   }
1518 
1519   if (PtrArgNum >= 0) {
1520     // Check that pointer arguments have the specified type.
1521     Expr *Arg = TheCall->getArg(PtrArgNum);
1522     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1523       Arg = ICE->getSubExpr();
1524     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1525     QualType RHSTy = RHS.get()->getType();
1526 
1527     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1528     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1529                           Arch == llvm::Triple::aarch64_be;
1530     bool IsInt64Long =
1531         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1532     QualType EltTy =
1533         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1534     if (HasConstPtr)
1535       EltTy = EltTy.withConst();
1536     QualType LHSTy = Context.getPointerType(EltTy);
1537     AssignConvertType ConvTy;
1538     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1539     if (RHS.isInvalid())
1540       return true;
1541     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1542                                  RHS.get(), AA_Assigning))
1543       return true;
1544   }
1545 
1546   // For NEON intrinsics which take an immediate value as part of the
1547   // instruction, range check them here.
1548   unsigned i = 0, l = 0, u = 0;
1549   switch (BuiltinID) {
1550   default:
1551     return false;
1552   #define GET_NEON_IMMEDIATE_CHECK
1553   #include "clang/Basic/arm_neon.inc"
1554   #include "clang/Basic/arm_fp16.inc"
1555   #undef GET_NEON_IMMEDIATE_CHECK
1556   }
1557 
1558   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1559 }
1560 
1561 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1562                                         unsigned MaxWidth) {
1563   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1564           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1565           BuiltinID == ARM::BI__builtin_arm_strex ||
1566           BuiltinID == ARM::BI__builtin_arm_stlex ||
1567           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1568           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1569           BuiltinID == AArch64::BI__builtin_arm_strex ||
1570           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1571          "unexpected ARM builtin");
1572   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1573                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1574                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1575                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1576 
1577   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1578 
1579   // Ensure that we have the proper number of arguments.
1580   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1581     return true;
1582 
1583   // Inspect the pointer argument of the atomic builtin.  This should always be
1584   // a pointer type, whose element is an integral scalar or pointer type.
1585   // Because it is a pointer type, we don't have to worry about any implicit
1586   // casts here.
1587   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1588   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1589   if (PointerArgRes.isInvalid())
1590     return true;
1591   PointerArg = PointerArgRes.get();
1592 
1593   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1594   if (!pointerType) {
1595     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1596         << PointerArg->getType() << PointerArg->getSourceRange();
1597     return true;
1598   }
1599 
1600   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1601   // task is to insert the appropriate casts into the AST. First work out just
1602   // what the appropriate type is.
1603   QualType ValType = pointerType->getPointeeType();
1604   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1605   if (IsLdrex)
1606     AddrType.addConst();
1607 
1608   // Issue a warning if the cast is dodgy.
1609   CastKind CastNeeded = CK_NoOp;
1610   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1611     CastNeeded = CK_BitCast;
1612     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1613         << PointerArg->getType() << Context.getPointerType(AddrType)
1614         << AA_Passing << PointerArg->getSourceRange();
1615   }
1616 
1617   // Finally, do the cast and replace the argument with the corrected version.
1618   AddrType = Context.getPointerType(AddrType);
1619   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1620   if (PointerArgRes.isInvalid())
1621     return true;
1622   PointerArg = PointerArgRes.get();
1623 
1624   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1625 
1626   // In general, we allow ints, floats and pointers to be loaded and stored.
1627   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1628       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1629     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1630         << PointerArg->getType() << PointerArg->getSourceRange();
1631     return true;
1632   }
1633 
1634   // But ARM doesn't have instructions to deal with 128-bit versions.
1635   if (Context.getTypeSize(ValType) > MaxWidth) {
1636     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1637     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1638         << PointerArg->getType() << PointerArg->getSourceRange();
1639     return true;
1640   }
1641 
1642   switch (ValType.getObjCLifetime()) {
1643   case Qualifiers::OCL_None:
1644   case Qualifiers::OCL_ExplicitNone:
1645     // okay
1646     break;
1647 
1648   case Qualifiers::OCL_Weak:
1649   case Qualifiers::OCL_Strong:
1650   case Qualifiers::OCL_Autoreleasing:
1651     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1652         << ValType << PointerArg->getSourceRange();
1653     return true;
1654   }
1655 
1656   if (IsLdrex) {
1657     TheCall->setType(ValType);
1658     return false;
1659   }
1660 
1661   // Initialize the argument to be stored.
1662   ExprResult ValArg = TheCall->getArg(0);
1663   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1664       Context, ValType, /*consume*/ false);
1665   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1666   if (ValArg.isInvalid())
1667     return true;
1668   TheCall->setArg(0, ValArg.get());
1669 
1670   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1671   // but the custom checker bypasses all default analysis.
1672   TheCall->setType(Context.IntTy);
1673   return false;
1674 }
1675 
1676 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1677   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1678       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1679       BuiltinID == ARM::BI__builtin_arm_strex ||
1680       BuiltinID == ARM::BI__builtin_arm_stlex) {
1681     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1682   }
1683 
1684   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1685     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1686       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1687   }
1688 
1689   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1690       BuiltinID == ARM::BI__builtin_arm_wsr64)
1691     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1692 
1693   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1694       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1695       BuiltinID == ARM::BI__builtin_arm_wsr ||
1696       BuiltinID == ARM::BI__builtin_arm_wsrp)
1697     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1698 
1699   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1700     return true;
1701 
1702   // For intrinsics which take an immediate value as part of the instruction,
1703   // range check them here.
1704   // FIXME: VFP Intrinsics should error if VFP not present.
1705   switch (BuiltinID) {
1706   default: return false;
1707   case ARM::BI__builtin_arm_ssat:
1708     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1709   case ARM::BI__builtin_arm_usat:
1710     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1711   case ARM::BI__builtin_arm_ssat16:
1712     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1713   case ARM::BI__builtin_arm_usat16:
1714     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1715   case ARM::BI__builtin_arm_vcvtr_f:
1716   case ARM::BI__builtin_arm_vcvtr_d:
1717     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1718   case ARM::BI__builtin_arm_dmb:
1719   case ARM::BI__builtin_arm_dsb:
1720   case ARM::BI__builtin_arm_isb:
1721   case ARM::BI__builtin_arm_dbg:
1722     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1723   }
1724 }
1725 
1726 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1727                                          CallExpr *TheCall) {
1728   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1729       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1730       BuiltinID == AArch64::BI__builtin_arm_strex ||
1731       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1732     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1733   }
1734 
1735   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1736     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1737       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1738       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1739       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1740   }
1741 
1742   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1743       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1744     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1745 
1746   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1747       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1748       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1749       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1750     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1751 
1752   // Only check the valid encoding range. Any constant in this range would be
1753   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1754   // an exception for incorrect registers. This matches MSVC behavior.
1755   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1756       BuiltinID == AArch64::BI_WriteStatusReg)
1757     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1758 
1759   if (BuiltinID == AArch64::BI__getReg)
1760     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
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   unsigned i = 0, l = 0, u = 0;
1768   switch (BuiltinID) {
1769   default: return false;
1770   case AArch64::BI__builtin_arm_dmb:
1771   case AArch64::BI__builtin_arm_dsb:
1772   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1773   }
1774 
1775   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1776 }
1777 
1778 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1779   struct BuiltinAndString {
1780     unsigned BuiltinID;
1781     const char *Str;
1782   };
1783 
1784   static BuiltinAndString ValidCPU[] = {
1785     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65" },
1786     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65" },
1787     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65" },
1788     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65" },
1789     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65" },
1790     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65" },
1791     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65" },
1792     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65" },
1793     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65" },
1794     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65" },
1795     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65" },
1796     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65" },
1797     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65" },
1798     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65" },
1799     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65" },
1800     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65" },
1801     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65" },
1802     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65" },
1803     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65" },
1804   };
1805 
1806   static BuiltinAndString ValidHVX[] = {
1807     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65" },
1808     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65" },
1809     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65" },
1810     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65" },
1811     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65" },
1812     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65" },
1813     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65" },
1814     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65" },
1815     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65" },
1816     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65" },
1817     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65" },
1818     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65" },
1819     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65" },
1820     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65" },
1821     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65" },
1822     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65" },
1823     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65" },
1824     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65" },
1825     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65" },
1826     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65" },
1827     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65" },
1828     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65" },
1829     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65" },
1830     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65" },
1831     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65" },
1832     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65" },
1833     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65" },
1834     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65" },
1835     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65" },
1836     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65" },
1837     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65" },
1838     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65" },
1839     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65" },
1840     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65" },
1841     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65" },
1842     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65" },
1843     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65" },
1844     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65" },
1845     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65" },
1846     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65" },
1847     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65" },
1848     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65" },
1849     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65" },
1850     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65" },
1851     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65" },
1852     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65" },
1853     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65" },
1854     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65" },
1855     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65" },
1856     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65" },
1857     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65" },
1858     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65" },
1859     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65" },
1860     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65" },
1861     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65" },
1862     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65" },
1863     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65" },
1864     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65" },
1865     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65" },
1866     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65" },
1867     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65" },
1868     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65" },
1869     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65" },
1870     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65" },
1871     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65" },
1872     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65" },
1873     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65" },
1874     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65" },
1875     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65" },
1876     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65" },
1877     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65" },
1878     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65" },
1879     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65" },
1880     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65" },
1881     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65" },
1882     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65" },
1883     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65" },
1884     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65" },
1885     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65" },
1886     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65" },
1887     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65" },
1888     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65" },
1889     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65" },
1890     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65" },
1891     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65" },
1892     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65" },
1893     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65" },
1894     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65" },
1895     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65" },
1896     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65" },
1897     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65" },
1898     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65" },
1899     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65" },
1900     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65" },
1901     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65" },
1902     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65" },
1903     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65" },
1904     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65" },
1905     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65" },
1906     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65" },
1907     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65" },
1908     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65" },
1909     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65" },
1910     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65" },
1911     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65" },
1912     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65" },
1913     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65" },
1914     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65" },
1915     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65" },
1916     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65" },
1917     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65" },
1918     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65" },
1919     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65" },
1920     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65" },
1921     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65" },
1922     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65" },
1923     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65" },
1924     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65" },
1925     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65" },
1926     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65" },
1927     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65" },
1928     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65" },
1929     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65" },
1930     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65" },
1931     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65" },
1932     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65" },
1933     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65" },
1934     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65" },
1935     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65" },
1936     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65" },
1937     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65" },
1938     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65" },
1939     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65" },
1940     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65" },
1941     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65" },
1942     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65" },
1943     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65" },
1944     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65" },
1945     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65" },
1946     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65" },
1947     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65" },
1948     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65" },
1949     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65" },
1950     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65" },
1951     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65" },
1952     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65" },
1953     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65" },
1954     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65" },
1955     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65" },
1956     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65" },
1957     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65" },
1958     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65" },
1959     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65" },
1960     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65" },
1961     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65" },
1962     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65" },
1963     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65" },
1964     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65" },
1965     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65" },
1966     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65" },
1967     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65" },
1968     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65" },
1969     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65" },
1970     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65" },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65" },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65" },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65" },
2531   };
2532 
2533   // Sort the tables on first execution so we can binary search them.
2534   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2535     return LHS.BuiltinID < RHS.BuiltinID;
2536   };
2537   static const bool SortOnce =
2538       (std::sort(std::begin(ValidCPU), std::end(ValidCPU), SortCmp),
2539        std::sort(std::begin(ValidHVX), std::end(ValidHVX), SortCmp), true);
2540   (void)SortOnce;
2541   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2542     return BI.BuiltinID < BuiltinID;
2543   };
2544 
2545   const TargetInfo &TI = Context.getTargetInfo();
2546 
2547   const BuiltinAndString *FC =
2548       std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2549                        LowerBoundCmp);
2550   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2551     const TargetOptions &Opts = TI.getTargetOpts();
2552     StringRef CPU = Opts.CPU;
2553     if (!CPU.empty()) {
2554       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2555       CPU.consume_front("hexagon");
2556       SmallVector<StringRef, 3> CPUs;
2557       StringRef(FC->Str).split(CPUs, ',');
2558       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2559         return Diag(TheCall->getBeginLoc(),
2560                     diag::err_hexagon_builtin_unsupported_cpu);
2561     }
2562   }
2563 
2564   const BuiltinAndString *FH =
2565       std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2566                        LowerBoundCmp);
2567   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2568     if (!TI.hasFeature("hvx"))
2569       return Diag(TheCall->getBeginLoc(),
2570                   diag::err_hexagon_builtin_requires_hvx);
2571 
2572     SmallVector<StringRef, 3> HVXs;
2573     StringRef(FH->Str).split(HVXs, ',');
2574     bool IsValid = llvm::any_of(HVXs,
2575                                 [&TI] (StringRef V) {
2576                                   std::string F = "hvx" + V.str();
2577                                   return TI.hasFeature(F);
2578                                 });
2579     if (!IsValid)
2580       return Diag(TheCall->getBeginLoc(),
2581                   diag::err_hexagon_builtin_unsupported_hvx);
2582   }
2583 
2584   return false;
2585 }
2586 
2587 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2588   struct ArgInfo {
2589     uint8_t OpNum;
2590     bool IsSigned;
2591     uint8_t BitWidth;
2592     uint8_t Align;
2593   };
2594   struct BuiltinInfo {
2595     unsigned BuiltinID;
2596     ArgInfo Infos[2];
2597   };
2598 
2599   static BuiltinInfo Infos[] = {
2600     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2601     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2602     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2603     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2604     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2605     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2606     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2607     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2608     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2609     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2610     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2611 
2612     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2615     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2616     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2617     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2618     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2620     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2622     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2623 
2624     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2629     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2638     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2643     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2646     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2647     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2649     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2653     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2654     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2655     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2657     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2659     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2676                                                       {{ 1, false, 6,  0 }} },
2677     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2679     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2680     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2682     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2683     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2684                                                       {{ 1, false, 5,  0 }} },
2685     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2686     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2691                                                        { 2, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2693                                                        { 2, false, 6,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2695                                                        { 3, false, 5,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2697                                                        { 3, false, 6,  0 }} },
2698     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2714                                                       {{ 2, false, 4,  0 },
2715                                                        { 3, false, 5,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2717                                                       {{ 2, false, 4,  0 },
2718                                                        { 3, false, 5,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2720                                                       {{ 2, false, 4,  0 },
2721                                                        { 3, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2723                                                       {{ 2, false, 4,  0 },
2724                                                        { 3, false, 5,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2736                                                        { 2, false, 5,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2738                                                        { 2, false, 6,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2743     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2744     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2746     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2748                                                       {{ 1, false, 4,  0 }} },
2749     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2751                                                       {{ 1, false, 4,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2772                                                       {{ 3, false, 1,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2777                                                       {{ 3, false, 1,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2782                                                       {{ 3, false, 1,  0 }} },
2783   };
2784 
2785   // Use a dynamically initialized static to sort the table exactly once on
2786   // first run.
2787   static const bool SortOnce =
2788       (std::sort(std::begin(Infos), std::end(Infos),
2789                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2790                    return LHS.BuiltinID < RHS.BuiltinID;
2791                  }),
2792        true);
2793   (void)SortOnce;
2794 
2795   const BuiltinInfo *F =
2796       std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2797                        [](const BuiltinInfo &BI, unsigned BuiltinID) {
2798                          return BI.BuiltinID < BuiltinID;
2799                        });
2800   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2801     return false;
2802 
2803   bool Error = false;
2804 
2805   for (const ArgInfo &A : F->Infos) {
2806     // Ignore empty ArgInfo elements.
2807     if (A.BitWidth == 0)
2808       continue;
2809 
2810     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2811     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2812     if (!A.Align) {
2813       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2814     } else {
2815       unsigned M = 1 << A.Align;
2816       Min *= M;
2817       Max *= M;
2818       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2819                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2820     }
2821   }
2822   return Error;
2823 }
2824 
2825 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2826                                            CallExpr *TheCall) {
2827   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2828          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2829 }
2830 
2831 
2832 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2833 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2834 // ordering for DSP is unspecified. MSA is ordered by the data format used
2835 // by the underlying instruction i.e., df/m, df/n and then by size.
2836 //
2837 // FIXME: The size tests here should instead be tablegen'd along with the
2838 //        definitions from include/clang/Basic/BuiltinsMips.def.
2839 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2840 //        be too.
2841 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2842   unsigned i = 0, l = 0, u = 0, m = 0;
2843   switch (BuiltinID) {
2844   default: return false;
2845   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2846   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2847   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2848   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2849   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2850   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2851   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2852   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
2853   // df/m field.
2854   // These intrinsics take an unsigned 3 bit immediate.
2855   case Mips::BI__builtin_msa_bclri_b:
2856   case Mips::BI__builtin_msa_bnegi_b:
2857   case Mips::BI__builtin_msa_bseti_b:
2858   case Mips::BI__builtin_msa_sat_s_b:
2859   case Mips::BI__builtin_msa_sat_u_b:
2860   case Mips::BI__builtin_msa_slli_b:
2861   case Mips::BI__builtin_msa_srai_b:
2862   case Mips::BI__builtin_msa_srari_b:
2863   case Mips::BI__builtin_msa_srli_b:
2864   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2865   case Mips::BI__builtin_msa_binsli_b:
2866   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2867   // These intrinsics take an unsigned 4 bit immediate.
2868   case Mips::BI__builtin_msa_bclri_h:
2869   case Mips::BI__builtin_msa_bnegi_h:
2870   case Mips::BI__builtin_msa_bseti_h:
2871   case Mips::BI__builtin_msa_sat_s_h:
2872   case Mips::BI__builtin_msa_sat_u_h:
2873   case Mips::BI__builtin_msa_slli_h:
2874   case Mips::BI__builtin_msa_srai_h:
2875   case Mips::BI__builtin_msa_srari_h:
2876   case Mips::BI__builtin_msa_srli_h:
2877   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2878   case Mips::BI__builtin_msa_binsli_h:
2879   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2880   // These intrinsics take an unsigned 5 bit immediate.
2881   // The first block of intrinsics actually have an unsigned 5 bit field,
2882   // not a df/n field.
2883   case Mips::BI__builtin_msa_clei_u_b:
2884   case Mips::BI__builtin_msa_clei_u_h:
2885   case Mips::BI__builtin_msa_clei_u_w:
2886   case Mips::BI__builtin_msa_clei_u_d:
2887   case Mips::BI__builtin_msa_clti_u_b:
2888   case Mips::BI__builtin_msa_clti_u_h:
2889   case Mips::BI__builtin_msa_clti_u_w:
2890   case Mips::BI__builtin_msa_clti_u_d:
2891   case Mips::BI__builtin_msa_maxi_u_b:
2892   case Mips::BI__builtin_msa_maxi_u_h:
2893   case Mips::BI__builtin_msa_maxi_u_w:
2894   case Mips::BI__builtin_msa_maxi_u_d:
2895   case Mips::BI__builtin_msa_mini_u_b:
2896   case Mips::BI__builtin_msa_mini_u_h:
2897   case Mips::BI__builtin_msa_mini_u_w:
2898   case Mips::BI__builtin_msa_mini_u_d:
2899   case Mips::BI__builtin_msa_addvi_b:
2900   case Mips::BI__builtin_msa_addvi_h:
2901   case Mips::BI__builtin_msa_addvi_w:
2902   case Mips::BI__builtin_msa_addvi_d:
2903   case Mips::BI__builtin_msa_bclri_w:
2904   case Mips::BI__builtin_msa_bnegi_w:
2905   case Mips::BI__builtin_msa_bseti_w:
2906   case Mips::BI__builtin_msa_sat_s_w:
2907   case Mips::BI__builtin_msa_sat_u_w:
2908   case Mips::BI__builtin_msa_slli_w:
2909   case Mips::BI__builtin_msa_srai_w:
2910   case Mips::BI__builtin_msa_srari_w:
2911   case Mips::BI__builtin_msa_srli_w:
2912   case Mips::BI__builtin_msa_srlri_w:
2913   case Mips::BI__builtin_msa_subvi_b:
2914   case Mips::BI__builtin_msa_subvi_h:
2915   case Mips::BI__builtin_msa_subvi_w:
2916   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2917   case Mips::BI__builtin_msa_binsli_w:
2918   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2919   // These intrinsics take an unsigned 6 bit immediate.
2920   case Mips::BI__builtin_msa_bclri_d:
2921   case Mips::BI__builtin_msa_bnegi_d:
2922   case Mips::BI__builtin_msa_bseti_d:
2923   case Mips::BI__builtin_msa_sat_s_d:
2924   case Mips::BI__builtin_msa_sat_u_d:
2925   case Mips::BI__builtin_msa_slli_d:
2926   case Mips::BI__builtin_msa_srai_d:
2927   case Mips::BI__builtin_msa_srari_d:
2928   case Mips::BI__builtin_msa_srli_d:
2929   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2930   case Mips::BI__builtin_msa_binsli_d:
2931   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2932   // These intrinsics take a signed 5 bit immediate.
2933   case Mips::BI__builtin_msa_ceqi_b:
2934   case Mips::BI__builtin_msa_ceqi_h:
2935   case Mips::BI__builtin_msa_ceqi_w:
2936   case Mips::BI__builtin_msa_ceqi_d:
2937   case Mips::BI__builtin_msa_clti_s_b:
2938   case Mips::BI__builtin_msa_clti_s_h:
2939   case Mips::BI__builtin_msa_clti_s_w:
2940   case Mips::BI__builtin_msa_clti_s_d:
2941   case Mips::BI__builtin_msa_clei_s_b:
2942   case Mips::BI__builtin_msa_clei_s_h:
2943   case Mips::BI__builtin_msa_clei_s_w:
2944   case Mips::BI__builtin_msa_clei_s_d:
2945   case Mips::BI__builtin_msa_maxi_s_b:
2946   case Mips::BI__builtin_msa_maxi_s_h:
2947   case Mips::BI__builtin_msa_maxi_s_w:
2948   case Mips::BI__builtin_msa_maxi_s_d:
2949   case Mips::BI__builtin_msa_mini_s_b:
2950   case Mips::BI__builtin_msa_mini_s_h:
2951   case Mips::BI__builtin_msa_mini_s_w:
2952   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2953   // These intrinsics take an unsigned 8 bit immediate.
2954   case Mips::BI__builtin_msa_andi_b:
2955   case Mips::BI__builtin_msa_nori_b:
2956   case Mips::BI__builtin_msa_ori_b:
2957   case Mips::BI__builtin_msa_shf_b:
2958   case Mips::BI__builtin_msa_shf_h:
2959   case Mips::BI__builtin_msa_shf_w:
2960   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2961   case Mips::BI__builtin_msa_bseli_b:
2962   case Mips::BI__builtin_msa_bmnzi_b:
2963   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2964   // df/n format
2965   // These intrinsics take an unsigned 4 bit immediate.
2966   case Mips::BI__builtin_msa_copy_s_b:
2967   case Mips::BI__builtin_msa_copy_u_b:
2968   case Mips::BI__builtin_msa_insve_b:
2969   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2970   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2971   // These intrinsics take an unsigned 3 bit immediate.
2972   case Mips::BI__builtin_msa_copy_s_h:
2973   case Mips::BI__builtin_msa_copy_u_h:
2974   case Mips::BI__builtin_msa_insve_h:
2975   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2976   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2977   // These intrinsics take an unsigned 2 bit immediate.
2978   case Mips::BI__builtin_msa_copy_s_w:
2979   case Mips::BI__builtin_msa_copy_u_w:
2980   case Mips::BI__builtin_msa_insve_w:
2981   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2982   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2983   // These intrinsics take an unsigned 1 bit immediate.
2984   case Mips::BI__builtin_msa_copy_s_d:
2985   case Mips::BI__builtin_msa_copy_u_d:
2986   case Mips::BI__builtin_msa_insve_d:
2987   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2988   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2989   // Memory offsets and immediate loads.
2990   // These intrinsics take a signed 10 bit immediate.
2991   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2992   case Mips::BI__builtin_msa_ldi_h:
2993   case Mips::BI__builtin_msa_ldi_w:
2994   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2995   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2996   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2997   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2998   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2999   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
3000   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
3001   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
3002   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
3003   }
3004 
3005   if (!m)
3006     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3007 
3008   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3009          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3010 }
3011 
3012 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3013   unsigned i = 0, l = 0, u = 0;
3014   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3015                       BuiltinID == PPC::BI__builtin_divdeu ||
3016                       BuiltinID == PPC::BI__builtin_bpermd;
3017   bool IsTarget64Bit = Context.getTargetInfo()
3018                               .getTypeWidth(Context
3019                                             .getTargetInfo()
3020                                             .getIntPtrType()) == 64;
3021   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3022                        BuiltinID == PPC::BI__builtin_divweu ||
3023                        BuiltinID == PPC::BI__builtin_divde ||
3024                        BuiltinID == PPC::BI__builtin_divdeu;
3025 
3026   if (Is64BitBltin && !IsTarget64Bit)
3027     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3028            << TheCall->getSourceRange();
3029 
3030   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3031       (BuiltinID == PPC::BI__builtin_bpermd &&
3032        !Context.getTargetInfo().hasFeature("bpermd")))
3033     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3034            << TheCall->getSourceRange();
3035 
3036   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3037     if (!Context.getTargetInfo().hasFeature("vsx"))
3038       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3039              << TheCall->getSourceRange();
3040     return false;
3041   };
3042 
3043   switch (BuiltinID) {
3044   default: return false;
3045   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3046   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3047     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3048            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3049   case PPC::BI__builtin_tbegin:
3050   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3051   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3052   case PPC::BI__builtin_tabortwc:
3053   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3054   case PPC::BI__builtin_tabortwci:
3055   case PPC::BI__builtin_tabortdci:
3056     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3057            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3058   case PPC::BI__builtin_vsx_xxpermdi:
3059   case PPC::BI__builtin_vsx_xxsldwi:
3060     return SemaBuiltinVSX(TheCall);
3061   case PPC::BI__builtin_unpack_vector_int128:
3062     return SemaVSXCheck(TheCall) ||
3063            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3064   case PPC::BI__builtin_pack_vector_int128:
3065     return SemaVSXCheck(TheCall);
3066   }
3067   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3068 }
3069 
3070 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3071                                            CallExpr *TheCall) {
3072   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3073     Expr *Arg = TheCall->getArg(0);
3074     llvm::APSInt AbortCode(32);
3075     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3076         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3077       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3078              << Arg->getSourceRange();
3079   }
3080 
3081   // For intrinsics which take an immediate value as part of the instruction,
3082   // range check them here.
3083   unsigned i = 0, l = 0, u = 0;
3084   switch (BuiltinID) {
3085   default: return false;
3086   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3087   case SystemZ::BI__builtin_s390_verimb:
3088   case SystemZ::BI__builtin_s390_verimh:
3089   case SystemZ::BI__builtin_s390_verimf:
3090   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3091   case SystemZ::BI__builtin_s390_vfaeb:
3092   case SystemZ::BI__builtin_s390_vfaeh:
3093   case SystemZ::BI__builtin_s390_vfaef:
3094   case SystemZ::BI__builtin_s390_vfaebs:
3095   case SystemZ::BI__builtin_s390_vfaehs:
3096   case SystemZ::BI__builtin_s390_vfaefs:
3097   case SystemZ::BI__builtin_s390_vfaezb:
3098   case SystemZ::BI__builtin_s390_vfaezh:
3099   case SystemZ::BI__builtin_s390_vfaezf:
3100   case SystemZ::BI__builtin_s390_vfaezbs:
3101   case SystemZ::BI__builtin_s390_vfaezhs:
3102   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3103   case SystemZ::BI__builtin_s390_vfisb:
3104   case SystemZ::BI__builtin_s390_vfidb:
3105     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3106            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3107   case SystemZ::BI__builtin_s390_vftcisb:
3108   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3109   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3110   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3111   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3112   case SystemZ::BI__builtin_s390_vstrcb:
3113   case SystemZ::BI__builtin_s390_vstrch:
3114   case SystemZ::BI__builtin_s390_vstrcf:
3115   case SystemZ::BI__builtin_s390_vstrczb:
3116   case SystemZ::BI__builtin_s390_vstrczh:
3117   case SystemZ::BI__builtin_s390_vstrczf:
3118   case SystemZ::BI__builtin_s390_vstrcbs:
3119   case SystemZ::BI__builtin_s390_vstrchs:
3120   case SystemZ::BI__builtin_s390_vstrcfs:
3121   case SystemZ::BI__builtin_s390_vstrczbs:
3122   case SystemZ::BI__builtin_s390_vstrczhs:
3123   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3124   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3125   case SystemZ::BI__builtin_s390_vfminsb:
3126   case SystemZ::BI__builtin_s390_vfmaxsb:
3127   case SystemZ::BI__builtin_s390_vfmindb:
3128   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3129   }
3130   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3131 }
3132 
3133 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3134 /// This checks that the target supports __builtin_cpu_supports and
3135 /// that the string argument is constant and valid.
3136 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3137   Expr *Arg = TheCall->getArg(0);
3138 
3139   // Check if the argument is a string literal.
3140   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3141     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3142            << Arg->getSourceRange();
3143 
3144   // Check the contents of the string.
3145   StringRef Feature =
3146       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3147   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3148     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3149            << Arg->getSourceRange();
3150   return false;
3151 }
3152 
3153 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3154 /// This checks that the target supports __builtin_cpu_is and
3155 /// that the string argument is constant and valid.
3156 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3157   Expr *Arg = TheCall->getArg(0);
3158 
3159   // Check if the argument is a string literal.
3160   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3161     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3162            << Arg->getSourceRange();
3163 
3164   // Check the contents of the string.
3165   StringRef Feature =
3166       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3167   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3168     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3169            << Arg->getSourceRange();
3170   return false;
3171 }
3172 
3173 // Check if the rounding mode is legal.
3174 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3175   // Indicates if this instruction has rounding control or just SAE.
3176   bool HasRC = false;
3177 
3178   unsigned ArgNum = 0;
3179   switch (BuiltinID) {
3180   default:
3181     return false;
3182   case X86::BI__builtin_ia32_vcvttsd2si32:
3183   case X86::BI__builtin_ia32_vcvttsd2si64:
3184   case X86::BI__builtin_ia32_vcvttsd2usi32:
3185   case X86::BI__builtin_ia32_vcvttsd2usi64:
3186   case X86::BI__builtin_ia32_vcvttss2si32:
3187   case X86::BI__builtin_ia32_vcvttss2si64:
3188   case X86::BI__builtin_ia32_vcvttss2usi32:
3189   case X86::BI__builtin_ia32_vcvttss2usi64:
3190     ArgNum = 1;
3191     break;
3192   case X86::BI__builtin_ia32_maxpd512:
3193   case X86::BI__builtin_ia32_maxps512:
3194   case X86::BI__builtin_ia32_minpd512:
3195   case X86::BI__builtin_ia32_minps512:
3196     ArgNum = 2;
3197     break;
3198   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3199   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3200   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3201   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3202   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3203   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3204   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3205   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3206   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3207   case X86::BI__builtin_ia32_exp2pd_mask:
3208   case X86::BI__builtin_ia32_exp2ps_mask:
3209   case X86::BI__builtin_ia32_getexppd512_mask:
3210   case X86::BI__builtin_ia32_getexpps512_mask:
3211   case X86::BI__builtin_ia32_rcp28pd_mask:
3212   case X86::BI__builtin_ia32_rcp28ps_mask:
3213   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3214   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3215   case X86::BI__builtin_ia32_vcomisd:
3216   case X86::BI__builtin_ia32_vcomiss:
3217   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3218     ArgNum = 3;
3219     break;
3220   case X86::BI__builtin_ia32_cmppd512_mask:
3221   case X86::BI__builtin_ia32_cmpps512_mask:
3222   case X86::BI__builtin_ia32_cmpsd_mask:
3223   case X86::BI__builtin_ia32_cmpss_mask:
3224   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3225   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3226   case X86::BI__builtin_ia32_getexpss128_round_mask:
3227   case X86::BI__builtin_ia32_maxsd_round_mask:
3228   case X86::BI__builtin_ia32_maxss_round_mask:
3229   case X86::BI__builtin_ia32_minsd_round_mask:
3230   case X86::BI__builtin_ia32_minss_round_mask:
3231   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3232   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3233   case X86::BI__builtin_ia32_reducepd512_mask:
3234   case X86::BI__builtin_ia32_reduceps512_mask:
3235   case X86::BI__builtin_ia32_rndscalepd_mask:
3236   case X86::BI__builtin_ia32_rndscaleps_mask:
3237   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3238   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3239     ArgNum = 4;
3240     break;
3241   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3242   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3243   case X86::BI__builtin_ia32_fixupimmps512_mask:
3244   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3245   case X86::BI__builtin_ia32_fixupimmsd_mask:
3246   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3247   case X86::BI__builtin_ia32_fixupimmss_mask:
3248   case X86::BI__builtin_ia32_fixupimmss_maskz:
3249   case X86::BI__builtin_ia32_rangepd512_mask:
3250   case X86::BI__builtin_ia32_rangeps512_mask:
3251   case X86::BI__builtin_ia32_rangesd128_round_mask:
3252   case X86::BI__builtin_ia32_rangess128_round_mask:
3253   case X86::BI__builtin_ia32_reducesd_mask:
3254   case X86::BI__builtin_ia32_reducess_mask:
3255   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3256   case X86::BI__builtin_ia32_rndscaless_round_mask:
3257     ArgNum = 5;
3258     break;
3259   case X86::BI__builtin_ia32_vcvtsd2si64:
3260   case X86::BI__builtin_ia32_vcvtsd2si32:
3261   case X86::BI__builtin_ia32_vcvtsd2usi32:
3262   case X86::BI__builtin_ia32_vcvtsd2usi64:
3263   case X86::BI__builtin_ia32_vcvtss2si32:
3264   case X86::BI__builtin_ia32_vcvtss2si64:
3265   case X86::BI__builtin_ia32_vcvtss2usi32:
3266   case X86::BI__builtin_ia32_vcvtss2usi64:
3267   case X86::BI__builtin_ia32_sqrtpd512:
3268   case X86::BI__builtin_ia32_sqrtps512:
3269     ArgNum = 1;
3270     HasRC = true;
3271     break;
3272   case X86::BI__builtin_ia32_addpd512:
3273   case X86::BI__builtin_ia32_addps512:
3274   case X86::BI__builtin_ia32_divpd512:
3275   case X86::BI__builtin_ia32_divps512:
3276   case X86::BI__builtin_ia32_mulpd512:
3277   case X86::BI__builtin_ia32_mulps512:
3278   case X86::BI__builtin_ia32_subpd512:
3279   case X86::BI__builtin_ia32_subps512:
3280   case X86::BI__builtin_ia32_cvtsi2sd64:
3281   case X86::BI__builtin_ia32_cvtsi2ss32:
3282   case X86::BI__builtin_ia32_cvtsi2ss64:
3283   case X86::BI__builtin_ia32_cvtusi2sd64:
3284   case X86::BI__builtin_ia32_cvtusi2ss32:
3285   case X86::BI__builtin_ia32_cvtusi2ss64:
3286     ArgNum = 2;
3287     HasRC = true;
3288     break;
3289   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3290   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3291   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3292   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3293   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3294   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3295   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3296   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3297   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3298   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3299   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3300     ArgNum = 3;
3301     HasRC = true;
3302     break;
3303   case X86::BI__builtin_ia32_addss_round_mask:
3304   case X86::BI__builtin_ia32_addsd_round_mask:
3305   case X86::BI__builtin_ia32_divss_round_mask:
3306   case X86::BI__builtin_ia32_divsd_round_mask:
3307   case X86::BI__builtin_ia32_mulss_round_mask:
3308   case X86::BI__builtin_ia32_mulsd_round_mask:
3309   case X86::BI__builtin_ia32_subss_round_mask:
3310   case X86::BI__builtin_ia32_subsd_round_mask:
3311   case X86::BI__builtin_ia32_scalefpd512_mask:
3312   case X86::BI__builtin_ia32_scalefps512_mask:
3313   case X86::BI__builtin_ia32_scalefsd_round_mask:
3314   case X86::BI__builtin_ia32_scalefss_round_mask:
3315   case X86::BI__builtin_ia32_getmantpd512_mask:
3316   case X86::BI__builtin_ia32_getmantps512_mask:
3317   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3318   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3319   case X86::BI__builtin_ia32_sqrtss_round_mask:
3320   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3321   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3322   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3323   case X86::BI__builtin_ia32_vfmaddss3_mask:
3324   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3325   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3326   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3327   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3328   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3329   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3330   case X86::BI__builtin_ia32_vfmaddps512_mask:
3331   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3332   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3333   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3334   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3335   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3336   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3337   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3338   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3339   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3340   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3341   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3342     ArgNum = 4;
3343     HasRC = true;
3344     break;
3345   case X86::BI__builtin_ia32_getmantsd_round_mask:
3346   case X86::BI__builtin_ia32_getmantss_round_mask:
3347     ArgNum = 5;
3348     HasRC = true;
3349     break;
3350   }
3351 
3352   llvm::APSInt Result;
3353 
3354   // We can't check the value of a dependent argument.
3355   Expr *Arg = TheCall->getArg(ArgNum);
3356   if (Arg->isTypeDependent() || Arg->isValueDependent())
3357     return false;
3358 
3359   // Check constant-ness first.
3360   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3361     return true;
3362 
3363   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3364   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3365   // combined with ROUND_NO_EXC.
3366   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3367       Result == 8/*ROUND_NO_EXC*/ ||
3368       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3369     return false;
3370 
3371   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3372          << Arg->getSourceRange();
3373 }
3374 
3375 // Check if the gather/scatter scale is legal.
3376 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3377                                              CallExpr *TheCall) {
3378   unsigned ArgNum = 0;
3379   switch (BuiltinID) {
3380   default:
3381     return false;
3382   case X86::BI__builtin_ia32_gatherpfdpd:
3383   case X86::BI__builtin_ia32_gatherpfdps:
3384   case X86::BI__builtin_ia32_gatherpfqpd:
3385   case X86::BI__builtin_ia32_gatherpfqps:
3386   case X86::BI__builtin_ia32_scatterpfdpd:
3387   case X86::BI__builtin_ia32_scatterpfdps:
3388   case X86::BI__builtin_ia32_scatterpfqpd:
3389   case X86::BI__builtin_ia32_scatterpfqps:
3390     ArgNum = 3;
3391     break;
3392   case X86::BI__builtin_ia32_gatherd_pd:
3393   case X86::BI__builtin_ia32_gatherd_pd256:
3394   case X86::BI__builtin_ia32_gatherq_pd:
3395   case X86::BI__builtin_ia32_gatherq_pd256:
3396   case X86::BI__builtin_ia32_gatherd_ps:
3397   case X86::BI__builtin_ia32_gatherd_ps256:
3398   case X86::BI__builtin_ia32_gatherq_ps:
3399   case X86::BI__builtin_ia32_gatherq_ps256:
3400   case X86::BI__builtin_ia32_gatherd_q:
3401   case X86::BI__builtin_ia32_gatherd_q256:
3402   case X86::BI__builtin_ia32_gatherq_q:
3403   case X86::BI__builtin_ia32_gatherq_q256:
3404   case X86::BI__builtin_ia32_gatherd_d:
3405   case X86::BI__builtin_ia32_gatherd_d256:
3406   case X86::BI__builtin_ia32_gatherq_d:
3407   case X86::BI__builtin_ia32_gatherq_d256:
3408   case X86::BI__builtin_ia32_gather3div2df:
3409   case X86::BI__builtin_ia32_gather3div2di:
3410   case X86::BI__builtin_ia32_gather3div4df:
3411   case X86::BI__builtin_ia32_gather3div4di:
3412   case X86::BI__builtin_ia32_gather3div4sf:
3413   case X86::BI__builtin_ia32_gather3div4si:
3414   case X86::BI__builtin_ia32_gather3div8sf:
3415   case X86::BI__builtin_ia32_gather3div8si:
3416   case X86::BI__builtin_ia32_gather3siv2df:
3417   case X86::BI__builtin_ia32_gather3siv2di:
3418   case X86::BI__builtin_ia32_gather3siv4df:
3419   case X86::BI__builtin_ia32_gather3siv4di:
3420   case X86::BI__builtin_ia32_gather3siv4sf:
3421   case X86::BI__builtin_ia32_gather3siv4si:
3422   case X86::BI__builtin_ia32_gather3siv8sf:
3423   case X86::BI__builtin_ia32_gather3siv8si:
3424   case X86::BI__builtin_ia32_gathersiv8df:
3425   case X86::BI__builtin_ia32_gathersiv16sf:
3426   case X86::BI__builtin_ia32_gatherdiv8df:
3427   case X86::BI__builtin_ia32_gatherdiv16sf:
3428   case X86::BI__builtin_ia32_gathersiv8di:
3429   case X86::BI__builtin_ia32_gathersiv16si:
3430   case X86::BI__builtin_ia32_gatherdiv8di:
3431   case X86::BI__builtin_ia32_gatherdiv16si:
3432   case X86::BI__builtin_ia32_scatterdiv2df:
3433   case X86::BI__builtin_ia32_scatterdiv2di:
3434   case X86::BI__builtin_ia32_scatterdiv4df:
3435   case X86::BI__builtin_ia32_scatterdiv4di:
3436   case X86::BI__builtin_ia32_scatterdiv4sf:
3437   case X86::BI__builtin_ia32_scatterdiv4si:
3438   case X86::BI__builtin_ia32_scatterdiv8sf:
3439   case X86::BI__builtin_ia32_scatterdiv8si:
3440   case X86::BI__builtin_ia32_scattersiv2df:
3441   case X86::BI__builtin_ia32_scattersiv2di:
3442   case X86::BI__builtin_ia32_scattersiv4df:
3443   case X86::BI__builtin_ia32_scattersiv4di:
3444   case X86::BI__builtin_ia32_scattersiv4sf:
3445   case X86::BI__builtin_ia32_scattersiv4si:
3446   case X86::BI__builtin_ia32_scattersiv8sf:
3447   case X86::BI__builtin_ia32_scattersiv8si:
3448   case X86::BI__builtin_ia32_scattersiv8df:
3449   case X86::BI__builtin_ia32_scattersiv16sf:
3450   case X86::BI__builtin_ia32_scatterdiv8df:
3451   case X86::BI__builtin_ia32_scatterdiv16sf:
3452   case X86::BI__builtin_ia32_scattersiv8di:
3453   case X86::BI__builtin_ia32_scattersiv16si:
3454   case X86::BI__builtin_ia32_scatterdiv8di:
3455   case X86::BI__builtin_ia32_scatterdiv16si:
3456     ArgNum = 4;
3457     break;
3458   }
3459 
3460   llvm::APSInt Result;
3461 
3462   // We can't check the value of a dependent argument.
3463   Expr *Arg = TheCall->getArg(ArgNum);
3464   if (Arg->isTypeDependent() || Arg->isValueDependent())
3465     return false;
3466 
3467   // Check constant-ness first.
3468   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3469     return true;
3470 
3471   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3472     return false;
3473 
3474   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3475          << Arg->getSourceRange();
3476 }
3477 
3478 static bool isX86_32Builtin(unsigned BuiltinID) {
3479   // These builtins only work on x86-32 targets.
3480   switch (BuiltinID) {
3481   case X86::BI__builtin_ia32_readeflags_u32:
3482   case X86::BI__builtin_ia32_writeeflags_u32:
3483     return true;
3484   }
3485 
3486   return false;
3487 }
3488 
3489 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3490   if (BuiltinID == X86::BI__builtin_cpu_supports)
3491     return SemaBuiltinCpuSupports(*this, TheCall);
3492 
3493   if (BuiltinID == X86::BI__builtin_cpu_is)
3494     return SemaBuiltinCpuIs(*this, TheCall);
3495 
3496   // Check for 32-bit only builtins on a 64-bit target.
3497   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3498   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3499     return Diag(TheCall->getCallee()->getBeginLoc(),
3500                 diag::err_32_bit_builtin_64_bit_tgt);
3501 
3502   // If the intrinsic has rounding or SAE make sure its valid.
3503   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3504     return true;
3505 
3506   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3507   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3508     return true;
3509 
3510   // For intrinsics which take an immediate value as part of the instruction,
3511   // range check them here.
3512   int i = 0, l = 0, u = 0;
3513   switch (BuiltinID) {
3514   default:
3515     return false;
3516   case X86::BI__builtin_ia32_vec_ext_v2si:
3517   case X86::BI__builtin_ia32_vec_ext_v2di:
3518   case X86::BI__builtin_ia32_vextractf128_pd256:
3519   case X86::BI__builtin_ia32_vextractf128_ps256:
3520   case X86::BI__builtin_ia32_vextractf128_si256:
3521   case X86::BI__builtin_ia32_extract128i256:
3522   case X86::BI__builtin_ia32_extractf64x4_mask:
3523   case X86::BI__builtin_ia32_extracti64x4_mask:
3524   case X86::BI__builtin_ia32_extractf32x8_mask:
3525   case X86::BI__builtin_ia32_extracti32x8_mask:
3526   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3527   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3528   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3529   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3530     i = 1; l = 0; u = 1;
3531     break;
3532   case X86::BI__builtin_ia32_vec_set_v2di:
3533   case X86::BI__builtin_ia32_vinsertf128_pd256:
3534   case X86::BI__builtin_ia32_vinsertf128_ps256:
3535   case X86::BI__builtin_ia32_vinsertf128_si256:
3536   case X86::BI__builtin_ia32_insert128i256:
3537   case X86::BI__builtin_ia32_insertf32x8:
3538   case X86::BI__builtin_ia32_inserti32x8:
3539   case X86::BI__builtin_ia32_insertf64x4:
3540   case X86::BI__builtin_ia32_inserti64x4:
3541   case X86::BI__builtin_ia32_insertf64x2_256:
3542   case X86::BI__builtin_ia32_inserti64x2_256:
3543   case X86::BI__builtin_ia32_insertf32x4_256:
3544   case X86::BI__builtin_ia32_inserti32x4_256:
3545     i = 2; l = 0; u = 1;
3546     break;
3547   case X86::BI__builtin_ia32_vpermilpd:
3548   case X86::BI__builtin_ia32_vec_ext_v4hi:
3549   case X86::BI__builtin_ia32_vec_ext_v4si:
3550   case X86::BI__builtin_ia32_vec_ext_v4sf:
3551   case X86::BI__builtin_ia32_vec_ext_v4di:
3552   case X86::BI__builtin_ia32_extractf32x4_mask:
3553   case X86::BI__builtin_ia32_extracti32x4_mask:
3554   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3555   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3556     i = 1; l = 0; u = 3;
3557     break;
3558   case X86::BI_mm_prefetch:
3559   case X86::BI__builtin_ia32_vec_ext_v8hi:
3560   case X86::BI__builtin_ia32_vec_ext_v8si:
3561     i = 1; l = 0; u = 7;
3562     break;
3563   case X86::BI__builtin_ia32_sha1rnds4:
3564   case X86::BI__builtin_ia32_blendpd:
3565   case X86::BI__builtin_ia32_shufpd:
3566   case X86::BI__builtin_ia32_vec_set_v4hi:
3567   case X86::BI__builtin_ia32_vec_set_v4si:
3568   case X86::BI__builtin_ia32_vec_set_v4di:
3569   case X86::BI__builtin_ia32_shuf_f32x4_256:
3570   case X86::BI__builtin_ia32_shuf_f64x2_256:
3571   case X86::BI__builtin_ia32_shuf_i32x4_256:
3572   case X86::BI__builtin_ia32_shuf_i64x2_256:
3573   case X86::BI__builtin_ia32_insertf64x2_512:
3574   case X86::BI__builtin_ia32_inserti64x2_512:
3575   case X86::BI__builtin_ia32_insertf32x4:
3576   case X86::BI__builtin_ia32_inserti32x4:
3577     i = 2; l = 0; u = 3;
3578     break;
3579   case X86::BI__builtin_ia32_vpermil2pd:
3580   case X86::BI__builtin_ia32_vpermil2pd256:
3581   case X86::BI__builtin_ia32_vpermil2ps:
3582   case X86::BI__builtin_ia32_vpermil2ps256:
3583     i = 3; l = 0; u = 3;
3584     break;
3585   case X86::BI__builtin_ia32_cmpb128_mask:
3586   case X86::BI__builtin_ia32_cmpw128_mask:
3587   case X86::BI__builtin_ia32_cmpd128_mask:
3588   case X86::BI__builtin_ia32_cmpq128_mask:
3589   case X86::BI__builtin_ia32_cmpb256_mask:
3590   case X86::BI__builtin_ia32_cmpw256_mask:
3591   case X86::BI__builtin_ia32_cmpd256_mask:
3592   case X86::BI__builtin_ia32_cmpq256_mask:
3593   case X86::BI__builtin_ia32_cmpb512_mask:
3594   case X86::BI__builtin_ia32_cmpw512_mask:
3595   case X86::BI__builtin_ia32_cmpd512_mask:
3596   case X86::BI__builtin_ia32_cmpq512_mask:
3597   case X86::BI__builtin_ia32_ucmpb128_mask:
3598   case X86::BI__builtin_ia32_ucmpw128_mask:
3599   case X86::BI__builtin_ia32_ucmpd128_mask:
3600   case X86::BI__builtin_ia32_ucmpq128_mask:
3601   case X86::BI__builtin_ia32_ucmpb256_mask:
3602   case X86::BI__builtin_ia32_ucmpw256_mask:
3603   case X86::BI__builtin_ia32_ucmpd256_mask:
3604   case X86::BI__builtin_ia32_ucmpq256_mask:
3605   case X86::BI__builtin_ia32_ucmpb512_mask:
3606   case X86::BI__builtin_ia32_ucmpw512_mask:
3607   case X86::BI__builtin_ia32_ucmpd512_mask:
3608   case X86::BI__builtin_ia32_ucmpq512_mask:
3609   case X86::BI__builtin_ia32_vpcomub:
3610   case X86::BI__builtin_ia32_vpcomuw:
3611   case X86::BI__builtin_ia32_vpcomud:
3612   case X86::BI__builtin_ia32_vpcomuq:
3613   case X86::BI__builtin_ia32_vpcomb:
3614   case X86::BI__builtin_ia32_vpcomw:
3615   case X86::BI__builtin_ia32_vpcomd:
3616   case X86::BI__builtin_ia32_vpcomq:
3617   case X86::BI__builtin_ia32_vec_set_v8hi:
3618   case X86::BI__builtin_ia32_vec_set_v8si:
3619     i = 2; l = 0; u = 7;
3620     break;
3621   case X86::BI__builtin_ia32_vpermilpd256:
3622   case X86::BI__builtin_ia32_roundps:
3623   case X86::BI__builtin_ia32_roundpd:
3624   case X86::BI__builtin_ia32_roundps256:
3625   case X86::BI__builtin_ia32_roundpd256:
3626   case X86::BI__builtin_ia32_getmantpd128_mask:
3627   case X86::BI__builtin_ia32_getmantpd256_mask:
3628   case X86::BI__builtin_ia32_getmantps128_mask:
3629   case X86::BI__builtin_ia32_getmantps256_mask:
3630   case X86::BI__builtin_ia32_getmantpd512_mask:
3631   case X86::BI__builtin_ia32_getmantps512_mask:
3632   case X86::BI__builtin_ia32_vec_ext_v16qi:
3633   case X86::BI__builtin_ia32_vec_ext_v16hi:
3634     i = 1; l = 0; u = 15;
3635     break;
3636   case X86::BI__builtin_ia32_pblendd128:
3637   case X86::BI__builtin_ia32_blendps:
3638   case X86::BI__builtin_ia32_blendpd256:
3639   case X86::BI__builtin_ia32_shufpd256:
3640   case X86::BI__builtin_ia32_roundss:
3641   case X86::BI__builtin_ia32_roundsd:
3642   case X86::BI__builtin_ia32_rangepd128_mask:
3643   case X86::BI__builtin_ia32_rangepd256_mask:
3644   case X86::BI__builtin_ia32_rangepd512_mask:
3645   case X86::BI__builtin_ia32_rangeps128_mask:
3646   case X86::BI__builtin_ia32_rangeps256_mask:
3647   case X86::BI__builtin_ia32_rangeps512_mask:
3648   case X86::BI__builtin_ia32_getmantsd_round_mask:
3649   case X86::BI__builtin_ia32_getmantss_round_mask:
3650   case X86::BI__builtin_ia32_vec_set_v16qi:
3651   case X86::BI__builtin_ia32_vec_set_v16hi:
3652     i = 2; l = 0; u = 15;
3653     break;
3654   case X86::BI__builtin_ia32_vec_ext_v32qi:
3655     i = 1; l = 0; u = 31;
3656     break;
3657   case X86::BI__builtin_ia32_cmpps:
3658   case X86::BI__builtin_ia32_cmpss:
3659   case X86::BI__builtin_ia32_cmppd:
3660   case X86::BI__builtin_ia32_cmpsd:
3661   case X86::BI__builtin_ia32_cmpps256:
3662   case X86::BI__builtin_ia32_cmppd256:
3663   case X86::BI__builtin_ia32_cmpps128_mask:
3664   case X86::BI__builtin_ia32_cmppd128_mask:
3665   case X86::BI__builtin_ia32_cmpps256_mask:
3666   case X86::BI__builtin_ia32_cmppd256_mask:
3667   case X86::BI__builtin_ia32_cmpps512_mask:
3668   case X86::BI__builtin_ia32_cmppd512_mask:
3669   case X86::BI__builtin_ia32_cmpsd_mask:
3670   case X86::BI__builtin_ia32_cmpss_mask:
3671   case X86::BI__builtin_ia32_vec_set_v32qi:
3672     i = 2; l = 0; u = 31;
3673     break;
3674   case X86::BI__builtin_ia32_permdf256:
3675   case X86::BI__builtin_ia32_permdi256:
3676   case X86::BI__builtin_ia32_permdf512:
3677   case X86::BI__builtin_ia32_permdi512:
3678   case X86::BI__builtin_ia32_vpermilps:
3679   case X86::BI__builtin_ia32_vpermilps256:
3680   case X86::BI__builtin_ia32_vpermilpd512:
3681   case X86::BI__builtin_ia32_vpermilps512:
3682   case X86::BI__builtin_ia32_pshufd:
3683   case X86::BI__builtin_ia32_pshufd256:
3684   case X86::BI__builtin_ia32_pshufd512:
3685   case X86::BI__builtin_ia32_pshufhw:
3686   case X86::BI__builtin_ia32_pshufhw256:
3687   case X86::BI__builtin_ia32_pshufhw512:
3688   case X86::BI__builtin_ia32_pshuflw:
3689   case X86::BI__builtin_ia32_pshuflw256:
3690   case X86::BI__builtin_ia32_pshuflw512:
3691   case X86::BI__builtin_ia32_vcvtps2ph:
3692   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3693   case X86::BI__builtin_ia32_vcvtps2ph256:
3694   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3695   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3696   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3697   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3698   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3699   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3700   case X86::BI__builtin_ia32_rndscaleps_mask:
3701   case X86::BI__builtin_ia32_rndscalepd_mask:
3702   case X86::BI__builtin_ia32_reducepd128_mask:
3703   case X86::BI__builtin_ia32_reducepd256_mask:
3704   case X86::BI__builtin_ia32_reducepd512_mask:
3705   case X86::BI__builtin_ia32_reduceps128_mask:
3706   case X86::BI__builtin_ia32_reduceps256_mask:
3707   case X86::BI__builtin_ia32_reduceps512_mask:
3708   case X86::BI__builtin_ia32_prold512:
3709   case X86::BI__builtin_ia32_prolq512:
3710   case X86::BI__builtin_ia32_prold128:
3711   case X86::BI__builtin_ia32_prold256:
3712   case X86::BI__builtin_ia32_prolq128:
3713   case X86::BI__builtin_ia32_prolq256:
3714   case X86::BI__builtin_ia32_prord512:
3715   case X86::BI__builtin_ia32_prorq512:
3716   case X86::BI__builtin_ia32_prord128:
3717   case X86::BI__builtin_ia32_prord256:
3718   case X86::BI__builtin_ia32_prorq128:
3719   case X86::BI__builtin_ia32_prorq256:
3720   case X86::BI__builtin_ia32_fpclasspd128_mask:
3721   case X86::BI__builtin_ia32_fpclasspd256_mask:
3722   case X86::BI__builtin_ia32_fpclassps128_mask:
3723   case X86::BI__builtin_ia32_fpclassps256_mask:
3724   case X86::BI__builtin_ia32_fpclassps512_mask:
3725   case X86::BI__builtin_ia32_fpclasspd512_mask:
3726   case X86::BI__builtin_ia32_fpclasssd_mask:
3727   case X86::BI__builtin_ia32_fpclassss_mask:
3728   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3729   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3730   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3731   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3732   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3733   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3734   case X86::BI__builtin_ia32_kshiftliqi:
3735   case X86::BI__builtin_ia32_kshiftlihi:
3736   case X86::BI__builtin_ia32_kshiftlisi:
3737   case X86::BI__builtin_ia32_kshiftlidi:
3738   case X86::BI__builtin_ia32_kshiftriqi:
3739   case X86::BI__builtin_ia32_kshiftrihi:
3740   case X86::BI__builtin_ia32_kshiftrisi:
3741   case X86::BI__builtin_ia32_kshiftridi:
3742     i = 1; l = 0; u = 255;
3743     break;
3744   case X86::BI__builtin_ia32_vperm2f128_pd256:
3745   case X86::BI__builtin_ia32_vperm2f128_ps256:
3746   case X86::BI__builtin_ia32_vperm2f128_si256:
3747   case X86::BI__builtin_ia32_permti256:
3748   case X86::BI__builtin_ia32_pblendw128:
3749   case X86::BI__builtin_ia32_pblendw256:
3750   case X86::BI__builtin_ia32_blendps256:
3751   case X86::BI__builtin_ia32_pblendd256:
3752   case X86::BI__builtin_ia32_palignr128:
3753   case X86::BI__builtin_ia32_palignr256:
3754   case X86::BI__builtin_ia32_palignr512:
3755   case X86::BI__builtin_ia32_alignq512:
3756   case X86::BI__builtin_ia32_alignd512:
3757   case X86::BI__builtin_ia32_alignd128:
3758   case X86::BI__builtin_ia32_alignd256:
3759   case X86::BI__builtin_ia32_alignq128:
3760   case X86::BI__builtin_ia32_alignq256:
3761   case X86::BI__builtin_ia32_vcomisd:
3762   case X86::BI__builtin_ia32_vcomiss:
3763   case X86::BI__builtin_ia32_shuf_f32x4:
3764   case X86::BI__builtin_ia32_shuf_f64x2:
3765   case X86::BI__builtin_ia32_shuf_i32x4:
3766   case X86::BI__builtin_ia32_shuf_i64x2:
3767   case X86::BI__builtin_ia32_shufpd512:
3768   case X86::BI__builtin_ia32_shufps:
3769   case X86::BI__builtin_ia32_shufps256:
3770   case X86::BI__builtin_ia32_shufps512:
3771   case X86::BI__builtin_ia32_dbpsadbw128:
3772   case X86::BI__builtin_ia32_dbpsadbw256:
3773   case X86::BI__builtin_ia32_dbpsadbw512:
3774   case X86::BI__builtin_ia32_vpshldd128:
3775   case X86::BI__builtin_ia32_vpshldd256:
3776   case X86::BI__builtin_ia32_vpshldd512:
3777   case X86::BI__builtin_ia32_vpshldq128:
3778   case X86::BI__builtin_ia32_vpshldq256:
3779   case X86::BI__builtin_ia32_vpshldq512:
3780   case X86::BI__builtin_ia32_vpshldw128:
3781   case X86::BI__builtin_ia32_vpshldw256:
3782   case X86::BI__builtin_ia32_vpshldw512:
3783   case X86::BI__builtin_ia32_vpshrdd128:
3784   case X86::BI__builtin_ia32_vpshrdd256:
3785   case X86::BI__builtin_ia32_vpshrdd512:
3786   case X86::BI__builtin_ia32_vpshrdq128:
3787   case X86::BI__builtin_ia32_vpshrdq256:
3788   case X86::BI__builtin_ia32_vpshrdq512:
3789   case X86::BI__builtin_ia32_vpshrdw128:
3790   case X86::BI__builtin_ia32_vpshrdw256:
3791   case X86::BI__builtin_ia32_vpshrdw512:
3792     i = 2; l = 0; u = 255;
3793     break;
3794   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3795   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3796   case X86::BI__builtin_ia32_fixupimmps512_mask:
3797   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3798   case X86::BI__builtin_ia32_fixupimmsd_mask:
3799   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3800   case X86::BI__builtin_ia32_fixupimmss_mask:
3801   case X86::BI__builtin_ia32_fixupimmss_maskz:
3802   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3803   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3804   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3805   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3806   case X86::BI__builtin_ia32_fixupimmps128_mask:
3807   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3808   case X86::BI__builtin_ia32_fixupimmps256_mask:
3809   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3810   case X86::BI__builtin_ia32_pternlogd512_mask:
3811   case X86::BI__builtin_ia32_pternlogd512_maskz:
3812   case X86::BI__builtin_ia32_pternlogq512_mask:
3813   case X86::BI__builtin_ia32_pternlogq512_maskz:
3814   case X86::BI__builtin_ia32_pternlogd128_mask:
3815   case X86::BI__builtin_ia32_pternlogd128_maskz:
3816   case X86::BI__builtin_ia32_pternlogd256_mask:
3817   case X86::BI__builtin_ia32_pternlogd256_maskz:
3818   case X86::BI__builtin_ia32_pternlogq128_mask:
3819   case X86::BI__builtin_ia32_pternlogq128_maskz:
3820   case X86::BI__builtin_ia32_pternlogq256_mask:
3821   case X86::BI__builtin_ia32_pternlogq256_maskz:
3822     i = 3; l = 0; u = 255;
3823     break;
3824   case X86::BI__builtin_ia32_gatherpfdpd:
3825   case X86::BI__builtin_ia32_gatherpfdps:
3826   case X86::BI__builtin_ia32_gatherpfqpd:
3827   case X86::BI__builtin_ia32_gatherpfqps:
3828   case X86::BI__builtin_ia32_scatterpfdpd:
3829   case X86::BI__builtin_ia32_scatterpfdps:
3830   case X86::BI__builtin_ia32_scatterpfqpd:
3831   case X86::BI__builtin_ia32_scatterpfqps:
3832     i = 4; l = 2; u = 3;
3833     break;
3834   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3835   case X86::BI__builtin_ia32_rndscaless_round_mask:
3836     i = 4; l = 0; u = 255;
3837     break;
3838   }
3839 
3840   // Note that we don't force a hard error on the range check here, allowing
3841   // template-generated or macro-generated dead code to potentially have out-of-
3842   // range values. These need to code generate, but don't need to necessarily
3843   // make any sense. We use a warning that defaults to an error.
3844   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3845 }
3846 
3847 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3848 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3849 /// Returns true when the format fits the function and the FormatStringInfo has
3850 /// been populated.
3851 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3852                                FormatStringInfo *FSI) {
3853   FSI->HasVAListArg = Format->getFirstArg() == 0;
3854   FSI->FormatIdx = Format->getFormatIdx() - 1;
3855   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3856 
3857   // The way the format attribute works in GCC, the implicit this argument
3858   // of member functions is counted. However, it doesn't appear in our own
3859   // lists, so decrement format_idx in that case.
3860   if (IsCXXMember) {
3861     if(FSI->FormatIdx == 0)
3862       return false;
3863     --FSI->FormatIdx;
3864     if (FSI->FirstDataArg != 0)
3865       --FSI->FirstDataArg;
3866   }
3867   return true;
3868 }
3869 
3870 /// Checks if a the given expression evaluates to null.
3871 ///
3872 /// Returns true if the value evaluates to null.
3873 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3874   // If the expression has non-null type, it doesn't evaluate to null.
3875   if (auto nullability
3876         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3877     if (*nullability == NullabilityKind::NonNull)
3878       return false;
3879   }
3880 
3881   // As a special case, transparent unions initialized with zero are
3882   // considered null for the purposes of the nonnull attribute.
3883   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3884     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3885       if (const CompoundLiteralExpr *CLE =
3886           dyn_cast<CompoundLiteralExpr>(Expr))
3887         if (const InitListExpr *ILE =
3888             dyn_cast<InitListExpr>(CLE->getInitializer()))
3889           Expr = ILE->getInit(0);
3890   }
3891 
3892   bool Result;
3893   return (!Expr->isValueDependent() &&
3894           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3895           !Result);
3896 }
3897 
3898 static void CheckNonNullArgument(Sema &S,
3899                                  const Expr *ArgExpr,
3900                                  SourceLocation CallSiteLoc) {
3901   if (CheckNonNullExpr(S, ArgExpr))
3902     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3903            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
3904 }
3905 
3906 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3907   FormatStringInfo FSI;
3908   if ((GetFormatStringType(Format) == FST_NSString) &&
3909       getFormatStringInfo(Format, false, &FSI)) {
3910     Idx = FSI.FormatIdx;
3911     return true;
3912   }
3913   return false;
3914 }
3915 
3916 /// Diagnose use of %s directive in an NSString which is being passed
3917 /// as formatting string to formatting method.
3918 static void
3919 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3920                                         const NamedDecl *FDecl,
3921                                         Expr **Args,
3922                                         unsigned NumArgs) {
3923   unsigned Idx = 0;
3924   bool Format = false;
3925   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3926   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3927     Idx = 2;
3928     Format = true;
3929   }
3930   else
3931     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3932       if (S.GetFormatNSStringIdx(I, Idx)) {
3933         Format = true;
3934         break;
3935       }
3936     }
3937   if (!Format || NumArgs <= Idx)
3938     return;
3939   const Expr *FormatExpr = Args[Idx];
3940   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3941     FormatExpr = CSCE->getSubExpr();
3942   const StringLiteral *FormatString;
3943   if (const ObjCStringLiteral *OSL =
3944       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3945     FormatString = OSL->getString();
3946   else
3947     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3948   if (!FormatString)
3949     return;
3950   if (S.FormatStringHasSArg(FormatString)) {
3951     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3952       << "%s" << 1 << 1;
3953     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3954       << FDecl->getDeclName();
3955   }
3956 }
3957 
3958 /// Determine whether the given type has a non-null nullability annotation.
3959 static bool isNonNullType(ASTContext &ctx, QualType type) {
3960   if (auto nullability = type->getNullability(ctx))
3961     return *nullability == NullabilityKind::NonNull;
3962 
3963   return false;
3964 }
3965 
3966 static void CheckNonNullArguments(Sema &S,
3967                                   const NamedDecl *FDecl,
3968                                   const FunctionProtoType *Proto,
3969                                   ArrayRef<const Expr *> Args,
3970                                   SourceLocation CallSiteLoc) {
3971   assert((FDecl || Proto) && "Need a function declaration or prototype");
3972 
3973   // Check the attributes attached to the method/function itself.
3974   llvm::SmallBitVector NonNullArgs;
3975   if (FDecl) {
3976     // Handle the nonnull attribute on the function/method declaration itself.
3977     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3978       if (!NonNull->args_size()) {
3979         // Easy case: all pointer arguments are nonnull.
3980         for (const auto *Arg : Args)
3981           if (S.isValidPointerAttrType(Arg->getType()))
3982             CheckNonNullArgument(S, Arg, CallSiteLoc);
3983         return;
3984       }
3985 
3986       for (const ParamIdx &Idx : NonNull->args()) {
3987         unsigned IdxAST = Idx.getASTIndex();
3988         if (IdxAST >= Args.size())
3989           continue;
3990         if (NonNullArgs.empty())
3991           NonNullArgs.resize(Args.size());
3992         NonNullArgs.set(IdxAST);
3993       }
3994     }
3995   }
3996 
3997   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3998     // Handle the nonnull attribute on the parameters of the
3999     // function/method.
4000     ArrayRef<ParmVarDecl*> parms;
4001     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4002       parms = FD->parameters();
4003     else
4004       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4005 
4006     unsigned ParamIndex = 0;
4007     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4008          I != E; ++I, ++ParamIndex) {
4009       const ParmVarDecl *PVD = *I;
4010       if (PVD->hasAttr<NonNullAttr>() ||
4011           isNonNullType(S.Context, PVD->getType())) {
4012         if (NonNullArgs.empty())
4013           NonNullArgs.resize(Args.size());
4014 
4015         NonNullArgs.set(ParamIndex);
4016       }
4017     }
4018   } else {
4019     // If we have a non-function, non-method declaration but no
4020     // function prototype, try to dig out the function prototype.
4021     if (!Proto) {
4022       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4023         QualType type = VD->getType().getNonReferenceType();
4024         if (auto pointerType = type->getAs<PointerType>())
4025           type = pointerType->getPointeeType();
4026         else if (auto blockType = type->getAs<BlockPointerType>())
4027           type = blockType->getPointeeType();
4028         // FIXME: data member pointers?
4029 
4030         // Dig out the function prototype, if there is one.
4031         Proto = type->getAs<FunctionProtoType>();
4032       }
4033     }
4034 
4035     // Fill in non-null argument information from the nullability
4036     // information on the parameter types (if we have them).
4037     if (Proto) {
4038       unsigned Index = 0;
4039       for (auto paramType : Proto->getParamTypes()) {
4040         if (isNonNullType(S.Context, paramType)) {
4041           if (NonNullArgs.empty())
4042             NonNullArgs.resize(Args.size());
4043 
4044           NonNullArgs.set(Index);
4045         }
4046 
4047         ++Index;
4048       }
4049     }
4050   }
4051 
4052   // Check for non-null arguments.
4053   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4054        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4055     if (NonNullArgs[ArgIndex])
4056       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4057   }
4058 }
4059 
4060 /// Handles the checks for format strings, non-POD arguments to vararg
4061 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4062 /// attributes.
4063 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4064                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4065                      bool IsMemberFunction, SourceLocation Loc,
4066                      SourceRange Range, VariadicCallType CallType) {
4067   // FIXME: We should check as much as we can in the template definition.
4068   if (CurContext->isDependentContext())
4069     return;
4070 
4071   // Printf and scanf checking.
4072   llvm::SmallBitVector CheckedVarArgs;
4073   if (FDecl) {
4074     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4075       // Only create vector if there are format attributes.
4076       CheckedVarArgs.resize(Args.size());
4077 
4078       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4079                            CheckedVarArgs);
4080     }
4081   }
4082 
4083   // Refuse POD arguments that weren't caught by the format string
4084   // checks above.
4085   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4086   if (CallType != VariadicDoesNotApply &&
4087       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4088     unsigned NumParams = Proto ? Proto->getNumParams()
4089                        : FDecl && isa<FunctionDecl>(FDecl)
4090                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4091                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4092                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4093                        : 0;
4094 
4095     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4096       // Args[ArgIdx] can be null in malformed code.
4097       if (const Expr *Arg = Args[ArgIdx]) {
4098         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4099           checkVariadicArgument(Arg, CallType);
4100       }
4101     }
4102   }
4103 
4104   if (FDecl || Proto) {
4105     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4106 
4107     // Type safety checking.
4108     if (FDecl) {
4109       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4110         CheckArgumentWithTypeTag(I, Args, Loc);
4111     }
4112   }
4113 
4114   if (FD)
4115     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4116 }
4117 
4118 /// CheckConstructorCall - Check a constructor call for correctness and safety
4119 /// properties not enforced by the C type system.
4120 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4121                                 ArrayRef<const Expr *> Args,
4122                                 const FunctionProtoType *Proto,
4123                                 SourceLocation Loc) {
4124   VariadicCallType CallType =
4125     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4126   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4127             Loc, SourceRange(), CallType);
4128 }
4129 
4130 /// CheckFunctionCall - Check a direct function call for various correctness
4131 /// and safety properties not strictly enforced by the C type system.
4132 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4133                              const FunctionProtoType *Proto) {
4134   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4135                               isa<CXXMethodDecl>(FDecl);
4136   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4137                           IsMemberOperatorCall;
4138   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4139                                                   TheCall->getCallee());
4140   Expr** Args = TheCall->getArgs();
4141   unsigned NumArgs = TheCall->getNumArgs();
4142 
4143   Expr *ImplicitThis = nullptr;
4144   if (IsMemberOperatorCall) {
4145     // If this is a call to a member operator, hide the first argument
4146     // from checkCall.
4147     // FIXME: Our choice of AST representation here is less than ideal.
4148     ImplicitThis = Args[0];
4149     ++Args;
4150     --NumArgs;
4151   } else if (IsMemberFunction)
4152     ImplicitThis =
4153         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4154 
4155   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4156             IsMemberFunction, TheCall->getRParenLoc(),
4157             TheCall->getCallee()->getSourceRange(), CallType);
4158 
4159   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4160   // None of the checks below are needed for functions that don't have
4161   // simple names (e.g., C++ conversion functions).
4162   if (!FnInfo)
4163     return false;
4164 
4165   CheckAbsoluteValueFunction(TheCall, FDecl);
4166   CheckMaxUnsignedZero(TheCall, FDecl);
4167 
4168   if (getLangOpts().ObjC1)
4169     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4170 
4171   unsigned CMId = FDecl->getMemoryFunctionKind();
4172   if (CMId == 0)
4173     return false;
4174 
4175   // Handle memory setting and copying functions.
4176   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4177     CheckStrlcpycatArguments(TheCall, FnInfo);
4178   else if (CMId == Builtin::BIstrncat)
4179     CheckStrncatArguments(TheCall, FnInfo);
4180   else
4181     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4182 
4183   return false;
4184 }
4185 
4186 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4187                                ArrayRef<const Expr *> Args) {
4188   VariadicCallType CallType =
4189       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4190 
4191   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4192             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4193             CallType);
4194 
4195   return false;
4196 }
4197 
4198 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4199                             const FunctionProtoType *Proto) {
4200   QualType Ty;
4201   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4202     Ty = V->getType().getNonReferenceType();
4203   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4204     Ty = F->getType().getNonReferenceType();
4205   else
4206     return false;
4207 
4208   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4209       !Ty->isFunctionProtoType())
4210     return false;
4211 
4212   VariadicCallType CallType;
4213   if (!Proto || !Proto->isVariadic()) {
4214     CallType = VariadicDoesNotApply;
4215   } else if (Ty->isBlockPointerType()) {
4216     CallType = VariadicBlock;
4217   } else { // Ty->isFunctionPointerType()
4218     CallType = VariadicFunction;
4219   }
4220 
4221   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4222             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4223             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4224             TheCall->getCallee()->getSourceRange(), CallType);
4225 
4226   return false;
4227 }
4228 
4229 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4230 /// such as function pointers returned from functions.
4231 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4232   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4233                                                   TheCall->getCallee());
4234   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4235             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4236             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4237             TheCall->getCallee()->getSourceRange(), CallType);
4238 
4239   return false;
4240 }
4241 
4242 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4243   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4244     return false;
4245 
4246   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4247   switch (Op) {
4248   case AtomicExpr::AO__c11_atomic_init:
4249   case AtomicExpr::AO__opencl_atomic_init:
4250     llvm_unreachable("There is no ordering argument for an init");
4251 
4252   case AtomicExpr::AO__c11_atomic_load:
4253   case AtomicExpr::AO__opencl_atomic_load:
4254   case AtomicExpr::AO__atomic_load_n:
4255   case AtomicExpr::AO__atomic_load:
4256     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4257            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4258 
4259   case AtomicExpr::AO__c11_atomic_store:
4260   case AtomicExpr::AO__opencl_atomic_store:
4261   case AtomicExpr::AO__atomic_store:
4262   case AtomicExpr::AO__atomic_store_n:
4263     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4264            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4265            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4266 
4267   default:
4268     return true;
4269   }
4270 }
4271 
4272 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4273                                          AtomicExpr::AtomicOp Op) {
4274   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4275   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4276 
4277   // All the non-OpenCL operations take one of the following forms.
4278   // The OpenCL operations take the __c11 forms with one extra argument for
4279   // synchronization scope.
4280   enum {
4281     // C    __c11_atomic_init(A *, C)
4282     Init,
4283 
4284     // C    __c11_atomic_load(A *, int)
4285     Load,
4286 
4287     // void __atomic_load(A *, CP, int)
4288     LoadCopy,
4289 
4290     // void __atomic_store(A *, CP, int)
4291     Copy,
4292 
4293     // C    __c11_atomic_add(A *, M, int)
4294     Arithmetic,
4295 
4296     // C    __atomic_exchange_n(A *, CP, int)
4297     Xchg,
4298 
4299     // void __atomic_exchange(A *, C *, CP, int)
4300     GNUXchg,
4301 
4302     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4303     C11CmpXchg,
4304 
4305     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4306     GNUCmpXchg
4307   } Form = Init;
4308 
4309   const unsigned NumForm = GNUCmpXchg + 1;
4310   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4311   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4312   // where:
4313   //   C is an appropriate type,
4314   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4315   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4316   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4317   //   the int parameters are for orderings.
4318 
4319   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4320       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4321       "need to update code for modified forms");
4322   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4323                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4324                         AtomicExpr::AO__atomic_load,
4325                 "need to update code for modified C11 atomics");
4326   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4327                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4328   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4329                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4330                IsOpenCL;
4331   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4332              Op == AtomicExpr::AO__atomic_store_n ||
4333              Op == AtomicExpr::AO__atomic_exchange_n ||
4334              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4335   bool IsAddSub = false;
4336   bool IsMinMax = false;
4337 
4338   switch (Op) {
4339   case AtomicExpr::AO__c11_atomic_init:
4340   case AtomicExpr::AO__opencl_atomic_init:
4341     Form = Init;
4342     break;
4343 
4344   case AtomicExpr::AO__c11_atomic_load:
4345   case AtomicExpr::AO__opencl_atomic_load:
4346   case AtomicExpr::AO__atomic_load_n:
4347     Form = Load;
4348     break;
4349 
4350   case AtomicExpr::AO__atomic_load:
4351     Form = LoadCopy;
4352     break;
4353 
4354   case AtomicExpr::AO__c11_atomic_store:
4355   case AtomicExpr::AO__opencl_atomic_store:
4356   case AtomicExpr::AO__atomic_store:
4357   case AtomicExpr::AO__atomic_store_n:
4358     Form = Copy;
4359     break;
4360 
4361   case AtomicExpr::AO__c11_atomic_fetch_add:
4362   case AtomicExpr::AO__c11_atomic_fetch_sub:
4363   case AtomicExpr::AO__opencl_atomic_fetch_add:
4364   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4365   case AtomicExpr::AO__opencl_atomic_fetch_min:
4366   case AtomicExpr::AO__opencl_atomic_fetch_max:
4367   case AtomicExpr::AO__atomic_fetch_add:
4368   case AtomicExpr::AO__atomic_fetch_sub:
4369   case AtomicExpr::AO__atomic_add_fetch:
4370   case AtomicExpr::AO__atomic_sub_fetch:
4371     IsAddSub = true;
4372     LLVM_FALLTHROUGH;
4373   case AtomicExpr::AO__c11_atomic_fetch_and:
4374   case AtomicExpr::AO__c11_atomic_fetch_or:
4375   case AtomicExpr::AO__c11_atomic_fetch_xor:
4376   case AtomicExpr::AO__opencl_atomic_fetch_and:
4377   case AtomicExpr::AO__opencl_atomic_fetch_or:
4378   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4379   case AtomicExpr::AO__atomic_fetch_and:
4380   case AtomicExpr::AO__atomic_fetch_or:
4381   case AtomicExpr::AO__atomic_fetch_xor:
4382   case AtomicExpr::AO__atomic_fetch_nand:
4383   case AtomicExpr::AO__atomic_and_fetch:
4384   case AtomicExpr::AO__atomic_or_fetch:
4385   case AtomicExpr::AO__atomic_xor_fetch:
4386   case AtomicExpr::AO__atomic_nand_fetch:
4387     Form = Arithmetic;
4388     break;
4389 
4390   case AtomicExpr::AO__atomic_fetch_min:
4391   case AtomicExpr::AO__atomic_fetch_max:
4392     IsMinMax = true;
4393     Form = Arithmetic;
4394     break;
4395 
4396   case AtomicExpr::AO__c11_atomic_exchange:
4397   case AtomicExpr::AO__opencl_atomic_exchange:
4398   case AtomicExpr::AO__atomic_exchange_n:
4399     Form = Xchg;
4400     break;
4401 
4402   case AtomicExpr::AO__atomic_exchange:
4403     Form = GNUXchg;
4404     break;
4405 
4406   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4407   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4408   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4409   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4410     Form = C11CmpXchg;
4411     break;
4412 
4413   case AtomicExpr::AO__atomic_compare_exchange:
4414   case AtomicExpr::AO__atomic_compare_exchange_n:
4415     Form = GNUCmpXchg;
4416     break;
4417   }
4418 
4419   unsigned AdjustedNumArgs = NumArgs[Form];
4420   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4421     ++AdjustedNumArgs;
4422   // Check we have the right number of arguments.
4423   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4424     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4425         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4426         << TheCall->getCallee()->getSourceRange();
4427     return ExprError();
4428   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4429     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4430          diag::err_typecheck_call_too_many_args)
4431         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4432         << TheCall->getCallee()->getSourceRange();
4433     return ExprError();
4434   }
4435 
4436   // Inspect the first argument of the atomic operation.
4437   Expr *Ptr = TheCall->getArg(0);
4438   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4439   if (ConvertedPtr.isInvalid())
4440     return ExprError();
4441 
4442   Ptr = ConvertedPtr.get();
4443   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4444   if (!pointerType) {
4445     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4446         << Ptr->getType() << Ptr->getSourceRange();
4447     return ExprError();
4448   }
4449 
4450   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4451   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4452   QualType ValType = AtomTy; // 'C'
4453   if (IsC11) {
4454     if (!AtomTy->isAtomicType()) {
4455       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4456           << Ptr->getType() << Ptr->getSourceRange();
4457       return ExprError();
4458     }
4459     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4460         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4461       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4462           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4463           << Ptr->getSourceRange();
4464       return ExprError();
4465     }
4466     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4467   } else if (Form != Load && Form != LoadCopy) {
4468     if (ValType.isConstQualified()) {
4469       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4470           << Ptr->getType() << Ptr->getSourceRange();
4471       return ExprError();
4472     }
4473   }
4474 
4475   // For an arithmetic operation, the implied arithmetic must be well-formed.
4476   if (Form == Arithmetic) {
4477     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4478     if (IsAddSub && !ValType->isIntegerType()
4479         && !ValType->isPointerType()) {
4480       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4481           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4482       return ExprError();
4483     }
4484     if (IsMinMax) {
4485       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4486       if (!BT || (BT->getKind() != BuiltinType::Int &&
4487                   BT->getKind() != BuiltinType::UInt)) {
4488         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4489         return ExprError();
4490       }
4491     }
4492     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4493       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4494           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4495       return ExprError();
4496     }
4497     if (IsC11 && ValType->isPointerType() &&
4498         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4499                             diag::err_incomplete_type)) {
4500       return ExprError();
4501     }
4502   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4503     // For __atomic_*_n operations, the value type must be a scalar integral or
4504     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4505     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4506         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4507     return ExprError();
4508   }
4509 
4510   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4511       !AtomTy->isScalarType()) {
4512     // For GNU atomics, require a trivially-copyable type. This is not part of
4513     // the GNU atomics specification, but we enforce it for sanity.
4514     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4515         << Ptr->getType() << Ptr->getSourceRange();
4516     return ExprError();
4517   }
4518 
4519   switch (ValType.getObjCLifetime()) {
4520   case Qualifiers::OCL_None:
4521   case Qualifiers::OCL_ExplicitNone:
4522     // okay
4523     break;
4524 
4525   case Qualifiers::OCL_Weak:
4526   case Qualifiers::OCL_Strong:
4527   case Qualifiers::OCL_Autoreleasing:
4528     // FIXME: Can this happen? By this point, ValType should be known
4529     // to be trivially copyable.
4530     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4531         << ValType << Ptr->getSourceRange();
4532     return ExprError();
4533   }
4534 
4535   // All atomic operations have an overload which takes a pointer to a volatile
4536   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4537   // into the result or the other operands. Similarly atomic_load takes a
4538   // pointer to a const 'A'.
4539   ValType.removeLocalVolatile();
4540   ValType.removeLocalConst();
4541   QualType ResultType = ValType;
4542   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4543       Form == Init)
4544     ResultType = Context.VoidTy;
4545   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4546     ResultType = Context.BoolTy;
4547 
4548   // The type of a parameter passed 'by value'. In the GNU atomics, such
4549   // arguments are actually passed as pointers.
4550   QualType ByValType = ValType; // 'CP'
4551   bool IsPassedByAddress = false;
4552   if (!IsC11 && !IsN) {
4553     ByValType = Ptr->getType();
4554     IsPassedByAddress = true;
4555   }
4556 
4557   // The first argument's non-CV pointer type is used to deduce the type of
4558   // subsequent arguments, except for:
4559   //  - weak flag (always converted to bool)
4560   //  - memory order (always converted to int)
4561   //  - scope  (always converted to int)
4562   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4563     QualType Ty;
4564     if (i < NumVals[Form] + 1) {
4565       switch (i) {
4566       case 0:
4567         // The first argument is always a pointer. It has a fixed type.
4568         // It is always dereferenced, a nullptr is undefined.
4569         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4570         // Nothing else to do: we already know all we want about this pointer.
4571         continue;
4572       case 1:
4573         // The second argument is the non-atomic operand. For arithmetic, this
4574         // is always passed by value, and for a compare_exchange it is always
4575         // passed by address. For the rest, GNU uses by-address and C11 uses
4576         // by-value.
4577         assert(Form != Load);
4578         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4579           Ty = ValType;
4580         else if (Form == Copy || Form == Xchg) {
4581           if (IsPassedByAddress)
4582             // The value pointer is always dereferenced, a nullptr is undefined.
4583             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4584           Ty = ByValType;
4585         } else if (Form == Arithmetic)
4586           Ty = Context.getPointerDiffType();
4587         else {
4588           Expr *ValArg = TheCall->getArg(i);
4589           // The value pointer is always dereferenced, a nullptr is undefined.
4590           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4591           LangAS AS = LangAS::Default;
4592           // Keep address space of non-atomic pointer type.
4593           if (const PointerType *PtrTy =
4594                   ValArg->getType()->getAs<PointerType>()) {
4595             AS = PtrTy->getPointeeType().getAddressSpace();
4596           }
4597           Ty = Context.getPointerType(
4598               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4599         }
4600         break;
4601       case 2:
4602         // The third argument to compare_exchange / GNU exchange is the desired
4603         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4604         if (IsPassedByAddress)
4605           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4606         Ty = ByValType;
4607         break;
4608       case 3:
4609         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4610         Ty = Context.BoolTy;
4611         break;
4612       }
4613     } else {
4614       // The order(s) and scope are always converted to int.
4615       Ty = Context.IntTy;
4616     }
4617 
4618     InitializedEntity Entity =
4619         InitializedEntity::InitializeParameter(Context, Ty, false);
4620     ExprResult Arg = TheCall->getArg(i);
4621     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4622     if (Arg.isInvalid())
4623       return true;
4624     TheCall->setArg(i, Arg.get());
4625   }
4626 
4627   // Permute the arguments into a 'consistent' order.
4628   SmallVector<Expr*, 5> SubExprs;
4629   SubExprs.push_back(Ptr);
4630   switch (Form) {
4631   case Init:
4632     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4633     SubExprs.push_back(TheCall->getArg(1)); // Val1
4634     break;
4635   case Load:
4636     SubExprs.push_back(TheCall->getArg(1)); // Order
4637     break;
4638   case LoadCopy:
4639   case Copy:
4640   case Arithmetic:
4641   case Xchg:
4642     SubExprs.push_back(TheCall->getArg(2)); // Order
4643     SubExprs.push_back(TheCall->getArg(1)); // Val1
4644     break;
4645   case GNUXchg:
4646     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4647     SubExprs.push_back(TheCall->getArg(3)); // Order
4648     SubExprs.push_back(TheCall->getArg(1)); // Val1
4649     SubExprs.push_back(TheCall->getArg(2)); // Val2
4650     break;
4651   case C11CmpXchg:
4652     SubExprs.push_back(TheCall->getArg(3)); // Order
4653     SubExprs.push_back(TheCall->getArg(1)); // Val1
4654     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4655     SubExprs.push_back(TheCall->getArg(2)); // Val2
4656     break;
4657   case GNUCmpXchg:
4658     SubExprs.push_back(TheCall->getArg(4)); // Order
4659     SubExprs.push_back(TheCall->getArg(1)); // Val1
4660     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4661     SubExprs.push_back(TheCall->getArg(2)); // Val2
4662     SubExprs.push_back(TheCall->getArg(3)); // Weak
4663     break;
4664   }
4665 
4666   if (SubExprs.size() >= 2 && Form != Init) {
4667     llvm::APSInt Result(32);
4668     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4669         !isValidOrderingForOp(Result.getSExtValue(), Op))
4670       Diag(SubExprs[1]->getBeginLoc(),
4671            diag::warn_atomic_op_has_invalid_memory_order)
4672           << SubExprs[1]->getSourceRange();
4673   }
4674 
4675   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4676     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4677     llvm::APSInt Result(32);
4678     if (Scope->isIntegerConstantExpr(Result, Context) &&
4679         !ScopeModel->isValid(Result.getZExtValue())) {
4680       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4681           << Scope->getSourceRange();
4682     }
4683     SubExprs.push_back(Scope);
4684   }
4685 
4686   AtomicExpr *AE =
4687       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4688                                ResultType, Op, TheCall->getRParenLoc());
4689 
4690   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4691        Op == AtomicExpr::AO__c11_atomic_store ||
4692        Op == AtomicExpr::AO__opencl_atomic_load ||
4693        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4694       Context.AtomicUsesUnsupportedLibcall(AE))
4695     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4696         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4697              Op == AtomicExpr::AO__opencl_atomic_load)
4698                 ? 0
4699                 : 1);
4700 
4701   return AE;
4702 }
4703 
4704 /// checkBuiltinArgument - Given a call to a builtin function, perform
4705 /// normal type-checking on the given argument, updating the call in
4706 /// place.  This is useful when a builtin function requires custom
4707 /// type-checking for some of its arguments but not necessarily all of
4708 /// them.
4709 ///
4710 /// Returns true on error.
4711 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4712   FunctionDecl *Fn = E->getDirectCallee();
4713   assert(Fn && "builtin call without direct callee!");
4714 
4715   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4716   InitializedEntity Entity =
4717     InitializedEntity::InitializeParameter(S.Context, Param);
4718 
4719   ExprResult Arg = E->getArg(0);
4720   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4721   if (Arg.isInvalid())
4722     return true;
4723 
4724   E->setArg(ArgIndex, Arg.get());
4725   return false;
4726 }
4727 
4728 /// We have a call to a function like __sync_fetch_and_add, which is an
4729 /// overloaded function based on the pointer type of its first argument.
4730 /// The main ActOnCallExpr routines have already promoted the types of
4731 /// arguments because all of these calls are prototyped as void(...).
4732 ///
4733 /// This function goes through and does final semantic checking for these
4734 /// builtins, as well as generating any warnings.
4735 ExprResult
4736 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4737   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4738   Expr *Callee = TheCall->getCallee();
4739   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4740   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4741 
4742   // Ensure that we have at least one argument to do type inference from.
4743   if (TheCall->getNumArgs() < 1) {
4744     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4745         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4746     return ExprError();
4747   }
4748 
4749   // Inspect the first argument of the atomic builtin.  This should always be
4750   // a pointer type, whose element is an integral scalar or pointer type.
4751   // Because it is a pointer type, we don't have to worry about any implicit
4752   // casts here.
4753   // FIXME: We don't allow floating point scalars as input.
4754   Expr *FirstArg = TheCall->getArg(0);
4755   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4756   if (FirstArgResult.isInvalid())
4757     return ExprError();
4758   FirstArg = FirstArgResult.get();
4759   TheCall->setArg(0, FirstArg);
4760 
4761   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4762   if (!pointerType) {
4763     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4764         << FirstArg->getType() << FirstArg->getSourceRange();
4765     return ExprError();
4766   }
4767 
4768   QualType ValType = pointerType->getPointeeType();
4769   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4770       !ValType->isBlockPointerType()) {
4771     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4772         << FirstArg->getType() << FirstArg->getSourceRange();
4773     return ExprError();
4774   }
4775 
4776   if (ValType.isConstQualified()) {
4777     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4778         << FirstArg->getType() << FirstArg->getSourceRange();
4779     return ExprError();
4780   }
4781 
4782   switch (ValType.getObjCLifetime()) {
4783   case Qualifiers::OCL_None:
4784   case Qualifiers::OCL_ExplicitNone:
4785     // okay
4786     break;
4787 
4788   case Qualifiers::OCL_Weak:
4789   case Qualifiers::OCL_Strong:
4790   case Qualifiers::OCL_Autoreleasing:
4791     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4792         << ValType << FirstArg->getSourceRange();
4793     return ExprError();
4794   }
4795 
4796   // Strip any qualifiers off ValType.
4797   ValType = ValType.getUnqualifiedType();
4798 
4799   // The majority of builtins return a value, but a few have special return
4800   // types, so allow them to override appropriately below.
4801   QualType ResultType = ValType;
4802 
4803   // We need to figure out which concrete builtin this maps onto.  For example,
4804   // __sync_fetch_and_add with a 2 byte object turns into
4805   // __sync_fetch_and_add_2.
4806 #define BUILTIN_ROW(x) \
4807   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4808     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4809 
4810   static const unsigned BuiltinIndices[][5] = {
4811     BUILTIN_ROW(__sync_fetch_and_add),
4812     BUILTIN_ROW(__sync_fetch_and_sub),
4813     BUILTIN_ROW(__sync_fetch_and_or),
4814     BUILTIN_ROW(__sync_fetch_and_and),
4815     BUILTIN_ROW(__sync_fetch_and_xor),
4816     BUILTIN_ROW(__sync_fetch_and_nand),
4817 
4818     BUILTIN_ROW(__sync_add_and_fetch),
4819     BUILTIN_ROW(__sync_sub_and_fetch),
4820     BUILTIN_ROW(__sync_and_and_fetch),
4821     BUILTIN_ROW(__sync_or_and_fetch),
4822     BUILTIN_ROW(__sync_xor_and_fetch),
4823     BUILTIN_ROW(__sync_nand_and_fetch),
4824 
4825     BUILTIN_ROW(__sync_val_compare_and_swap),
4826     BUILTIN_ROW(__sync_bool_compare_and_swap),
4827     BUILTIN_ROW(__sync_lock_test_and_set),
4828     BUILTIN_ROW(__sync_lock_release),
4829     BUILTIN_ROW(__sync_swap)
4830   };
4831 #undef BUILTIN_ROW
4832 
4833   // Determine the index of the size.
4834   unsigned SizeIndex;
4835   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4836   case 1: SizeIndex = 0; break;
4837   case 2: SizeIndex = 1; break;
4838   case 4: SizeIndex = 2; break;
4839   case 8: SizeIndex = 3; break;
4840   case 16: SizeIndex = 4; break;
4841   default:
4842     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4843         << FirstArg->getType() << FirstArg->getSourceRange();
4844     return ExprError();
4845   }
4846 
4847   // Each of these builtins has one pointer argument, followed by some number of
4848   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4849   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4850   // as the number of fixed args.
4851   unsigned BuiltinID = FDecl->getBuiltinID();
4852   unsigned BuiltinIndex, NumFixed = 1;
4853   bool WarnAboutSemanticsChange = false;
4854   switch (BuiltinID) {
4855   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4856   case Builtin::BI__sync_fetch_and_add:
4857   case Builtin::BI__sync_fetch_and_add_1:
4858   case Builtin::BI__sync_fetch_and_add_2:
4859   case Builtin::BI__sync_fetch_and_add_4:
4860   case Builtin::BI__sync_fetch_and_add_8:
4861   case Builtin::BI__sync_fetch_and_add_16:
4862     BuiltinIndex = 0;
4863     break;
4864 
4865   case Builtin::BI__sync_fetch_and_sub:
4866   case Builtin::BI__sync_fetch_and_sub_1:
4867   case Builtin::BI__sync_fetch_and_sub_2:
4868   case Builtin::BI__sync_fetch_and_sub_4:
4869   case Builtin::BI__sync_fetch_and_sub_8:
4870   case Builtin::BI__sync_fetch_and_sub_16:
4871     BuiltinIndex = 1;
4872     break;
4873 
4874   case Builtin::BI__sync_fetch_and_or:
4875   case Builtin::BI__sync_fetch_and_or_1:
4876   case Builtin::BI__sync_fetch_and_or_2:
4877   case Builtin::BI__sync_fetch_and_or_4:
4878   case Builtin::BI__sync_fetch_and_or_8:
4879   case Builtin::BI__sync_fetch_and_or_16:
4880     BuiltinIndex = 2;
4881     break;
4882 
4883   case Builtin::BI__sync_fetch_and_and:
4884   case Builtin::BI__sync_fetch_and_and_1:
4885   case Builtin::BI__sync_fetch_and_and_2:
4886   case Builtin::BI__sync_fetch_and_and_4:
4887   case Builtin::BI__sync_fetch_and_and_8:
4888   case Builtin::BI__sync_fetch_and_and_16:
4889     BuiltinIndex = 3;
4890     break;
4891 
4892   case Builtin::BI__sync_fetch_and_xor:
4893   case Builtin::BI__sync_fetch_and_xor_1:
4894   case Builtin::BI__sync_fetch_and_xor_2:
4895   case Builtin::BI__sync_fetch_and_xor_4:
4896   case Builtin::BI__sync_fetch_and_xor_8:
4897   case Builtin::BI__sync_fetch_and_xor_16:
4898     BuiltinIndex = 4;
4899     break;
4900 
4901   case Builtin::BI__sync_fetch_and_nand:
4902   case Builtin::BI__sync_fetch_and_nand_1:
4903   case Builtin::BI__sync_fetch_and_nand_2:
4904   case Builtin::BI__sync_fetch_and_nand_4:
4905   case Builtin::BI__sync_fetch_and_nand_8:
4906   case Builtin::BI__sync_fetch_and_nand_16:
4907     BuiltinIndex = 5;
4908     WarnAboutSemanticsChange = true;
4909     break;
4910 
4911   case Builtin::BI__sync_add_and_fetch:
4912   case Builtin::BI__sync_add_and_fetch_1:
4913   case Builtin::BI__sync_add_and_fetch_2:
4914   case Builtin::BI__sync_add_and_fetch_4:
4915   case Builtin::BI__sync_add_and_fetch_8:
4916   case Builtin::BI__sync_add_and_fetch_16:
4917     BuiltinIndex = 6;
4918     break;
4919 
4920   case Builtin::BI__sync_sub_and_fetch:
4921   case Builtin::BI__sync_sub_and_fetch_1:
4922   case Builtin::BI__sync_sub_and_fetch_2:
4923   case Builtin::BI__sync_sub_and_fetch_4:
4924   case Builtin::BI__sync_sub_and_fetch_8:
4925   case Builtin::BI__sync_sub_and_fetch_16:
4926     BuiltinIndex = 7;
4927     break;
4928 
4929   case Builtin::BI__sync_and_and_fetch:
4930   case Builtin::BI__sync_and_and_fetch_1:
4931   case Builtin::BI__sync_and_and_fetch_2:
4932   case Builtin::BI__sync_and_and_fetch_4:
4933   case Builtin::BI__sync_and_and_fetch_8:
4934   case Builtin::BI__sync_and_and_fetch_16:
4935     BuiltinIndex = 8;
4936     break;
4937 
4938   case Builtin::BI__sync_or_and_fetch:
4939   case Builtin::BI__sync_or_and_fetch_1:
4940   case Builtin::BI__sync_or_and_fetch_2:
4941   case Builtin::BI__sync_or_and_fetch_4:
4942   case Builtin::BI__sync_or_and_fetch_8:
4943   case Builtin::BI__sync_or_and_fetch_16:
4944     BuiltinIndex = 9;
4945     break;
4946 
4947   case Builtin::BI__sync_xor_and_fetch:
4948   case Builtin::BI__sync_xor_and_fetch_1:
4949   case Builtin::BI__sync_xor_and_fetch_2:
4950   case Builtin::BI__sync_xor_and_fetch_4:
4951   case Builtin::BI__sync_xor_and_fetch_8:
4952   case Builtin::BI__sync_xor_and_fetch_16:
4953     BuiltinIndex = 10;
4954     break;
4955 
4956   case Builtin::BI__sync_nand_and_fetch:
4957   case Builtin::BI__sync_nand_and_fetch_1:
4958   case Builtin::BI__sync_nand_and_fetch_2:
4959   case Builtin::BI__sync_nand_and_fetch_4:
4960   case Builtin::BI__sync_nand_and_fetch_8:
4961   case Builtin::BI__sync_nand_and_fetch_16:
4962     BuiltinIndex = 11;
4963     WarnAboutSemanticsChange = true;
4964     break;
4965 
4966   case Builtin::BI__sync_val_compare_and_swap:
4967   case Builtin::BI__sync_val_compare_and_swap_1:
4968   case Builtin::BI__sync_val_compare_and_swap_2:
4969   case Builtin::BI__sync_val_compare_and_swap_4:
4970   case Builtin::BI__sync_val_compare_and_swap_8:
4971   case Builtin::BI__sync_val_compare_and_swap_16:
4972     BuiltinIndex = 12;
4973     NumFixed = 2;
4974     break;
4975 
4976   case Builtin::BI__sync_bool_compare_and_swap:
4977   case Builtin::BI__sync_bool_compare_and_swap_1:
4978   case Builtin::BI__sync_bool_compare_and_swap_2:
4979   case Builtin::BI__sync_bool_compare_and_swap_4:
4980   case Builtin::BI__sync_bool_compare_and_swap_8:
4981   case Builtin::BI__sync_bool_compare_and_swap_16:
4982     BuiltinIndex = 13;
4983     NumFixed = 2;
4984     ResultType = Context.BoolTy;
4985     break;
4986 
4987   case Builtin::BI__sync_lock_test_and_set:
4988   case Builtin::BI__sync_lock_test_and_set_1:
4989   case Builtin::BI__sync_lock_test_and_set_2:
4990   case Builtin::BI__sync_lock_test_and_set_4:
4991   case Builtin::BI__sync_lock_test_and_set_8:
4992   case Builtin::BI__sync_lock_test_and_set_16:
4993     BuiltinIndex = 14;
4994     break;
4995 
4996   case Builtin::BI__sync_lock_release:
4997   case Builtin::BI__sync_lock_release_1:
4998   case Builtin::BI__sync_lock_release_2:
4999   case Builtin::BI__sync_lock_release_4:
5000   case Builtin::BI__sync_lock_release_8:
5001   case Builtin::BI__sync_lock_release_16:
5002     BuiltinIndex = 15;
5003     NumFixed = 0;
5004     ResultType = Context.VoidTy;
5005     break;
5006 
5007   case Builtin::BI__sync_swap:
5008   case Builtin::BI__sync_swap_1:
5009   case Builtin::BI__sync_swap_2:
5010   case Builtin::BI__sync_swap_4:
5011   case Builtin::BI__sync_swap_8:
5012   case Builtin::BI__sync_swap_16:
5013     BuiltinIndex = 16;
5014     break;
5015   }
5016 
5017   // Now that we know how many fixed arguments we expect, first check that we
5018   // have at least that many.
5019   if (TheCall->getNumArgs() < 1+NumFixed) {
5020     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5021         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5022         << Callee->getSourceRange();
5023     return ExprError();
5024   }
5025 
5026   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5027       << Callee->getSourceRange();
5028 
5029   if (WarnAboutSemanticsChange) {
5030     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5031         << Callee->getSourceRange();
5032   }
5033 
5034   // Get the decl for the concrete builtin from this, we can tell what the
5035   // concrete integer type we should convert to is.
5036   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5037   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5038   FunctionDecl *NewBuiltinDecl;
5039   if (NewBuiltinID == BuiltinID)
5040     NewBuiltinDecl = FDecl;
5041   else {
5042     // Perform builtin lookup to avoid redeclaring it.
5043     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5044     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5045     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5046     assert(Res.getFoundDecl());
5047     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5048     if (!NewBuiltinDecl)
5049       return ExprError();
5050   }
5051 
5052   // The first argument --- the pointer --- has a fixed type; we
5053   // deduce the types of the rest of the arguments accordingly.  Walk
5054   // the remaining arguments, converting them to the deduced value type.
5055   for (unsigned i = 0; i != NumFixed; ++i) {
5056     ExprResult Arg = TheCall->getArg(i+1);
5057 
5058     // GCC does an implicit conversion to the pointer or integer ValType.  This
5059     // can fail in some cases (1i -> int**), check for this error case now.
5060     // Initialize the argument.
5061     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5062                                                    ValType, /*consume*/ false);
5063     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5064     if (Arg.isInvalid())
5065       return ExprError();
5066 
5067     // Okay, we have something that *can* be converted to the right type.  Check
5068     // to see if there is a potentially weird extension going on here.  This can
5069     // happen when you do an atomic operation on something like an char* and
5070     // pass in 42.  The 42 gets converted to char.  This is even more strange
5071     // for things like 45.123 -> char, etc.
5072     // FIXME: Do this check.
5073     TheCall->setArg(i+1, Arg.get());
5074   }
5075 
5076   ASTContext& Context = this->getASTContext();
5077 
5078   // Create a new DeclRefExpr to refer to the new decl.
5079   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5080       Context,
5081       DRE->getQualifierLoc(),
5082       SourceLocation(),
5083       NewBuiltinDecl,
5084       /*enclosing*/ false,
5085       DRE->getLocation(),
5086       Context.BuiltinFnTy,
5087       DRE->getValueKind());
5088 
5089   // Set the callee in the CallExpr.
5090   // FIXME: This loses syntactic information.
5091   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5092   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5093                                               CK_BuiltinFnToFnPtr);
5094   TheCall->setCallee(PromotedCall.get());
5095 
5096   // Change the result type of the call to match the original value type. This
5097   // is arbitrary, but the codegen for these builtins ins design to handle it
5098   // gracefully.
5099   TheCall->setType(ResultType);
5100 
5101   return TheCallResult;
5102 }
5103 
5104 /// SemaBuiltinNontemporalOverloaded - We have a call to
5105 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5106 /// overloaded function based on the pointer type of its last argument.
5107 ///
5108 /// This function goes through and does final semantic checking for these
5109 /// builtins.
5110 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5111   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5112   DeclRefExpr *DRE =
5113       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5114   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5115   unsigned BuiltinID = FDecl->getBuiltinID();
5116   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5117           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5118          "Unexpected nontemporal load/store builtin!");
5119   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5120   unsigned numArgs = isStore ? 2 : 1;
5121 
5122   // Ensure that we have the proper number of arguments.
5123   if (checkArgCount(*this, TheCall, numArgs))
5124     return ExprError();
5125 
5126   // Inspect the last argument of the nontemporal builtin.  This should always
5127   // be a pointer type, from which we imply the type of the memory access.
5128   // Because it is a pointer type, we don't have to worry about any implicit
5129   // casts here.
5130   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5131   ExprResult PointerArgResult =
5132       DefaultFunctionArrayLvalueConversion(PointerArg);
5133 
5134   if (PointerArgResult.isInvalid())
5135     return ExprError();
5136   PointerArg = PointerArgResult.get();
5137   TheCall->setArg(numArgs - 1, PointerArg);
5138 
5139   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5140   if (!pointerType) {
5141     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5142         << PointerArg->getType() << PointerArg->getSourceRange();
5143     return ExprError();
5144   }
5145 
5146   QualType ValType = pointerType->getPointeeType();
5147 
5148   // Strip any qualifiers off ValType.
5149   ValType = ValType.getUnqualifiedType();
5150   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5151       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5152       !ValType->isVectorType()) {
5153     Diag(DRE->getBeginLoc(),
5154          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5155         << PointerArg->getType() << PointerArg->getSourceRange();
5156     return ExprError();
5157   }
5158 
5159   if (!isStore) {
5160     TheCall->setType(ValType);
5161     return TheCallResult;
5162   }
5163 
5164   ExprResult ValArg = TheCall->getArg(0);
5165   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5166       Context, ValType, /*consume*/ false);
5167   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5168   if (ValArg.isInvalid())
5169     return ExprError();
5170 
5171   TheCall->setArg(0, ValArg.get());
5172   TheCall->setType(Context.VoidTy);
5173   return TheCallResult;
5174 }
5175 
5176 /// CheckObjCString - Checks that the argument to the builtin
5177 /// CFString constructor is correct
5178 /// Note: It might also make sense to do the UTF-16 conversion here (would
5179 /// simplify the backend).
5180 bool Sema::CheckObjCString(Expr *Arg) {
5181   Arg = Arg->IgnoreParenCasts();
5182   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5183 
5184   if (!Literal || !Literal->isAscii()) {
5185     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5186         << Arg->getSourceRange();
5187     return true;
5188   }
5189 
5190   if (Literal->containsNonAsciiOrNull()) {
5191     StringRef String = Literal->getString();
5192     unsigned NumBytes = String.size();
5193     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5194     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5195     llvm::UTF16 *ToPtr = &ToBuf[0];
5196 
5197     llvm::ConversionResult Result =
5198         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5199                                  ToPtr + NumBytes, llvm::strictConversion);
5200     // Check for conversion failure.
5201     if (Result != llvm::conversionOK)
5202       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5203           << Arg->getSourceRange();
5204   }
5205   return false;
5206 }
5207 
5208 /// CheckObjCString - Checks that the format string argument to the os_log()
5209 /// and os_trace() functions is correct, and converts it to const char *.
5210 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5211   Arg = Arg->IgnoreParenCasts();
5212   auto *Literal = dyn_cast<StringLiteral>(Arg);
5213   if (!Literal) {
5214     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5215       Literal = ObjcLiteral->getString();
5216     }
5217   }
5218 
5219   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5220     return ExprError(
5221         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5222         << Arg->getSourceRange());
5223   }
5224 
5225   ExprResult Result(Literal);
5226   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5227   InitializedEntity Entity =
5228       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5229   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5230   return Result;
5231 }
5232 
5233 /// Check that the user is calling the appropriate va_start builtin for the
5234 /// target and calling convention.
5235 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5236   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5237   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5238   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5239   bool IsWindows = TT.isOSWindows();
5240   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5241   if (IsX64 || IsAArch64) {
5242     CallingConv CC = CC_C;
5243     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5244       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5245     if (IsMSVAStart) {
5246       // Don't allow this in System V ABI functions.
5247       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5248         return S.Diag(Fn->getBeginLoc(),
5249                       diag::err_ms_va_start_used_in_sysv_function);
5250     } else {
5251       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5252       // On x64 Windows, don't allow this in System V ABI functions.
5253       // (Yes, that means there's no corresponding way to support variadic
5254       // System V ABI functions on Windows.)
5255       if ((IsWindows && CC == CC_X86_64SysV) ||
5256           (!IsWindows && CC == CC_Win64))
5257         return S.Diag(Fn->getBeginLoc(),
5258                       diag::err_va_start_used_in_wrong_abi_function)
5259                << !IsWindows;
5260     }
5261     return false;
5262   }
5263 
5264   if (IsMSVAStart)
5265     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5266   return false;
5267 }
5268 
5269 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5270                                              ParmVarDecl **LastParam = nullptr) {
5271   // Determine whether the current function, block, or obj-c method is variadic
5272   // and get its parameter list.
5273   bool IsVariadic = false;
5274   ArrayRef<ParmVarDecl *> Params;
5275   DeclContext *Caller = S.CurContext;
5276   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5277     IsVariadic = Block->isVariadic();
5278     Params = Block->parameters();
5279   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5280     IsVariadic = FD->isVariadic();
5281     Params = FD->parameters();
5282   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5283     IsVariadic = MD->isVariadic();
5284     // FIXME: This isn't correct for methods (results in bogus warning).
5285     Params = MD->parameters();
5286   } else if (isa<CapturedDecl>(Caller)) {
5287     // We don't support va_start in a CapturedDecl.
5288     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5289     return true;
5290   } else {
5291     // This must be some other declcontext that parses exprs.
5292     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5293     return true;
5294   }
5295 
5296   if (!IsVariadic) {
5297     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5298     return true;
5299   }
5300 
5301   if (LastParam)
5302     *LastParam = Params.empty() ? nullptr : Params.back();
5303 
5304   return false;
5305 }
5306 
5307 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5308 /// for validity.  Emit an error and return true on failure; return false
5309 /// on success.
5310 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5311   Expr *Fn = TheCall->getCallee();
5312 
5313   if (checkVAStartABI(*this, BuiltinID, Fn))
5314     return true;
5315 
5316   if (TheCall->getNumArgs() > 2) {
5317     Diag(TheCall->getArg(2)->getBeginLoc(),
5318          diag::err_typecheck_call_too_many_args)
5319         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5320         << Fn->getSourceRange()
5321         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5322                        (*(TheCall->arg_end() - 1))->getEndLoc());
5323     return true;
5324   }
5325 
5326   if (TheCall->getNumArgs() < 2) {
5327     return Diag(TheCall->getEndLoc(),
5328                 diag::err_typecheck_call_too_few_args_at_least)
5329            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5330   }
5331 
5332   // Type-check the first argument normally.
5333   if (checkBuiltinArgument(*this, TheCall, 0))
5334     return true;
5335 
5336   // Check that the current function is variadic, and get its last parameter.
5337   ParmVarDecl *LastParam;
5338   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5339     return true;
5340 
5341   // Verify that the second argument to the builtin is the last argument of the
5342   // current function or method.
5343   bool SecondArgIsLastNamedArgument = false;
5344   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5345 
5346   // These are valid if SecondArgIsLastNamedArgument is false after the next
5347   // block.
5348   QualType Type;
5349   SourceLocation ParamLoc;
5350   bool IsCRegister = false;
5351 
5352   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5353     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5354       SecondArgIsLastNamedArgument = PV == LastParam;
5355 
5356       Type = PV->getType();
5357       ParamLoc = PV->getLocation();
5358       IsCRegister =
5359           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5360     }
5361   }
5362 
5363   if (!SecondArgIsLastNamedArgument)
5364     Diag(TheCall->getArg(1)->getBeginLoc(),
5365          diag::warn_second_arg_of_va_start_not_last_named_param);
5366   else if (IsCRegister || Type->isReferenceType() ||
5367            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5368              // Promotable integers are UB, but enumerations need a bit of
5369              // extra checking to see what their promotable type actually is.
5370              if (!Type->isPromotableIntegerType())
5371                return false;
5372              if (!Type->isEnumeralType())
5373                return true;
5374              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5375              return !(ED &&
5376                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5377            }()) {
5378     unsigned Reason = 0;
5379     if (Type->isReferenceType())  Reason = 1;
5380     else if (IsCRegister)         Reason = 2;
5381     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5382     Diag(ParamLoc, diag::note_parameter_type) << Type;
5383   }
5384 
5385   TheCall->setType(Context.VoidTy);
5386   return false;
5387 }
5388 
5389 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5390   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5391   //                 const char *named_addr);
5392 
5393   Expr *Func = Call->getCallee();
5394 
5395   if (Call->getNumArgs() < 3)
5396     return Diag(Call->getEndLoc(),
5397                 diag::err_typecheck_call_too_few_args_at_least)
5398            << 0 /*function call*/ << 3 << Call->getNumArgs();
5399 
5400   // Type-check the first argument normally.
5401   if (checkBuiltinArgument(*this, Call, 0))
5402     return true;
5403 
5404   // Check that the current function is variadic.
5405   if (checkVAStartIsInVariadicFunction(*this, Func))
5406     return true;
5407 
5408   // __va_start on Windows does not validate the parameter qualifiers
5409 
5410   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5411   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5412 
5413   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5414   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5415 
5416   const QualType &ConstCharPtrTy =
5417       Context.getPointerType(Context.CharTy.withConst());
5418   if (!Arg1Ty->isPointerType() ||
5419       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5420     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5421         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5422         << 0                                      /* qualifier difference */
5423         << 3                                      /* parameter mismatch */
5424         << 2 << Arg1->getType() << ConstCharPtrTy;
5425 
5426   const QualType SizeTy = Context.getSizeType();
5427   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5428     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5429         << Arg2->getType() << SizeTy << 1 /* different class */
5430         << 0                              /* qualifier difference */
5431         << 3                              /* parameter mismatch */
5432         << 3 << Arg2->getType() << SizeTy;
5433 
5434   return false;
5435 }
5436 
5437 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5438 /// friends.  This is declared to take (...), so we have to check everything.
5439 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5440   if (TheCall->getNumArgs() < 2)
5441     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5442            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5443   if (TheCall->getNumArgs() > 2)
5444     return Diag(TheCall->getArg(2)->getBeginLoc(),
5445                 diag::err_typecheck_call_too_many_args)
5446            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5447            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5448                           (*(TheCall->arg_end() - 1))->getEndLoc());
5449 
5450   ExprResult OrigArg0 = TheCall->getArg(0);
5451   ExprResult OrigArg1 = TheCall->getArg(1);
5452 
5453   // Do standard promotions between the two arguments, returning their common
5454   // type.
5455   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5456   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5457     return true;
5458 
5459   // Make sure any conversions are pushed back into the call; this is
5460   // type safe since unordered compare builtins are declared as "_Bool
5461   // foo(...)".
5462   TheCall->setArg(0, OrigArg0.get());
5463   TheCall->setArg(1, OrigArg1.get());
5464 
5465   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5466     return false;
5467 
5468   // If the common type isn't a real floating type, then the arguments were
5469   // invalid for this operation.
5470   if (Res.isNull() || !Res->isRealFloatingType())
5471     return Diag(OrigArg0.get()->getBeginLoc(),
5472                 diag::err_typecheck_call_invalid_ordered_compare)
5473            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5474            << SourceRange(OrigArg0.get()->getBeginLoc(),
5475                           OrigArg1.get()->getEndLoc());
5476 
5477   return false;
5478 }
5479 
5480 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5481 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5482 /// to check everything. We expect the last argument to be a floating point
5483 /// value.
5484 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5485   if (TheCall->getNumArgs() < NumArgs)
5486     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5487            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5488   if (TheCall->getNumArgs() > NumArgs)
5489     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5490                 diag::err_typecheck_call_too_many_args)
5491            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5492            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5493                           (*(TheCall->arg_end() - 1))->getEndLoc());
5494 
5495   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5496 
5497   if (OrigArg->isTypeDependent())
5498     return false;
5499 
5500   // This operation requires a non-_Complex floating-point number.
5501   if (!OrigArg->getType()->isRealFloatingType())
5502     return Diag(OrigArg->getBeginLoc(),
5503                 diag::err_typecheck_call_invalid_unary_fp)
5504            << OrigArg->getType() << OrigArg->getSourceRange();
5505 
5506   // If this is an implicit conversion from float -> float, double, or
5507   // long double, remove it.
5508   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5509     // Only remove standard FloatCasts, leaving other casts inplace
5510     if (Cast->getCastKind() == CK_FloatingCast) {
5511       Expr *CastArg = Cast->getSubExpr();
5512       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5513         assert(
5514             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5515              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5516              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5517             "promotion from float to either float, double, or long double is "
5518             "the only expected cast here");
5519         Cast->setSubExpr(nullptr);
5520         TheCall->setArg(NumArgs-1, CastArg);
5521       }
5522     }
5523   }
5524 
5525   return false;
5526 }
5527 
5528 // Customized Sema Checking for VSX builtins that have the following signature:
5529 // vector [...] builtinName(vector [...], vector [...], const int);
5530 // Which takes the same type of vectors (any legal vector type) for the first
5531 // two arguments and takes compile time constant for the third argument.
5532 // Example builtins are :
5533 // vector double vec_xxpermdi(vector double, vector double, int);
5534 // vector short vec_xxsldwi(vector short, vector short, int);
5535 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5536   unsigned ExpectedNumArgs = 3;
5537   if (TheCall->getNumArgs() < ExpectedNumArgs)
5538     return Diag(TheCall->getEndLoc(),
5539                 diag::err_typecheck_call_too_few_args_at_least)
5540            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5541            << TheCall->getSourceRange();
5542 
5543   if (TheCall->getNumArgs() > ExpectedNumArgs)
5544     return Diag(TheCall->getEndLoc(),
5545                 diag::err_typecheck_call_too_many_args_at_most)
5546            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5547            << TheCall->getSourceRange();
5548 
5549   // Check the third argument is a compile time constant
5550   llvm::APSInt Value;
5551   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5552     return Diag(TheCall->getBeginLoc(),
5553                 diag::err_vsx_builtin_nonconstant_argument)
5554            << 3 /* argument index */ << TheCall->getDirectCallee()
5555            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5556                           TheCall->getArg(2)->getEndLoc());
5557 
5558   QualType Arg1Ty = TheCall->getArg(0)->getType();
5559   QualType Arg2Ty = TheCall->getArg(1)->getType();
5560 
5561   // Check the type of argument 1 and argument 2 are vectors.
5562   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5563   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5564       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5565     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5566            << TheCall->getDirectCallee()
5567            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5568                           TheCall->getArg(1)->getEndLoc());
5569   }
5570 
5571   // Check the first two arguments are the same type.
5572   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5573     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5574            << TheCall->getDirectCallee()
5575            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5576                           TheCall->getArg(1)->getEndLoc());
5577   }
5578 
5579   // When default clang type checking is turned off and the customized type
5580   // checking is used, the returning type of the function must be explicitly
5581   // set. Otherwise it is _Bool by default.
5582   TheCall->setType(Arg1Ty);
5583 
5584   return false;
5585 }
5586 
5587 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5588 // This is declared to take (...), so we have to check everything.
5589 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5590   if (TheCall->getNumArgs() < 2)
5591     return ExprError(Diag(TheCall->getEndLoc(),
5592                           diag::err_typecheck_call_too_few_args_at_least)
5593                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5594                      << TheCall->getSourceRange());
5595 
5596   // Determine which of the following types of shufflevector we're checking:
5597   // 1) unary, vector mask: (lhs, mask)
5598   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5599   QualType resType = TheCall->getArg(0)->getType();
5600   unsigned numElements = 0;
5601 
5602   if (!TheCall->getArg(0)->isTypeDependent() &&
5603       !TheCall->getArg(1)->isTypeDependent()) {
5604     QualType LHSType = TheCall->getArg(0)->getType();
5605     QualType RHSType = TheCall->getArg(1)->getType();
5606 
5607     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5608       return ExprError(
5609           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5610           << TheCall->getDirectCallee()
5611           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5612                          TheCall->getArg(1)->getEndLoc()));
5613 
5614     numElements = LHSType->getAs<VectorType>()->getNumElements();
5615     unsigned numResElements = TheCall->getNumArgs() - 2;
5616 
5617     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5618     // with mask.  If so, verify that RHS is an integer vector type with the
5619     // same number of elts as lhs.
5620     if (TheCall->getNumArgs() == 2) {
5621       if (!RHSType->hasIntegerRepresentation() ||
5622           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5623         return ExprError(Diag(TheCall->getBeginLoc(),
5624                               diag::err_vec_builtin_incompatible_vector)
5625                          << TheCall->getDirectCallee()
5626                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5627                                         TheCall->getArg(1)->getEndLoc()));
5628     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5629       return ExprError(Diag(TheCall->getBeginLoc(),
5630                             diag::err_vec_builtin_incompatible_vector)
5631                        << TheCall->getDirectCallee()
5632                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5633                                       TheCall->getArg(1)->getEndLoc()));
5634     } else if (numElements != numResElements) {
5635       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5636       resType = Context.getVectorType(eltType, numResElements,
5637                                       VectorType::GenericVector);
5638     }
5639   }
5640 
5641   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5642     if (TheCall->getArg(i)->isTypeDependent() ||
5643         TheCall->getArg(i)->isValueDependent())
5644       continue;
5645 
5646     llvm::APSInt Result(32);
5647     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5648       return ExprError(Diag(TheCall->getBeginLoc(),
5649                             diag::err_shufflevector_nonconstant_argument)
5650                        << TheCall->getArg(i)->getSourceRange());
5651 
5652     // Allow -1 which will be translated to undef in the IR.
5653     if (Result.isSigned() && Result.isAllOnesValue())
5654       continue;
5655 
5656     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5657       return ExprError(Diag(TheCall->getBeginLoc(),
5658                             diag::err_shufflevector_argument_too_large)
5659                        << TheCall->getArg(i)->getSourceRange());
5660   }
5661 
5662   SmallVector<Expr*, 32> exprs;
5663 
5664   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5665     exprs.push_back(TheCall->getArg(i));
5666     TheCall->setArg(i, nullptr);
5667   }
5668 
5669   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5670                                          TheCall->getCallee()->getBeginLoc(),
5671                                          TheCall->getRParenLoc());
5672 }
5673 
5674 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5675 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5676                                        SourceLocation BuiltinLoc,
5677                                        SourceLocation RParenLoc) {
5678   ExprValueKind VK = VK_RValue;
5679   ExprObjectKind OK = OK_Ordinary;
5680   QualType DstTy = TInfo->getType();
5681   QualType SrcTy = E->getType();
5682 
5683   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5684     return ExprError(Diag(BuiltinLoc,
5685                           diag::err_convertvector_non_vector)
5686                      << E->getSourceRange());
5687   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5688     return ExprError(Diag(BuiltinLoc,
5689                           diag::err_convertvector_non_vector_type));
5690 
5691   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5692     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5693     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5694     if (SrcElts != DstElts)
5695       return ExprError(Diag(BuiltinLoc,
5696                             diag::err_convertvector_incompatible_vector)
5697                        << E->getSourceRange());
5698   }
5699 
5700   return new (Context)
5701       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5702 }
5703 
5704 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5705 // This is declared to take (const void*, ...) and can take two
5706 // optional constant int args.
5707 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5708   unsigned NumArgs = TheCall->getNumArgs();
5709 
5710   if (NumArgs > 3)
5711     return Diag(TheCall->getEndLoc(),
5712                 diag::err_typecheck_call_too_many_args_at_most)
5713            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5714 
5715   // Argument 0 is checked for us and the remaining arguments must be
5716   // constant integers.
5717   for (unsigned i = 1; i != NumArgs; ++i)
5718     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5719       return true;
5720 
5721   return false;
5722 }
5723 
5724 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5725 // __assume does not evaluate its arguments, and should warn if its argument
5726 // has side effects.
5727 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5728   Expr *Arg = TheCall->getArg(0);
5729   if (Arg->isInstantiationDependent()) return false;
5730 
5731   if (Arg->HasSideEffects(Context))
5732     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5733         << Arg->getSourceRange()
5734         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5735 
5736   return false;
5737 }
5738 
5739 /// Handle __builtin_alloca_with_align. This is declared
5740 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5741 /// than 8.
5742 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5743   // The alignment must be a constant integer.
5744   Expr *Arg = TheCall->getArg(1);
5745 
5746   // We can't check the value of a dependent argument.
5747   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5748     if (const auto *UE =
5749             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5750       if (UE->getKind() == UETT_AlignOf ||
5751           UE->getKind() == UETT_PreferredAlignOf)
5752         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5753             << Arg->getSourceRange();
5754 
5755     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5756 
5757     if (!Result.isPowerOf2())
5758       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5759              << Arg->getSourceRange();
5760 
5761     if (Result < Context.getCharWidth())
5762       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5763              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5764 
5765     if (Result > std::numeric_limits<int32_t>::max())
5766       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5767              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5768   }
5769 
5770   return false;
5771 }
5772 
5773 /// Handle __builtin_assume_aligned. This is declared
5774 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5775 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5776   unsigned NumArgs = TheCall->getNumArgs();
5777 
5778   if (NumArgs > 3)
5779     return Diag(TheCall->getEndLoc(),
5780                 diag::err_typecheck_call_too_many_args_at_most)
5781            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5782 
5783   // The alignment must be a constant integer.
5784   Expr *Arg = TheCall->getArg(1);
5785 
5786   // We can't check the value of a dependent argument.
5787   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5788     llvm::APSInt Result;
5789     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5790       return true;
5791 
5792     if (!Result.isPowerOf2())
5793       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5794              << Arg->getSourceRange();
5795   }
5796 
5797   if (NumArgs > 2) {
5798     ExprResult Arg(TheCall->getArg(2));
5799     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5800       Context.getSizeType(), false);
5801     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5802     if (Arg.isInvalid()) return true;
5803     TheCall->setArg(2, Arg.get());
5804   }
5805 
5806   return false;
5807 }
5808 
5809 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5810   unsigned BuiltinID =
5811       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5812   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5813 
5814   unsigned NumArgs = TheCall->getNumArgs();
5815   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5816   if (NumArgs < NumRequiredArgs) {
5817     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5818            << 0 /* function call */ << NumRequiredArgs << NumArgs
5819            << TheCall->getSourceRange();
5820   }
5821   if (NumArgs >= NumRequiredArgs + 0x100) {
5822     return Diag(TheCall->getEndLoc(),
5823                 diag::err_typecheck_call_too_many_args_at_most)
5824            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5825            << TheCall->getSourceRange();
5826   }
5827   unsigned i = 0;
5828 
5829   // For formatting call, check buffer arg.
5830   if (!IsSizeCall) {
5831     ExprResult Arg(TheCall->getArg(i));
5832     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5833         Context, Context.VoidPtrTy, false);
5834     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5835     if (Arg.isInvalid())
5836       return true;
5837     TheCall->setArg(i, Arg.get());
5838     i++;
5839   }
5840 
5841   // Check string literal arg.
5842   unsigned FormatIdx = i;
5843   {
5844     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5845     if (Arg.isInvalid())
5846       return true;
5847     TheCall->setArg(i, Arg.get());
5848     i++;
5849   }
5850 
5851   // Make sure variadic args are scalar.
5852   unsigned FirstDataArg = i;
5853   while (i < NumArgs) {
5854     ExprResult Arg = DefaultVariadicArgumentPromotion(
5855         TheCall->getArg(i), VariadicFunction, nullptr);
5856     if (Arg.isInvalid())
5857       return true;
5858     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5859     if (ArgSize.getQuantity() >= 0x100) {
5860       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5861              << i << (int)ArgSize.getQuantity() << 0xff
5862              << TheCall->getSourceRange();
5863     }
5864     TheCall->setArg(i, Arg.get());
5865     i++;
5866   }
5867 
5868   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5869   // call to avoid duplicate diagnostics.
5870   if (!IsSizeCall) {
5871     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5872     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5873     bool Success = CheckFormatArguments(
5874         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5875         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5876         CheckedVarArgs);
5877     if (!Success)
5878       return true;
5879   }
5880 
5881   if (IsSizeCall) {
5882     TheCall->setType(Context.getSizeType());
5883   } else {
5884     TheCall->setType(Context.VoidPtrTy);
5885   }
5886   return false;
5887 }
5888 
5889 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5890 /// TheCall is a constant expression.
5891 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5892                                   llvm::APSInt &Result) {
5893   Expr *Arg = TheCall->getArg(ArgNum);
5894   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5895   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5896 
5897   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5898 
5899   if (!Arg->isIntegerConstantExpr(Result, Context))
5900     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5901            << FDecl->getDeclName() << Arg->getSourceRange();
5902 
5903   return false;
5904 }
5905 
5906 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5907 /// TheCall is a constant expression in the range [Low, High].
5908 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5909                                        int Low, int High, bool RangeIsError) {
5910   llvm::APSInt Result;
5911 
5912   // We can't check the value of a dependent argument.
5913   Expr *Arg = TheCall->getArg(ArgNum);
5914   if (Arg->isTypeDependent() || Arg->isValueDependent())
5915     return false;
5916 
5917   // Check constant-ness first.
5918   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5919     return true;
5920 
5921   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5922     if (RangeIsError)
5923       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5924              << Result.toString(10) << Low << High << Arg->getSourceRange();
5925     else
5926       // Defer the warning until we know if the code will be emitted so that
5927       // dead code can ignore this.
5928       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5929                           PDiag(diag::warn_argument_invalid_range)
5930                               << Result.toString(10) << Low << High
5931                               << Arg->getSourceRange());
5932   }
5933 
5934   return false;
5935 }
5936 
5937 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5938 /// TheCall is a constant expression is a multiple of Num..
5939 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5940                                           unsigned Num) {
5941   llvm::APSInt Result;
5942 
5943   // We can't check the value of a dependent argument.
5944   Expr *Arg = TheCall->getArg(ArgNum);
5945   if (Arg->isTypeDependent() || Arg->isValueDependent())
5946     return false;
5947 
5948   // Check constant-ness first.
5949   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5950     return true;
5951 
5952   if (Result.getSExtValue() % Num != 0)
5953     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5954            << Num << Arg->getSourceRange();
5955 
5956   return false;
5957 }
5958 
5959 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5960 /// TheCall is an ARM/AArch64 special register string literal.
5961 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5962                                     int ArgNum, unsigned ExpectedFieldNum,
5963                                     bool AllowName) {
5964   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5965                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5966                       BuiltinID == ARM::BI__builtin_arm_rsr ||
5967                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
5968                       BuiltinID == ARM::BI__builtin_arm_wsr ||
5969                       BuiltinID == ARM::BI__builtin_arm_wsrp;
5970   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5971                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5972                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
5973                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5974                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
5975                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
5976   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5977 
5978   // We can't check the value of a dependent argument.
5979   Expr *Arg = TheCall->getArg(ArgNum);
5980   if (Arg->isTypeDependent() || Arg->isValueDependent())
5981     return false;
5982 
5983   // Check if the argument is a string literal.
5984   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5985     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
5986            << Arg->getSourceRange();
5987 
5988   // Check the type of special register given.
5989   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5990   SmallVector<StringRef, 6> Fields;
5991   Reg.split(Fields, ":");
5992 
5993   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5994     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
5995            << Arg->getSourceRange();
5996 
5997   // If the string is the name of a register then we cannot check that it is
5998   // valid here but if the string is of one the forms described in ACLE then we
5999   // can check that the supplied fields are integers and within the valid
6000   // ranges.
6001   if (Fields.size() > 1) {
6002     bool FiveFields = Fields.size() == 5;
6003 
6004     bool ValidString = true;
6005     if (IsARMBuiltin) {
6006       ValidString &= Fields[0].startswith_lower("cp") ||
6007                      Fields[0].startswith_lower("p");
6008       if (ValidString)
6009         Fields[0] =
6010           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6011 
6012       ValidString &= Fields[2].startswith_lower("c");
6013       if (ValidString)
6014         Fields[2] = Fields[2].drop_front(1);
6015 
6016       if (FiveFields) {
6017         ValidString &= Fields[3].startswith_lower("c");
6018         if (ValidString)
6019           Fields[3] = Fields[3].drop_front(1);
6020       }
6021     }
6022 
6023     SmallVector<int, 5> Ranges;
6024     if (FiveFields)
6025       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6026     else
6027       Ranges.append({15, 7, 15});
6028 
6029     for (unsigned i=0; i<Fields.size(); ++i) {
6030       int IntField;
6031       ValidString &= !Fields[i].getAsInteger(10, IntField);
6032       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6033     }
6034 
6035     if (!ValidString)
6036       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6037              << Arg->getSourceRange();
6038   } else if (IsAArch64Builtin && Fields.size() == 1) {
6039     // If the register name is one of those that appear in the condition below
6040     // and the special register builtin being used is one of the write builtins,
6041     // then we require that the argument provided for writing to the register
6042     // is an integer constant expression. This is because it will be lowered to
6043     // an MSR (immediate) instruction, so we need to know the immediate at
6044     // compile time.
6045     if (TheCall->getNumArgs() != 2)
6046       return false;
6047 
6048     std::string RegLower = Reg.lower();
6049     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6050         RegLower != "pan" && RegLower != "uao")
6051       return false;
6052 
6053     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6054   }
6055 
6056   return false;
6057 }
6058 
6059 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6060 /// This checks that the target supports __builtin_longjmp and
6061 /// that val is a constant 1.
6062 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6063   if (!Context.getTargetInfo().hasSjLjLowering())
6064     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6065            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6066 
6067   Expr *Arg = TheCall->getArg(1);
6068   llvm::APSInt Result;
6069 
6070   // TODO: This is less than ideal. Overload this to take a value.
6071   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6072     return true;
6073 
6074   if (Result != 1)
6075     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6076            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6077 
6078   return false;
6079 }
6080 
6081 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6082 /// This checks that the target supports __builtin_setjmp.
6083 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6084   if (!Context.getTargetInfo().hasSjLjLowering())
6085     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6086            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6087   return false;
6088 }
6089 
6090 namespace {
6091 
6092 class UncoveredArgHandler {
6093   enum { Unknown = -1, AllCovered = -2 };
6094 
6095   signed FirstUncoveredArg = Unknown;
6096   SmallVector<const Expr *, 4> DiagnosticExprs;
6097 
6098 public:
6099   UncoveredArgHandler() = default;
6100 
6101   bool hasUncoveredArg() const {
6102     return (FirstUncoveredArg >= 0);
6103   }
6104 
6105   unsigned getUncoveredArg() const {
6106     assert(hasUncoveredArg() && "no uncovered argument");
6107     return FirstUncoveredArg;
6108   }
6109 
6110   void setAllCovered() {
6111     // A string has been found with all arguments covered, so clear out
6112     // the diagnostics.
6113     DiagnosticExprs.clear();
6114     FirstUncoveredArg = AllCovered;
6115   }
6116 
6117   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6118     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6119 
6120     // Don't update if a previous string covers all arguments.
6121     if (FirstUncoveredArg == AllCovered)
6122       return;
6123 
6124     // UncoveredArgHandler tracks the highest uncovered argument index
6125     // and with it all the strings that match this index.
6126     if (NewFirstUncoveredArg == FirstUncoveredArg)
6127       DiagnosticExprs.push_back(StrExpr);
6128     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6129       DiagnosticExprs.clear();
6130       DiagnosticExprs.push_back(StrExpr);
6131       FirstUncoveredArg = NewFirstUncoveredArg;
6132     }
6133   }
6134 
6135   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6136 };
6137 
6138 enum StringLiteralCheckType {
6139   SLCT_NotALiteral,
6140   SLCT_UncheckedLiteral,
6141   SLCT_CheckedLiteral
6142 };
6143 
6144 } // namespace
6145 
6146 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6147                                      BinaryOperatorKind BinOpKind,
6148                                      bool AddendIsRight) {
6149   unsigned BitWidth = Offset.getBitWidth();
6150   unsigned AddendBitWidth = Addend.getBitWidth();
6151   // There might be negative interim results.
6152   if (Addend.isUnsigned()) {
6153     Addend = Addend.zext(++AddendBitWidth);
6154     Addend.setIsSigned(true);
6155   }
6156   // Adjust the bit width of the APSInts.
6157   if (AddendBitWidth > BitWidth) {
6158     Offset = Offset.sext(AddendBitWidth);
6159     BitWidth = AddendBitWidth;
6160   } else if (BitWidth > AddendBitWidth) {
6161     Addend = Addend.sext(BitWidth);
6162   }
6163 
6164   bool Ov = false;
6165   llvm::APSInt ResOffset = Offset;
6166   if (BinOpKind == BO_Add)
6167     ResOffset = Offset.sadd_ov(Addend, Ov);
6168   else {
6169     assert(AddendIsRight && BinOpKind == BO_Sub &&
6170            "operator must be add or sub with addend on the right");
6171     ResOffset = Offset.ssub_ov(Addend, Ov);
6172   }
6173 
6174   // We add an offset to a pointer here so we should support an offset as big as
6175   // possible.
6176   if (Ov) {
6177     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6178            "index (intermediate) result too big");
6179     Offset = Offset.sext(2 * BitWidth);
6180     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6181     return;
6182   }
6183 
6184   Offset = ResOffset;
6185 }
6186 
6187 namespace {
6188 
6189 // This is a wrapper class around StringLiteral to support offsetted string
6190 // literals as format strings. It takes the offset into account when returning
6191 // the string and its length or the source locations to display notes correctly.
6192 class FormatStringLiteral {
6193   const StringLiteral *FExpr;
6194   int64_t Offset;
6195 
6196  public:
6197   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6198       : FExpr(fexpr), Offset(Offset) {}
6199 
6200   StringRef getString() const {
6201     return FExpr->getString().drop_front(Offset);
6202   }
6203 
6204   unsigned getByteLength() const {
6205     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6206   }
6207 
6208   unsigned getLength() const { return FExpr->getLength() - Offset; }
6209   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6210 
6211   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6212 
6213   QualType getType() const { return FExpr->getType(); }
6214 
6215   bool isAscii() const { return FExpr->isAscii(); }
6216   bool isWide() const { return FExpr->isWide(); }
6217   bool isUTF8() const { return FExpr->isUTF8(); }
6218   bool isUTF16() const { return FExpr->isUTF16(); }
6219   bool isUTF32() const { return FExpr->isUTF32(); }
6220   bool isPascal() const { return FExpr->isPascal(); }
6221 
6222   SourceLocation getLocationOfByte(
6223       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6224       const TargetInfo &Target, unsigned *StartToken = nullptr,
6225       unsigned *StartTokenByteOffset = nullptr) const {
6226     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6227                                     StartToken, StartTokenByteOffset);
6228   }
6229 
6230   SourceLocation getBeginLoc() const LLVM_READONLY {
6231     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6232   }
6233 
6234   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6235 };
6236 
6237 }  // namespace
6238 
6239 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6240                               const Expr *OrigFormatExpr,
6241                               ArrayRef<const Expr *> Args,
6242                               bool HasVAListArg, unsigned format_idx,
6243                               unsigned firstDataArg,
6244                               Sema::FormatStringType Type,
6245                               bool inFunctionCall,
6246                               Sema::VariadicCallType CallType,
6247                               llvm::SmallBitVector &CheckedVarArgs,
6248                               UncoveredArgHandler &UncoveredArg);
6249 
6250 // Determine if an expression is a string literal or constant string.
6251 // If this function returns false on the arguments to a function expecting a
6252 // format string, we will usually need to emit a warning.
6253 // True string literals are then checked by CheckFormatString.
6254 static StringLiteralCheckType
6255 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6256                       bool HasVAListArg, unsigned format_idx,
6257                       unsigned firstDataArg, Sema::FormatStringType Type,
6258                       Sema::VariadicCallType CallType, bool InFunctionCall,
6259                       llvm::SmallBitVector &CheckedVarArgs,
6260                       UncoveredArgHandler &UncoveredArg,
6261                       llvm::APSInt Offset) {
6262  tryAgain:
6263   assert(Offset.isSigned() && "invalid offset");
6264 
6265   if (E->isTypeDependent() || E->isValueDependent())
6266     return SLCT_NotALiteral;
6267 
6268   E = E->IgnoreParenCasts();
6269 
6270   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6271     // Technically -Wformat-nonliteral does not warn about this case.
6272     // The behavior of printf and friends in this case is implementation
6273     // dependent.  Ideally if the format string cannot be null then
6274     // it should have a 'nonnull' attribute in the function prototype.
6275     return SLCT_UncheckedLiteral;
6276 
6277   switch (E->getStmtClass()) {
6278   case Stmt::BinaryConditionalOperatorClass:
6279   case Stmt::ConditionalOperatorClass: {
6280     // The expression is a literal if both sub-expressions were, and it was
6281     // completely checked only if both sub-expressions were checked.
6282     const AbstractConditionalOperator *C =
6283         cast<AbstractConditionalOperator>(E);
6284 
6285     // Determine whether it is necessary to check both sub-expressions, for
6286     // example, because the condition expression is a constant that can be
6287     // evaluated at compile time.
6288     bool CheckLeft = true, CheckRight = true;
6289 
6290     bool Cond;
6291     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6292       if (Cond)
6293         CheckRight = false;
6294       else
6295         CheckLeft = false;
6296     }
6297 
6298     // We need to maintain the offsets for the right and the left hand side
6299     // separately to check if every possible indexed expression is a valid
6300     // string literal. They might have different offsets for different string
6301     // literals in the end.
6302     StringLiteralCheckType Left;
6303     if (!CheckLeft)
6304       Left = SLCT_UncheckedLiteral;
6305     else {
6306       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6307                                    HasVAListArg, format_idx, firstDataArg,
6308                                    Type, CallType, InFunctionCall,
6309                                    CheckedVarArgs, UncoveredArg, Offset);
6310       if (Left == SLCT_NotALiteral || !CheckRight) {
6311         return Left;
6312       }
6313     }
6314 
6315     StringLiteralCheckType Right =
6316         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6317                               HasVAListArg, format_idx, firstDataArg,
6318                               Type, CallType, InFunctionCall, CheckedVarArgs,
6319                               UncoveredArg, Offset);
6320 
6321     return (CheckLeft && Left < Right) ? Left : Right;
6322   }
6323 
6324   case Stmt::ImplicitCastExprClass:
6325     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6326     goto tryAgain;
6327 
6328   case Stmt::OpaqueValueExprClass:
6329     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6330       E = src;
6331       goto tryAgain;
6332     }
6333     return SLCT_NotALiteral;
6334 
6335   case Stmt::PredefinedExprClass:
6336     // While __func__, etc., are technically not string literals, they
6337     // cannot contain format specifiers and thus are not a security
6338     // liability.
6339     return SLCT_UncheckedLiteral;
6340 
6341   case Stmt::DeclRefExprClass: {
6342     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6343 
6344     // As an exception, do not flag errors for variables binding to
6345     // const string literals.
6346     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6347       bool isConstant = false;
6348       QualType T = DR->getType();
6349 
6350       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6351         isConstant = AT->getElementType().isConstant(S.Context);
6352       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6353         isConstant = T.isConstant(S.Context) &&
6354                      PT->getPointeeType().isConstant(S.Context);
6355       } else if (T->isObjCObjectPointerType()) {
6356         // In ObjC, there is usually no "const ObjectPointer" type,
6357         // so don't check if the pointee type is constant.
6358         isConstant = T.isConstant(S.Context);
6359       }
6360 
6361       if (isConstant) {
6362         if (const Expr *Init = VD->getAnyInitializer()) {
6363           // Look through initializers like const char c[] = { "foo" }
6364           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6365             if (InitList->isStringLiteralInit())
6366               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6367           }
6368           return checkFormatStringExpr(S, Init, Args,
6369                                        HasVAListArg, format_idx,
6370                                        firstDataArg, Type, CallType,
6371                                        /*InFunctionCall*/ false, CheckedVarArgs,
6372                                        UncoveredArg, Offset);
6373         }
6374       }
6375 
6376       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6377       // special check to see if the format string is a function parameter
6378       // of the function calling the printf function.  If the function
6379       // has an attribute indicating it is a printf-like function, then we
6380       // should suppress warnings concerning non-literals being used in a call
6381       // to a vprintf function.  For example:
6382       //
6383       // void
6384       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6385       //      va_list ap;
6386       //      va_start(ap, fmt);
6387       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6388       //      ...
6389       // }
6390       if (HasVAListArg) {
6391         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6392           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6393             int PVIndex = PV->getFunctionScopeIndex() + 1;
6394             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6395               // adjust for implicit parameter
6396               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6397                 if (MD->isInstance())
6398                   ++PVIndex;
6399               // We also check if the formats are compatible.
6400               // We can't pass a 'scanf' string to a 'printf' function.
6401               if (PVIndex == PVFormat->getFormatIdx() &&
6402                   Type == S.GetFormatStringType(PVFormat))
6403                 return SLCT_UncheckedLiteral;
6404             }
6405           }
6406         }
6407       }
6408     }
6409 
6410     return SLCT_NotALiteral;
6411   }
6412 
6413   case Stmt::CallExprClass:
6414   case Stmt::CXXMemberCallExprClass: {
6415     const CallExpr *CE = cast<CallExpr>(E);
6416     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6417       bool IsFirst = true;
6418       StringLiteralCheckType CommonResult;
6419       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6420         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6421         StringLiteralCheckType Result = checkFormatStringExpr(
6422             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6423             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6424         if (IsFirst) {
6425           CommonResult = Result;
6426           IsFirst = false;
6427         }
6428       }
6429       if (!IsFirst)
6430         return CommonResult;
6431 
6432       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6433         unsigned BuiltinID = FD->getBuiltinID();
6434         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6435             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6436           const Expr *Arg = CE->getArg(0);
6437           return checkFormatStringExpr(S, Arg, Args,
6438                                        HasVAListArg, format_idx,
6439                                        firstDataArg, Type, CallType,
6440                                        InFunctionCall, CheckedVarArgs,
6441                                        UncoveredArg, Offset);
6442         }
6443       }
6444     }
6445 
6446     return SLCT_NotALiteral;
6447   }
6448   case Stmt::ObjCMessageExprClass: {
6449     const auto *ME = cast<ObjCMessageExpr>(E);
6450     if (const auto *ND = ME->getMethodDecl()) {
6451       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6452         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6453         return checkFormatStringExpr(
6454             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6455             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6456       }
6457     }
6458 
6459     return SLCT_NotALiteral;
6460   }
6461   case Stmt::ObjCStringLiteralClass:
6462   case Stmt::StringLiteralClass: {
6463     const StringLiteral *StrE = nullptr;
6464 
6465     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6466       StrE = ObjCFExpr->getString();
6467     else
6468       StrE = cast<StringLiteral>(E);
6469 
6470     if (StrE) {
6471       if (Offset.isNegative() || Offset > StrE->getLength()) {
6472         // TODO: It would be better to have an explicit warning for out of
6473         // bounds literals.
6474         return SLCT_NotALiteral;
6475       }
6476       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6477       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6478                         firstDataArg, Type, InFunctionCall, CallType,
6479                         CheckedVarArgs, UncoveredArg);
6480       return SLCT_CheckedLiteral;
6481     }
6482 
6483     return SLCT_NotALiteral;
6484   }
6485   case Stmt::BinaryOperatorClass: {
6486     llvm::APSInt LResult;
6487     llvm::APSInt RResult;
6488 
6489     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6490 
6491     // A string literal + an int offset is still a string literal.
6492     if (BinOp->isAdditiveOp()) {
6493       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6494       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6495 
6496       if (LIsInt != RIsInt) {
6497         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6498 
6499         if (LIsInt) {
6500           if (BinOpKind == BO_Add) {
6501             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
6502             E = BinOp->getRHS();
6503             goto tryAgain;
6504           }
6505         } else {
6506           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
6507           E = BinOp->getLHS();
6508           goto tryAgain;
6509         }
6510       }
6511     }
6512 
6513     return SLCT_NotALiteral;
6514   }
6515   case Stmt::UnaryOperatorClass: {
6516     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6517     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6518     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6519       llvm::APSInt IndexResult;
6520       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6521         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
6522         E = ASE->getBase();
6523         goto tryAgain;
6524       }
6525     }
6526 
6527     return SLCT_NotALiteral;
6528   }
6529 
6530   default:
6531     return SLCT_NotALiteral;
6532   }
6533 }
6534 
6535 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6536   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6537       .Case("scanf", FST_Scanf)
6538       .Cases("printf", "printf0", FST_Printf)
6539       .Cases("NSString", "CFString", FST_NSString)
6540       .Case("strftime", FST_Strftime)
6541       .Case("strfmon", FST_Strfmon)
6542       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6543       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6544       .Case("os_trace", FST_OSLog)
6545       .Case("os_log", FST_OSLog)
6546       .Default(FST_Unknown);
6547 }
6548 
6549 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6550 /// functions) for correct use of format strings.
6551 /// Returns true if a format string has been fully checked.
6552 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6553                                 ArrayRef<const Expr *> Args,
6554                                 bool IsCXXMember,
6555                                 VariadicCallType CallType,
6556                                 SourceLocation Loc, SourceRange Range,
6557                                 llvm::SmallBitVector &CheckedVarArgs) {
6558   FormatStringInfo FSI;
6559   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6560     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6561                                 FSI.FirstDataArg, GetFormatStringType(Format),
6562                                 CallType, Loc, Range, CheckedVarArgs);
6563   return false;
6564 }
6565 
6566 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6567                                 bool HasVAListArg, unsigned format_idx,
6568                                 unsigned firstDataArg, FormatStringType Type,
6569                                 VariadicCallType CallType,
6570                                 SourceLocation Loc, SourceRange Range,
6571                                 llvm::SmallBitVector &CheckedVarArgs) {
6572   // CHECK: printf/scanf-like function is called with no format string.
6573   if (format_idx >= Args.size()) {
6574     Diag(Loc, diag::warn_missing_format_string) << Range;
6575     return false;
6576   }
6577 
6578   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6579 
6580   // CHECK: format string is not a string literal.
6581   //
6582   // Dynamically generated format strings are difficult to
6583   // automatically vet at compile time.  Requiring that format strings
6584   // are string literals: (1) permits the checking of format strings by
6585   // the compiler and thereby (2) can practically remove the source of
6586   // many format string exploits.
6587 
6588   // Format string can be either ObjC string (e.g. @"%d") or
6589   // C string (e.g. "%d")
6590   // ObjC string uses the same format specifiers as C string, so we can use
6591   // the same format string checking logic for both ObjC and C strings.
6592   UncoveredArgHandler UncoveredArg;
6593   StringLiteralCheckType CT =
6594       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6595                             format_idx, firstDataArg, Type, CallType,
6596                             /*IsFunctionCall*/ true, CheckedVarArgs,
6597                             UncoveredArg,
6598                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6599 
6600   // Generate a diagnostic where an uncovered argument is detected.
6601   if (UncoveredArg.hasUncoveredArg()) {
6602     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6603     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6604     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6605   }
6606 
6607   if (CT != SLCT_NotALiteral)
6608     // Literal format string found, check done!
6609     return CT == SLCT_CheckedLiteral;
6610 
6611   // Strftime is particular as it always uses a single 'time' argument,
6612   // so it is safe to pass a non-literal string.
6613   if (Type == FST_Strftime)
6614     return false;
6615 
6616   // Do not emit diag when the string param is a macro expansion and the
6617   // format is either NSString or CFString. This is a hack to prevent
6618   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6619   // which are usually used in place of NS and CF string literals.
6620   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6621   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6622     return false;
6623 
6624   // If there are no arguments specified, warn with -Wformat-security, otherwise
6625   // warn only with -Wformat-nonliteral.
6626   if (Args.size() == firstDataArg) {
6627     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6628       << OrigFormatExpr->getSourceRange();
6629     switch (Type) {
6630     default:
6631       break;
6632     case FST_Kprintf:
6633     case FST_FreeBSDKPrintf:
6634     case FST_Printf:
6635       Diag(FormatLoc, diag::note_format_security_fixit)
6636         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6637       break;
6638     case FST_NSString:
6639       Diag(FormatLoc, diag::note_format_security_fixit)
6640         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6641       break;
6642     }
6643   } else {
6644     Diag(FormatLoc, diag::warn_format_nonliteral)
6645       << OrigFormatExpr->getSourceRange();
6646   }
6647   return false;
6648 }
6649 
6650 namespace {
6651 
6652 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6653 protected:
6654   Sema &S;
6655   const FormatStringLiteral *FExpr;
6656   const Expr *OrigFormatExpr;
6657   const Sema::FormatStringType FSType;
6658   const unsigned FirstDataArg;
6659   const unsigned NumDataArgs;
6660   const char *Beg; // Start of format string.
6661   const bool HasVAListArg;
6662   ArrayRef<const Expr *> Args;
6663   unsigned FormatIdx;
6664   llvm::SmallBitVector CoveredArgs;
6665   bool usesPositionalArgs = false;
6666   bool atFirstArg = true;
6667   bool inFunctionCall;
6668   Sema::VariadicCallType CallType;
6669   llvm::SmallBitVector &CheckedVarArgs;
6670   UncoveredArgHandler &UncoveredArg;
6671 
6672 public:
6673   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6674                      const Expr *origFormatExpr,
6675                      const Sema::FormatStringType type, unsigned firstDataArg,
6676                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6677                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6678                      bool inFunctionCall, Sema::VariadicCallType callType,
6679                      llvm::SmallBitVector &CheckedVarArgs,
6680                      UncoveredArgHandler &UncoveredArg)
6681       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6682         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6683         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6684         inFunctionCall(inFunctionCall), CallType(callType),
6685         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6686     CoveredArgs.resize(numDataArgs);
6687     CoveredArgs.reset();
6688   }
6689 
6690   void DoneProcessing();
6691 
6692   void HandleIncompleteSpecifier(const char *startSpecifier,
6693                                  unsigned specifierLen) override;
6694 
6695   void HandleInvalidLengthModifier(
6696                            const analyze_format_string::FormatSpecifier &FS,
6697                            const analyze_format_string::ConversionSpecifier &CS,
6698                            const char *startSpecifier, unsigned specifierLen,
6699                            unsigned DiagID);
6700 
6701   void HandleNonStandardLengthModifier(
6702                     const analyze_format_string::FormatSpecifier &FS,
6703                     const char *startSpecifier, unsigned specifierLen);
6704 
6705   void HandleNonStandardConversionSpecifier(
6706                     const analyze_format_string::ConversionSpecifier &CS,
6707                     const char *startSpecifier, unsigned specifierLen);
6708 
6709   void HandlePosition(const char *startPos, unsigned posLen) override;
6710 
6711   void HandleInvalidPosition(const char *startSpecifier,
6712                              unsigned specifierLen,
6713                              analyze_format_string::PositionContext p) override;
6714 
6715   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6716 
6717   void HandleNullChar(const char *nullCharacter) override;
6718 
6719   template <typename Range>
6720   static void
6721   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6722                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6723                        bool IsStringLocation, Range StringRange,
6724                        ArrayRef<FixItHint> Fixit = None);
6725 
6726 protected:
6727   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6728                                         const char *startSpec,
6729                                         unsigned specifierLen,
6730                                         const char *csStart, unsigned csLen);
6731 
6732   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6733                                          const char *startSpec,
6734                                          unsigned specifierLen);
6735 
6736   SourceRange getFormatStringRange();
6737   CharSourceRange getSpecifierRange(const char *startSpecifier,
6738                                     unsigned specifierLen);
6739   SourceLocation getLocationOfByte(const char *x);
6740 
6741   const Expr *getDataArg(unsigned i) const;
6742 
6743   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6744                     const analyze_format_string::ConversionSpecifier &CS,
6745                     const char *startSpecifier, unsigned specifierLen,
6746                     unsigned argIndex);
6747 
6748   template <typename Range>
6749   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6750                             bool IsStringLocation, Range StringRange,
6751                             ArrayRef<FixItHint> Fixit = None);
6752 };
6753 
6754 } // namespace
6755 
6756 SourceRange CheckFormatHandler::getFormatStringRange() {
6757   return OrigFormatExpr->getSourceRange();
6758 }
6759 
6760 CharSourceRange CheckFormatHandler::
6761 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6762   SourceLocation Start = getLocationOfByte(startSpecifier);
6763   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6764 
6765   // Advance the end SourceLocation by one due to half-open ranges.
6766   End = End.getLocWithOffset(1);
6767 
6768   return CharSourceRange::getCharRange(Start, End);
6769 }
6770 
6771 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6772   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6773                                   S.getLangOpts(), S.Context.getTargetInfo());
6774 }
6775 
6776 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6777                                                    unsigned specifierLen){
6778   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6779                        getLocationOfByte(startSpecifier),
6780                        /*IsStringLocation*/true,
6781                        getSpecifierRange(startSpecifier, specifierLen));
6782 }
6783 
6784 void CheckFormatHandler::HandleInvalidLengthModifier(
6785     const analyze_format_string::FormatSpecifier &FS,
6786     const analyze_format_string::ConversionSpecifier &CS,
6787     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6788   using namespace analyze_format_string;
6789 
6790   const LengthModifier &LM = FS.getLengthModifier();
6791   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6792 
6793   // See if we know how to fix this length modifier.
6794   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6795   if (FixedLM) {
6796     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6797                          getLocationOfByte(LM.getStart()),
6798                          /*IsStringLocation*/true,
6799                          getSpecifierRange(startSpecifier, specifierLen));
6800 
6801     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6802       << FixedLM->toString()
6803       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6804 
6805   } else {
6806     FixItHint Hint;
6807     if (DiagID == diag::warn_format_nonsensical_length)
6808       Hint = FixItHint::CreateRemoval(LMRange);
6809 
6810     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6811                          getLocationOfByte(LM.getStart()),
6812                          /*IsStringLocation*/true,
6813                          getSpecifierRange(startSpecifier, specifierLen),
6814                          Hint);
6815   }
6816 }
6817 
6818 void CheckFormatHandler::HandleNonStandardLengthModifier(
6819     const analyze_format_string::FormatSpecifier &FS,
6820     const char *startSpecifier, unsigned specifierLen) {
6821   using namespace analyze_format_string;
6822 
6823   const LengthModifier &LM = FS.getLengthModifier();
6824   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6825 
6826   // See if we know how to fix this length modifier.
6827   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6828   if (FixedLM) {
6829     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6830                            << LM.toString() << 0,
6831                          getLocationOfByte(LM.getStart()),
6832                          /*IsStringLocation*/true,
6833                          getSpecifierRange(startSpecifier, specifierLen));
6834 
6835     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6836       << FixedLM->toString()
6837       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6838 
6839   } else {
6840     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6841                            << LM.toString() << 0,
6842                          getLocationOfByte(LM.getStart()),
6843                          /*IsStringLocation*/true,
6844                          getSpecifierRange(startSpecifier, specifierLen));
6845   }
6846 }
6847 
6848 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6849     const analyze_format_string::ConversionSpecifier &CS,
6850     const char *startSpecifier, unsigned specifierLen) {
6851   using namespace analyze_format_string;
6852 
6853   // See if we know how to fix this conversion specifier.
6854   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6855   if (FixedCS) {
6856     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6857                           << CS.toString() << /*conversion specifier*/1,
6858                          getLocationOfByte(CS.getStart()),
6859                          /*IsStringLocation*/true,
6860                          getSpecifierRange(startSpecifier, specifierLen));
6861 
6862     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6863     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6864       << FixedCS->toString()
6865       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6866   } else {
6867     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6868                           << CS.toString() << /*conversion specifier*/1,
6869                          getLocationOfByte(CS.getStart()),
6870                          /*IsStringLocation*/true,
6871                          getSpecifierRange(startSpecifier, specifierLen));
6872   }
6873 }
6874 
6875 void CheckFormatHandler::HandlePosition(const char *startPos,
6876                                         unsigned posLen) {
6877   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6878                                getLocationOfByte(startPos),
6879                                /*IsStringLocation*/true,
6880                                getSpecifierRange(startPos, posLen));
6881 }
6882 
6883 void
6884 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6885                                      analyze_format_string::PositionContext p) {
6886   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6887                          << (unsigned) p,
6888                        getLocationOfByte(startPos), /*IsStringLocation*/true,
6889                        getSpecifierRange(startPos, posLen));
6890 }
6891 
6892 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6893                                             unsigned posLen) {
6894   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6895                                getLocationOfByte(startPos),
6896                                /*IsStringLocation*/true,
6897                                getSpecifierRange(startPos, posLen));
6898 }
6899 
6900 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6901   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6902     // The presence of a null character is likely an error.
6903     EmitFormatDiagnostic(
6904       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6905       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6906       getFormatStringRange());
6907   }
6908 }
6909 
6910 // Note that this may return NULL if there was an error parsing or building
6911 // one of the argument expressions.
6912 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6913   return Args[FirstDataArg + i];
6914 }
6915 
6916 void CheckFormatHandler::DoneProcessing() {
6917   // Does the number of data arguments exceed the number of
6918   // format conversions in the format string?
6919   if (!HasVAListArg) {
6920       // Find any arguments that weren't covered.
6921     CoveredArgs.flip();
6922     signed notCoveredArg = CoveredArgs.find_first();
6923     if (notCoveredArg >= 0) {
6924       assert((unsigned)notCoveredArg < NumDataArgs);
6925       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6926     } else {
6927       UncoveredArg.setAllCovered();
6928     }
6929   }
6930 }
6931 
6932 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6933                                    const Expr *ArgExpr) {
6934   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6935          "Invalid state");
6936 
6937   if (!ArgExpr)
6938     return;
6939 
6940   SourceLocation Loc = ArgExpr->getBeginLoc();
6941 
6942   if (S.getSourceManager().isInSystemMacro(Loc))
6943     return;
6944 
6945   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6946   for (auto E : DiagnosticExprs)
6947     PDiag << E->getSourceRange();
6948 
6949   CheckFormatHandler::EmitFormatDiagnostic(
6950                                   S, IsFunctionCall, DiagnosticExprs[0],
6951                                   PDiag, Loc, /*IsStringLocation*/false,
6952                                   DiagnosticExprs[0]->getSourceRange());
6953 }
6954 
6955 bool
6956 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6957                                                      SourceLocation Loc,
6958                                                      const char *startSpec,
6959                                                      unsigned specifierLen,
6960                                                      const char *csStart,
6961                                                      unsigned csLen) {
6962   bool keepGoing = true;
6963   if (argIndex < NumDataArgs) {
6964     // Consider the argument coverered, even though the specifier doesn't
6965     // make sense.
6966     CoveredArgs.set(argIndex);
6967   }
6968   else {
6969     // If argIndex exceeds the number of data arguments we
6970     // don't issue a warning because that is just a cascade of warnings (and
6971     // they may have intended '%%' anyway). We don't want to continue processing
6972     // the format string after this point, however, as we will like just get
6973     // gibberish when trying to match arguments.
6974     keepGoing = false;
6975   }
6976 
6977   StringRef Specifier(csStart, csLen);
6978 
6979   // If the specifier in non-printable, it could be the first byte of a UTF-8
6980   // sequence. In that case, print the UTF-8 code point. If not, print the byte
6981   // hex value.
6982   std::string CodePointStr;
6983   if (!llvm::sys::locale::isPrint(*csStart)) {
6984     llvm::UTF32 CodePoint;
6985     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6986     const llvm::UTF8 *E =
6987         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6988     llvm::ConversionResult Result =
6989         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6990 
6991     if (Result != llvm::conversionOK) {
6992       unsigned char FirstChar = *csStart;
6993       CodePoint = (llvm::UTF32)FirstChar;
6994     }
6995 
6996     llvm::raw_string_ostream OS(CodePointStr);
6997     if (CodePoint < 256)
6998       OS << "\\x" << llvm::format("%02x", CodePoint);
6999     else if (CodePoint <= 0xFFFF)
7000       OS << "\\u" << llvm::format("%04x", CodePoint);
7001     else
7002       OS << "\\U" << llvm::format("%08x", CodePoint);
7003     OS.flush();
7004     Specifier = CodePointStr;
7005   }
7006 
7007   EmitFormatDiagnostic(
7008       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7009       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7010 
7011   return keepGoing;
7012 }
7013 
7014 void
7015 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7016                                                       const char *startSpec,
7017                                                       unsigned specifierLen) {
7018   EmitFormatDiagnostic(
7019     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7020     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7021 }
7022 
7023 bool
7024 CheckFormatHandler::CheckNumArgs(
7025   const analyze_format_string::FormatSpecifier &FS,
7026   const analyze_format_string::ConversionSpecifier &CS,
7027   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7028 
7029   if (argIndex >= NumDataArgs) {
7030     PartialDiagnostic PDiag = FS.usesPositionalArg()
7031       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7032            << (argIndex+1) << NumDataArgs)
7033       : S.PDiag(diag::warn_printf_insufficient_data_args);
7034     EmitFormatDiagnostic(
7035       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7036       getSpecifierRange(startSpecifier, specifierLen));
7037 
7038     // Since more arguments than conversion tokens are given, by extension
7039     // all arguments are covered, so mark this as so.
7040     UncoveredArg.setAllCovered();
7041     return false;
7042   }
7043   return true;
7044 }
7045 
7046 template<typename Range>
7047 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7048                                               SourceLocation Loc,
7049                                               bool IsStringLocation,
7050                                               Range StringRange,
7051                                               ArrayRef<FixItHint> FixIt) {
7052   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7053                        Loc, IsStringLocation, StringRange, FixIt);
7054 }
7055 
7056 /// If the format string is not within the function call, emit a note
7057 /// so that the function call and string are in diagnostic messages.
7058 ///
7059 /// \param InFunctionCall if true, the format string is within the function
7060 /// call and only one diagnostic message will be produced.  Otherwise, an
7061 /// extra note will be emitted pointing to location of the format string.
7062 ///
7063 /// \param ArgumentExpr the expression that is passed as the format string
7064 /// argument in the function call.  Used for getting locations when two
7065 /// diagnostics are emitted.
7066 ///
7067 /// \param PDiag the callee should already have provided any strings for the
7068 /// diagnostic message.  This function only adds locations and fixits
7069 /// to diagnostics.
7070 ///
7071 /// \param Loc primary location for diagnostic.  If two diagnostics are
7072 /// required, one will be at Loc and a new SourceLocation will be created for
7073 /// the other one.
7074 ///
7075 /// \param IsStringLocation if true, Loc points to the format string should be
7076 /// used for the note.  Otherwise, Loc points to the argument list and will
7077 /// be used with PDiag.
7078 ///
7079 /// \param StringRange some or all of the string to highlight.  This is
7080 /// templated so it can accept either a CharSourceRange or a SourceRange.
7081 ///
7082 /// \param FixIt optional fix it hint for the format string.
7083 template <typename Range>
7084 void CheckFormatHandler::EmitFormatDiagnostic(
7085     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7086     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7087     Range StringRange, ArrayRef<FixItHint> FixIt) {
7088   if (InFunctionCall) {
7089     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7090     D << StringRange;
7091     D << FixIt;
7092   } else {
7093     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7094       << ArgumentExpr->getSourceRange();
7095 
7096     const Sema::SemaDiagnosticBuilder &Note =
7097       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7098              diag::note_format_string_defined);
7099 
7100     Note << StringRange;
7101     Note << FixIt;
7102   }
7103 }
7104 
7105 //===--- CHECK: Printf format string checking ------------------------------===//
7106 
7107 namespace {
7108 
7109 class CheckPrintfHandler : public CheckFormatHandler {
7110 public:
7111   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7112                      const Expr *origFormatExpr,
7113                      const Sema::FormatStringType type, unsigned firstDataArg,
7114                      unsigned numDataArgs, bool isObjC, const char *beg,
7115                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7116                      unsigned formatIdx, bool inFunctionCall,
7117                      Sema::VariadicCallType CallType,
7118                      llvm::SmallBitVector &CheckedVarArgs,
7119                      UncoveredArgHandler &UncoveredArg)
7120       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7121                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7122                            inFunctionCall, CallType, CheckedVarArgs,
7123                            UncoveredArg) {}
7124 
7125   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7126 
7127   /// Returns true if '%@' specifiers are allowed in the format string.
7128   bool allowsObjCArg() const {
7129     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7130            FSType == Sema::FST_OSTrace;
7131   }
7132 
7133   bool HandleInvalidPrintfConversionSpecifier(
7134                                       const analyze_printf::PrintfSpecifier &FS,
7135                                       const char *startSpecifier,
7136                                       unsigned specifierLen) override;
7137 
7138   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7139                              const char *startSpecifier,
7140                              unsigned specifierLen) override;
7141   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7142                        const char *StartSpecifier,
7143                        unsigned SpecifierLen,
7144                        const Expr *E);
7145 
7146   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7147                     const char *startSpecifier, unsigned specifierLen);
7148   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7149                            const analyze_printf::OptionalAmount &Amt,
7150                            unsigned type,
7151                            const char *startSpecifier, unsigned specifierLen);
7152   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7153                   const analyze_printf::OptionalFlag &flag,
7154                   const char *startSpecifier, unsigned specifierLen);
7155   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7156                          const analyze_printf::OptionalFlag &ignoredFlag,
7157                          const analyze_printf::OptionalFlag &flag,
7158                          const char *startSpecifier, unsigned specifierLen);
7159   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7160                            const Expr *E);
7161 
7162   void HandleEmptyObjCModifierFlag(const char *startFlag,
7163                                    unsigned flagLen) override;
7164 
7165   void HandleInvalidObjCModifierFlag(const char *startFlag,
7166                                             unsigned flagLen) override;
7167 
7168   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7169                                            const char *flagsEnd,
7170                                            const char *conversionPosition)
7171                                              override;
7172 };
7173 
7174 } // namespace
7175 
7176 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7177                                       const analyze_printf::PrintfSpecifier &FS,
7178                                       const char *startSpecifier,
7179                                       unsigned specifierLen) {
7180   const analyze_printf::PrintfConversionSpecifier &CS =
7181     FS.getConversionSpecifier();
7182 
7183   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7184                                           getLocationOfByte(CS.getStart()),
7185                                           startSpecifier, specifierLen,
7186                                           CS.getStart(), CS.getLength());
7187 }
7188 
7189 bool CheckPrintfHandler::HandleAmount(
7190                                const analyze_format_string::OptionalAmount &Amt,
7191                                unsigned k, const char *startSpecifier,
7192                                unsigned specifierLen) {
7193   if (Amt.hasDataArgument()) {
7194     if (!HasVAListArg) {
7195       unsigned argIndex = Amt.getArgIndex();
7196       if (argIndex >= NumDataArgs) {
7197         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7198                                << k,
7199                              getLocationOfByte(Amt.getStart()),
7200                              /*IsStringLocation*/true,
7201                              getSpecifierRange(startSpecifier, specifierLen));
7202         // Don't do any more checking.  We will just emit
7203         // spurious errors.
7204         return false;
7205       }
7206 
7207       // Type check the data argument.  It should be an 'int'.
7208       // Although not in conformance with C99, we also allow the argument to be
7209       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7210       // doesn't emit a warning for that case.
7211       CoveredArgs.set(argIndex);
7212       const Expr *Arg = getDataArg(argIndex);
7213       if (!Arg)
7214         return false;
7215 
7216       QualType T = Arg->getType();
7217 
7218       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7219       assert(AT.isValid());
7220 
7221       if (!AT.matchesType(S.Context, T)) {
7222         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7223                                << k << AT.getRepresentativeTypeName(S.Context)
7224                                << T << Arg->getSourceRange(),
7225                              getLocationOfByte(Amt.getStart()),
7226                              /*IsStringLocation*/true,
7227                              getSpecifierRange(startSpecifier, specifierLen));
7228         // Don't do any more checking.  We will just emit
7229         // spurious errors.
7230         return false;
7231       }
7232     }
7233   }
7234   return true;
7235 }
7236 
7237 void CheckPrintfHandler::HandleInvalidAmount(
7238                                       const analyze_printf::PrintfSpecifier &FS,
7239                                       const analyze_printf::OptionalAmount &Amt,
7240                                       unsigned type,
7241                                       const char *startSpecifier,
7242                                       unsigned specifierLen) {
7243   const analyze_printf::PrintfConversionSpecifier &CS =
7244     FS.getConversionSpecifier();
7245 
7246   FixItHint fixit =
7247     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7248       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7249                                  Amt.getConstantLength()))
7250       : FixItHint();
7251 
7252   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7253                          << type << CS.toString(),
7254                        getLocationOfByte(Amt.getStart()),
7255                        /*IsStringLocation*/true,
7256                        getSpecifierRange(startSpecifier, specifierLen),
7257                        fixit);
7258 }
7259 
7260 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7261                                     const analyze_printf::OptionalFlag &flag,
7262                                     const char *startSpecifier,
7263                                     unsigned specifierLen) {
7264   // Warn about pointless flag with a fixit removal.
7265   const analyze_printf::PrintfConversionSpecifier &CS =
7266     FS.getConversionSpecifier();
7267   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7268                          << flag.toString() << CS.toString(),
7269                        getLocationOfByte(flag.getPosition()),
7270                        /*IsStringLocation*/true,
7271                        getSpecifierRange(startSpecifier, specifierLen),
7272                        FixItHint::CreateRemoval(
7273                          getSpecifierRange(flag.getPosition(), 1)));
7274 }
7275 
7276 void CheckPrintfHandler::HandleIgnoredFlag(
7277                                 const analyze_printf::PrintfSpecifier &FS,
7278                                 const analyze_printf::OptionalFlag &ignoredFlag,
7279                                 const analyze_printf::OptionalFlag &flag,
7280                                 const char *startSpecifier,
7281                                 unsigned specifierLen) {
7282   // Warn about ignored flag with a fixit removal.
7283   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7284                          << ignoredFlag.toString() << flag.toString(),
7285                        getLocationOfByte(ignoredFlag.getPosition()),
7286                        /*IsStringLocation*/true,
7287                        getSpecifierRange(startSpecifier, specifierLen),
7288                        FixItHint::CreateRemoval(
7289                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7290 }
7291 
7292 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7293                                                      unsigned flagLen) {
7294   // Warn about an empty flag.
7295   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7296                        getLocationOfByte(startFlag),
7297                        /*IsStringLocation*/true,
7298                        getSpecifierRange(startFlag, flagLen));
7299 }
7300 
7301 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7302                                                        unsigned flagLen) {
7303   // Warn about an invalid flag.
7304   auto Range = getSpecifierRange(startFlag, flagLen);
7305   StringRef flag(startFlag, flagLen);
7306   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7307                       getLocationOfByte(startFlag),
7308                       /*IsStringLocation*/true,
7309                       Range, FixItHint::CreateRemoval(Range));
7310 }
7311 
7312 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7313     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7314     // Warn about using '[...]' without a '@' conversion.
7315     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7316     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7317     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7318                          getLocationOfByte(conversionPosition),
7319                          /*IsStringLocation*/true,
7320                          Range, FixItHint::CreateRemoval(Range));
7321 }
7322 
7323 // Determines if the specified is a C++ class or struct containing
7324 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7325 // "c_str()").
7326 template<typename MemberKind>
7327 static llvm::SmallPtrSet<MemberKind*, 1>
7328 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7329   const RecordType *RT = Ty->getAs<RecordType>();
7330   llvm::SmallPtrSet<MemberKind*, 1> Results;
7331 
7332   if (!RT)
7333     return Results;
7334   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7335   if (!RD || !RD->getDefinition())
7336     return Results;
7337 
7338   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7339                  Sema::LookupMemberName);
7340   R.suppressDiagnostics();
7341 
7342   // We just need to include all members of the right kind turned up by the
7343   // filter, at this point.
7344   if (S.LookupQualifiedName(R, RT->getDecl()))
7345     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7346       NamedDecl *decl = (*I)->getUnderlyingDecl();
7347       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7348         Results.insert(FK);
7349     }
7350   return Results;
7351 }
7352 
7353 /// Check if we could call '.c_str()' on an object.
7354 ///
7355 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7356 /// allow the call, or if it would be ambiguous).
7357 bool Sema::hasCStrMethod(const Expr *E) {
7358   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7359 
7360   MethodSet Results =
7361       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7362   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7363        MI != ME; ++MI)
7364     if ((*MI)->getMinRequiredArguments() == 0)
7365       return true;
7366   return false;
7367 }
7368 
7369 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7370 // better diagnostic if so. AT is assumed to be valid.
7371 // Returns true when a c_str() conversion method is found.
7372 bool CheckPrintfHandler::checkForCStrMembers(
7373     const analyze_printf::ArgType &AT, const Expr *E) {
7374   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7375 
7376   MethodSet Results =
7377       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7378 
7379   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7380        MI != ME; ++MI) {
7381     const CXXMethodDecl *Method = *MI;
7382     if (Method->getMinRequiredArguments() == 0 &&
7383         AT.matchesType(S.Context, Method->getReturnType())) {
7384       // FIXME: Suggest parens if the expression needs them.
7385       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7386       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7387           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7388       return true;
7389     }
7390   }
7391 
7392   return false;
7393 }
7394 
7395 bool
7396 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7397                                             &FS,
7398                                           const char *startSpecifier,
7399                                           unsigned specifierLen) {
7400   using namespace analyze_format_string;
7401   using namespace analyze_printf;
7402 
7403   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7404 
7405   if (FS.consumesDataArgument()) {
7406     if (atFirstArg) {
7407         atFirstArg = false;
7408         usesPositionalArgs = FS.usesPositionalArg();
7409     }
7410     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7411       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7412                                         startSpecifier, specifierLen);
7413       return false;
7414     }
7415   }
7416 
7417   // First check if the field width, precision, and conversion specifier
7418   // have matching data arguments.
7419   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7420                     startSpecifier, specifierLen)) {
7421     return false;
7422   }
7423 
7424   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7425                     startSpecifier, specifierLen)) {
7426     return false;
7427   }
7428 
7429   if (!CS.consumesDataArgument()) {
7430     // FIXME: Technically specifying a precision or field width here
7431     // makes no sense.  Worth issuing a warning at some point.
7432     return true;
7433   }
7434 
7435   // Consume the argument.
7436   unsigned argIndex = FS.getArgIndex();
7437   if (argIndex < NumDataArgs) {
7438     // The check to see if the argIndex is valid will come later.
7439     // We set the bit here because we may exit early from this
7440     // function if we encounter some other error.
7441     CoveredArgs.set(argIndex);
7442   }
7443 
7444   // FreeBSD kernel extensions.
7445   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7446       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7447     // We need at least two arguments.
7448     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7449       return false;
7450 
7451     // Claim the second argument.
7452     CoveredArgs.set(argIndex + 1);
7453 
7454     // Type check the first argument (int for %b, pointer for %D)
7455     const Expr *Ex = getDataArg(argIndex);
7456     const analyze_printf::ArgType &AT =
7457       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7458         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7459     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7460       EmitFormatDiagnostic(
7461           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7462               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7463               << false << Ex->getSourceRange(),
7464           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7465           getSpecifierRange(startSpecifier, specifierLen));
7466 
7467     // Type check the second argument (char * for both %b and %D)
7468     Ex = getDataArg(argIndex + 1);
7469     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7470     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7471       EmitFormatDiagnostic(
7472           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7473               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7474               << false << Ex->getSourceRange(),
7475           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7476           getSpecifierRange(startSpecifier, specifierLen));
7477 
7478      return true;
7479   }
7480 
7481   // Check for using an Objective-C specific conversion specifier
7482   // in a non-ObjC literal.
7483   if (!allowsObjCArg() && CS.isObjCArg()) {
7484     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7485                                                   specifierLen);
7486   }
7487 
7488   // %P can only be used with os_log.
7489   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7490     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7491                                                   specifierLen);
7492   }
7493 
7494   // %n is not allowed with os_log.
7495   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7496     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7497                          getLocationOfByte(CS.getStart()),
7498                          /*IsStringLocation*/ false,
7499                          getSpecifierRange(startSpecifier, specifierLen));
7500 
7501     return true;
7502   }
7503 
7504   // Only scalars are allowed for os_trace.
7505   if (FSType == Sema::FST_OSTrace &&
7506       (CS.getKind() == ConversionSpecifier::PArg ||
7507        CS.getKind() == ConversionSpecifier::sArg ||
7508        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7509     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7510                                                   specifierLen);
7511   }
7512 
7513   // Check for use of public/private annotation outside of os_log().
7514   if (FSType != Sema::FST_OSLog) {
7515     if (FS.isPublic().isSet()) {
7516       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7517                                << "public",
7518                            getLocationOfByte(FS.isPublic().getPosition()),
7519                            /*IsStringLocation*/ false,
7520                            getSpecifierRange(startSpecifier, specifierLen));
7521     }
7522     if (FS.isPrivate().isSet()) {
7523       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7524                                << "private",
7525                            getLocationOfByte(FS.isPrivate().getPosition()),
7526                            /*IsStringLocation*/ false,
7527                            getSpecifierRange(startSpecifier, specifierLen));
7528     }
7529   }
7530 
7531   // Check for invalid use of field width
7532   if (!FS.hasValidFieldWidth()) {
7533     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7534         startSpecifier, specifierLen);
7535   }
7536 
7537   // Check for invalid use of precision
7538   if (!FS.hasValidPrecision()) {
7539     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7540         startSpecifier, specifierLen);
7541   }
7542 
7543   // Precision is mandatory for %P specifier.
7544   if (CS.getKind() == ConversionSpecifier::PArg &&
7545       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7546     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7547                          getLocationOfByte(startSpecifier),
7548                          /*IsStringLocation*/ false,
7549                          getSpecifierRange(startSpecifier, specifierLen));
7550   }
7551 
7552   // Check each flag does not conflict with any other component.
7553   if (!FS.hasValidThousandsGroupingPrefix())
7554     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7555   if (!FS.hasValidLeadingZeros())
7556     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7557   if (!FS.hasValidPlusPrefix())
7558     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7559   if (!FS.hasValidSpacePrefix())
7560     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7561   if (!FS.hasValidAlternativeForm())
7562     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7563   if (!FS.hasValidLeftJustified())
7564     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7565 
7566   // Check that flags are not ignored by another flag
7567   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7568     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7569         startSpecifier, specifierLen);
7570   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7571     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7572             startSpecifier, specifierLen);
7573 
7574   // Check the length modifier is valid with the given conversion specifier.
7575   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7576     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7577                                 diag::warn_format_nonsensical_length);
7578   else if (!FS.hasStandardLengthModifier())
7579     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7580   else if (!FS.hasStandardLengthConversionCombination())
7581     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7582                                 diag::warn_format_non_standard_conversion_spec);
7583 
7584   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7585     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7586 
7587   // The remaining checks depend on the data arguments.
7588   if (HasVAListArg)
7589     return true;
7590 
7591   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7592     return false;
7593 
7594   const Expr *Arg = getDataArg(argIndex);
7595   if (!Arg)
7596     return true;
7597 
7598   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7599 }
7600 
7601 static bool requiresParensToAddCast(const Expr *E) {
7602   // FIXME: We should have a general way to reason about operator
7603   // precedence and whether parens are actually needed here.
7604   // Take care of a few common cases where they aren't.
7605   const Expr *Inside = E->IgnoreImpCasts();
7606   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7607     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7608 
7609   switch (Inside->getStmtClass()) {
7610   case Stmt::ArraySubscriptExprClass:
7611   case Stmt::CallExprClass:
7612   case Stmt::CharacterLiteralClass:
7613   case Stmt::CXXBoolLiteralExprClass:
7614   case Stmt::DeclRefExprClass:
7615   case Stmt::FloatingLiteralClass:
7616   case Stmt::IntegerLiteralClass:
7617   case Stmt::MemberExprClass:
7618   case Stmt::ObjCArrayLiteralClass:
7619   case Stmt::ObjCBoolLiteralExprClass:
7620   case Stmt::ObjCBoxedExprClass:
7621   case Stmt::ObjCDictionaryLiteralClass:
7622   case Stmt::ObjCEncodeExprClass:
7623   case Stmt::ObjCIvarRefExprClass:
7624   case Stmt::ObjCMessageExprClass:
7625   case Stmt::ObjCPropertyRefExprClass:
7626   case Stmt::ObjCStringLiteralClass:
7627   case Stmt::ObjCSubscriptRefExprClass:
7628   case Stmt::ParenExprClass:
7629   case Stmt::StringLiteralClass:
7630   case Stmt::UnaryOperatorClass:
7631     return false;
7632   default:
7633     return true;
7634   }
7635 }
7636 
7637 static std::pair<QualType, StringRef>
7638 shouldNotPrintDirectly(const ASTContext &Context,
7639                        QualType IntendedTy,
7640                        const Expr *E) {
7641   // Use a 'while' to peel off layers of typedefs.
7642   QualType TyTy = IntendedTy;
7643   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7644     StringRef Name = UserTy->getDecl()->getName();
7645     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7646       .Case("CFIndex", Context.getNSIntegerType())
7647       .Case("NSInteger", Context.getNSIntegerType())
7648       .Case("NSUInteger", Context.getNSUIntegerType())
7649       .Case("SInt32", Context.IntTy)
7650       .Case("UInt32", Context.UnsignedIntTy)
7651       .Default(QualType());
7652 
7653     if (!CastTy.isNull())
7654       return std::make_pair(CastTy, Name);
7655 
7656     TyTy = UserTy->desugar();
7657   }
7658 
7659   // Strip parens if necessary.
7660   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7661     return shouldNotPrintDirectly(Context,
7662                                   PE->getSubExpr()->getType(),
7663                                   PE->getSubExpr());
7664 
7665   // If this is a conditional expression, then its result type is constructed
7666   // via usual arithmetic conversions and thus there might be no necessary
7667   // typedef sugar there.  Recurse to operands to check for NSInteger &
7668   // Co. usage condition.
7669   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7670     QualType TrueTy, FalseTy;
7671     StringRef TrueName, FalseName;
7672 
7673     std::tie(TrueTy, TrueName) =
7674       shouldNotPrintDirectly(Context,
7675                              CO->getTrueExpr()->getType(),
7676                              CO->getTrueExpr());
7677     std::tie(FalseTy, FalseName) =
7678       shouldNotPrintDirectly(Context,
7679                              CO->getFalseExpr()->getType(),
7680                              CO->getFalseExpr());
7681 
7682     if (TrueTy == FalseTy)
7683       return std::make_pair(TrueTy, TrueName);
7684     else if (TrueTy.isNull())
7685       return std::make_pair(FalseTy, FalseName);
7686     else if (FalseTy.isNull())
7687       return std::make_pair(TrueTy, TrueName);
7688   }
7689 
7690   return std::make_pair(QualType(), StringRef());
7691 }
7692 
7693 bool
7694 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7695                                     const char *StartSpecifier,
7696                                     unsigned SpecifierLen,
7697                                     const Expr *E) {
7698   using namespace analyze_format_string;
7699   using namespace analyze_printf;
7700 
7701   // Now type check the data expression that matches the
7702   // format specifier.
7703   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7704   if (!AT.isValid())
7705     return true;
7706 
7707   QualType ExprTy = E->getType();
7708   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7709     ExprTy = TET->getUnderlyingExpr()->getType();
7710   }
7711 
7712   const analyze_printf::ArgType::MatchKind Match =
7713       AT.matchesType(S.Context, ExprTy);
7714   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7715   if (Match == analyze_printf::ArgType::Match)
7716     return true;
7717 
7718   // Look through argument promotions for our error message's reported type.
7719   // This includes the integral and floating promotions, but excludes array
7720   // and function pointer decay; seeing that an argument intended to be a
7721   // string has type 'char [6]' is probably more confusing than 'char *'.
7722   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7723     if (ICE->getCastKind() == CK_IntegralCast ||
7724         ICE->getCastKind() == CK_FloatingCast) {
7725       E = ICE->getSubExpr();
7726       ExprTy = E->getType();
7727 
7728       // Check if we didn't match because of an implicit cast from a 'char'
7729       // or 'short' to an 'int'.  This is done because printf is a varargs
7730       // function.
7731       if (ICE->getType() == S.Context.IntTy ||
7732           ICE->getType() == S.Context.UnsignedIntTy) {
7733         // All further checking is done on the subexpression.
7734         if (AT.matchesType(S.Context, ExprTy))
7735           return true;
7736       }
7737     }
7738   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7739     // Special case for 'a', which has type 'int' in C.
7740     // Note, however, that we do /not/ want to treat multibyte constants like
7741     // 'MooV' as characters! This form is deprecated but still exists.
7742     if (ExprTy == S.Context.IntTy)
7743       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7744         ExprTy = S.Context.CharTy;
7745   }
7746 
7747   // Look through enums to their underlying type.
7748   bool IsEnum = false;
7749   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7750     ExprTy = EnumTy->getDecl()->getIntegerType();
7751     IsEnum = true;
7752   }
7753 
7754   // %C in an Objective-C context prints a unichar, not a wchar_t.
7755   // If the argument is an integer of some kind, believe the %C and suggest
7756   // a cast instead of changing the conversion specifier.
7757   QualType IntendedTy = ExprTy;
7758   if (isObjCContext() &&
7759       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7760     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7761         !ExprTy->isCharType()) {
7762       // 'unichar' is defined as a typedef of unsigned short, but we should
7763       // prefer using the typedef if it is visible.
7764       IntendedTy = S.Context.UnsignedShortTy;
7765 
7766       // While we are here, check if the value is an IntegerLiteral that happens
7767       // to be within the valid range.
7768       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7769         const llvm::APInt &V = IL->getValue();
7770         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7771           return true;
7772       }
7773 
7774       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7775                           Sema::LookupOrdinaryName);
7776       if (S.LookupName(Result, S.getCurScope())) {
7777         NamedDecl *ND = Result.getFoundDecl();
7778         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7779           if (TD->getUnderlyingType() == IntendedTy)
7780             IntendedTy = S.Context.getTypedefType(TD);
7781       }
7782     }
7783   }
7784 
7785   // Special-case some of Darwin's platform-independence types by suggesting
7786   // casts to primitive types that are known to be large enough.
7787   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7788   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7789     QualType CastTy;
7790     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7791     if (!CastTy.isNull()) {
7792       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7793       // (long in ASTContext). Only complain to pedants.
7794       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7795           (AT.isSizeT() || AT.isPtrdiffT()) &&
7796           AT.matchesType(S.Context, CastTy))
7797         Pedantic = true;
7798       IntendedTy = CastTy;
7799       ShouldNotPrintDirectly = true;
7800     }
7801   }
7802 
7803   // We may be able to offer a FixItHint if it is a supported type.
7804   PrintfSpecifier fixedFS = FS;
7805   bool Success =
7806       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7807 
7808   if (Success) {
7809     // Get the fix string from the fixed format specifier
7810     SmallString<16> buf;
7811     llvm::raw_svector_ostream os(buf);
7812     fixedFS.toString(os);
7813 
7814     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7815 
7816     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7817       unsigned Diag =
7818           Pedantic
7819               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7820               : diag::warn_format_conversion_argument_type_mismatch;
7821       // In this case, the specifier is wrong and should be changed to match
7822       // the argument.
7823       EmitFormatDiagnostic(S.PDiag(Diag)
7824                                << AT.getRepresentativeTypeName(S.Context)
7825                                << IntendedTy << IsEnum << E->getSourceRange(),
7826                            E->getBeginLoc(),
7827                            /*IsStringLocation*/ false, SpecRange,
7828                            FixItHint::CreateReplacement(SpecRange, os.str()));
7829     } else {
7830       // The canonical type for formatting this value is different from the
7831       // actual type of the expression. (This occurs, for example, with Darwin's
7832       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7833       // should be printed as 'long' for 64-bit compatibility.)
7834       // Rather than emitting a normal format/argument mismatch, we want to
7835       // add a cast to the recommended type (and correct the format string
7836       // if necessary).
7837       SmallString<16> CastBuf;
7838       llvm::raw_svector_ostream CastFix(CastBuf);
7839       CastFix << "(";
7840       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7841       CastFix << ")";
7842 
7843       SmallVector<FixItHint,4> Hints;
7844       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
7845         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7846 
7847       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7848         // If there's already a cast present, just replace it.
7849         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7850         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7851 
7852       } else if (!requiresParensToAddCast(E)) {
7853         // If the expression has high enough precedence,
7854         // just write the C-style cast.
7855         Hints.push_back(
7856             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7857       } else {
7858         // Otherwise, add parens around the expression as well as the cast.
7859         CastFix << "(";
7860         Hints.push_back(
7861             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7862 
7863         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
7864         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7865       }
7866 
7867       if (ShouldNotPrintDirectly) {
7868         // The expression has a type that should not be printed directly.
7869         // We extract the name from the typedef because we don't want to show
7870         // the underlying type in the diagnostic.
7871         StringRef Name;
7872         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7873           Name = TypedefTy->getDecl()->getName();
7874         else
7875           Name = CastTyName;
7876         unsigned Diag = Pedantic
7877                             ? diag::warn_format_argument_needs_cast_pedantic
7878                             : diag::warn_format_argument_needs_cast;
7879         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7880                                            << E->getSourceRange(),
7881                              E->getBeginLoc(), /*IsStringLocation=*/false,
7882                              SpecRange, Hints);
7883       } else {
7884         // In this case, the expression could be printed using a different
7885         // specifier, but we've decided that the specifier is probably correct
7886         // and we should cast instead. Just use the normal warning message.
7887         EmitFormatDiagnostic(
7888             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7889                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7890                 << E->getSourceRange(),
7891             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7892       }
7893     }
7894   } else {
7895     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7896                                                    SpecifierLen);
7897     // Since the warning for passing non-POD types to variadic functions
7898     // was deferred until now, we emit a warning for non-POD
7899     // arguments here.
7900     switch (S.isValidVarArgType(ExprTy)) {
7901     case Sema::VAK_Valid:
7902     case Sema::VAK_ValidInCXX11: {
7903       unsigned Diag =
7904           Pedantic
7905               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7906               : diag::warn_format_conversion_argument_type_mismatch;
7907 
7908       EmitFormatDiagnostic(
7909           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7910                         << IsEnum << CSR << E->getSourceRange(),
7911           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7912       break;
7913     }
7914     case Sema::VAK_Undefined:
7915     case Sema::VAK_MSVCUndefined:
7916       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7917                                << S.getLangOpts().CPlusPlus11 << ExprTy
7918                                << CallType
7919                                << AT.getRepresentativeTypeName(S.Context) << CSR
7920                                << E->getSourceRange(),
7921                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7922       checkForCStrMembers(AT, E);
7923       break;
7924 
7925     case Sema::VAK_Invalid:
7926       if (ExprTy->isObjCObjectType())
7927         EmitFormatDiagnostic(
7928             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7929                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7930                 << AT.getRepresentativeTypeName(S.Context) << CSR
7931                 << E->getSourceRange(),
7932             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7933       else
7934         // FIXME: If this is an initializer list, suggest removing the braces
7935         // or inserting a cast to the target type.
7936         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7937             << isa<InitListExpr>(E) << ExprTy << CallType
7938             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
7939       break;
7940     }
7941 
7942     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7943            "format string specifier index out of range");
7944     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7945   }
7946 
7947   return true;
7948 }
7949 
7950 //===--- CHECK: Scanf format string checking ------------------------------===//
7951 
7952 namespace {
7953 
7954 class CheckScanfHandler : public CheckFormatHandler {
7955 public:
7956   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7957                     const Expr *origFormatExpr, Sema::FormatStringType type,
7958                     unsigned firstDataArg, unsigned numDataArgs,
7959                     const char *beg, bool hasVAListArg,
7960                     ArrayRef<const Expr *> Args, unsigned formatIdx,
7961                     bool inFunctionCall, Sema::VariadicCallType CallType,
7962                     llvm::SmallBitVector &CheckedVarArgs,
7963                     UncoveredArgHandler &UncoveredArg)
7964       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7965                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7966                            inFunctionCall, CallType, CheckedVarArgs,
7967                            UncoveredArg) {}
7968 
7969   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7970                             const char *startSpecifier,
7971                             unsigned specifierLen) override;
7972 
7973   bool HandleInvalidScanfConversionSpecifier(
7974           const analyze_scanf::ScanfSpecifier &FS,
7975           const char *startSpecifier,
7976           unsigned specifierLen) override;
7977 
7978   void HandleIncompleteScanList(const char *start, const char *end) override;
7979 };
7980 
7981 } // namespace
7982 
7983 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7984                                                  const char *end) {
7985   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7986                        getLocationOfByte(end), /*IsStringLocation*/true,
7987                        getSpecifierRange(start, end - start));
7988 }
7989 
7990 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7991                                         const analyze_scanf::ScanfSpecifier &FS,
7992                                         const char *startSpecifier,
7993                                         unsigned specifierLen) {
7994   const analyze_scanf::ScanfConversionSpecifier &CS =
7995     FS.getConversionSpecifier();
7996 
7997   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7998                                           getLocationOfByte(CS.getStart()),
7999                                           startSpecifier, specifierLen,
8000                                           CS.getStart(), CS.getLength());
8001 }
8002 
8003 bool CheckScanfHandler::HandleScanfSpecifier(
8004                                        const analyze_scanf::ScanfSpecifier &FS,
8005                                        const char *startSpecifier,
8006                                        unsigned specifierLen) {
8007   using namespace analyze_scanf;
8008   using namespace analyze_format_string;
8009 
8010   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8011 
8012   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8013   // be used to decide if we are using positional arguments consistently.
8014   if (FS.consumesDataArgument()) {
8015     if (atFirstArg) {
8016       atFirstArg = false;
8017       usesPositionalArgs = FS.usesPositionalArg();
8018     }
8019     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8020       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8021                                         startSpecifier, specifierLen);
8022       return false;
8023     }
8024   }
8025 
8026   // Check if the field with is non-zero.
8027   const OptionalAmount &Amt = FS.getFieldWidth();
8028   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8029     if (Amt.getConstantAmount() == 0) {
8030       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8031                                                    Amt.getConstantLength());
8032       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8033                            getLocationOfByte(Amt.getStart()),
8034                            /*IsStringLocation*/true, R,
8035                            FixItHint::CreateRemoval(R));
8036     }
8037   }
8038 
8039   if (!FS.consumesDataArgument()) {
8040     // FIXME: Technically specifying a precision or field width here
8041     // makes no sense.  Worth issuing a warning at some point.
8042     return true;
8043   }
8044 
8045   // Consume the argument.
8046   unsigned argIndex = FS.getArgIndex();
8047   if (argIndex < NumDataArgs) {
8048       // The check to see if the argIndex is valid will come later.
8049       // We set the bit here because we may exit early from this
8050       // function if we encounter some other error.
8051     CoveredArgs.set(argIndex);
8052   }
8053 
8054   // Check the length modifier is valid with the given conversion specifier.
8055   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
8056     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8057                                 diag::warn_format_nonsensical_length);
8058   else if (!FS.hasStandardLengthModifier())
8059     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8060   else if (!FS.hasStandardLengthConversionCombination())
8061     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8062                                 diag::warn_format_non_standard_conversion_spec);
8063 
8064   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8065     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8066 
8067   // The remaining checks depend on the data arguments.
8068   if (HasVAListArg)
8069     return true;
8070 
8071   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8072     return false;
8073 
8074   // Check that the argument type matches the format specifier.
8075   const Expr *Ex = getDataArg(argIndex);
8076   if (!Ex)
8077     return true;
8078 
8079   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8080 
8081   if (!AT.isValid()) {
8082     return true;
8083   }
8084 
8085   analyze_format_string::ArgType::MatchKind Match =
8086       AT.matchesType(S.Context, Ex->getType());
8087   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8088   if (Match == analyze_format_string::ArgType::Match)
8089     return true;
8090 
8091   ScanfSpecifier fixedFS = FS;
8092   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8093                                  S.getLangOpts(), S.Context);
8094 
8095   unsigned Diag =
8096       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8097                : diag::warn_format_conversion_argument_type_mismatch;
8098 
8099   if (Success) {
8100     // Get the fix string from the fixed format specifier.
8101     SmallString<128> buf;
8102     llvm::raw_svector_ostream os(buf);
8103     fixedFS.toString(os);
8104 
8105     EmitFormatDiagnostic(
8106         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8107                       << Ex->getType() << false << Ex->getSourceRange(),
8108         Ex->getBeginLoc(),
8109         /*IsStringLocation*/ false,
8110         getSpecifierRange(startSpecifier, specifierLen),
8111         FixItHint::CreateReplacement(
8112             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8113   } else {
8114     EmitFormatDiagnostic(S.PDiag(Diag)
8115                              << AT.getRepresentativeTypeName(S.Context)
8116                              << Ex->getType() << false << Ex->getSourceRange(),
8117                          Ex->getBeginLoc(),
8118                          /*IsStringLocation*/ false,
8119                          getSpecifierRange(startSpecifier, specifierLen));
8120   }
8121 
8122   return true;
8123 }
8124 
8125 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8126                               const Expr *OrigFormatExpr,
8127                               ArrayRef<const Expr *> Args,
8128                               bool HasVAListArg, unsigned format_idx,
8129                               unsigned firstDataArg,
8130                               Sema::FormatStringType Type,
8131                               bool inFunctionCall,
8132                               Sema::VariadicCallType CallType,
8133                               llvm::SmallBitVector &CheckedVarArgs,
8134                               UncoveredArgHandler &UncoveredArg) {
8135   // CHECK: is the format string a wide literal?
8136   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8137     CheckFormatHandler::EmitFormatDiagnostic(
8138         S, inFunctionCall, Args[format_idx],
8139         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8140         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8141     return;
8142   }
8143 
8144   // Str - The format string.  NOTE: this is NOT null-terminated!
8145   StringRef StrRef = FExpr->getString();
8146   const char *Str = StrRef.data();
8147   // Account for cases where the string literal is truncated in a declaration.
8148   const ConstantArrayType *T =
8149     S.Context.getAsConstantArrayType(FExpr->getType());
8150   assert(T && "String literal not of constant array type!");
8151   size_t TypeSize = T->getSize().getZExtValue();
8152   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8153   const unsigned numDataArgs = Args.size() - firstDataArg;
8154 
8155   // Emit a warning if the string literal is truncated and does not contain an
8156   // embedded null character.
8157   if (TypeSize <= StrRef.size() &&
8158       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8159     CheckFormatHandler::EmitFormatDiagnostic(
8160         S, inFunctionCall, Args[format_idx],
8161         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8162         FExpr->getBeginLoc(),
8163         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8164     return;
8165   }
8166 
8167   // CHECK: empty format string?
8168   if (StrLen == 0 && numDataArgs > 0) {
8169     CheckFormatHandler::EmitFormatDiagnostic(
8170         S, inFunctionCall, Args[format_idx],
8171         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8172         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8173     return;
8174   }
8175 
8176   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8177       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8178       Type == Sema::FST_OSTrace) {
8179     CheckPrintfHandler H(
8180         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8181         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8182         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8183         CheckedVarArgs, UncoveredArg);
8184 
8185     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8186                                                   S.getLangOpts(),
8187                                                   S.Context.getTargetInfo(),
8188                                             Type == Sema::FST_FreeBSDKPrintf))
8189       H.DoneProcessing();
8190   } else if (Type == Sema::FST_Scanf) {
8191     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8192                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8193                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8194 
8195     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8196                                                  S.getLangOpts(),
8197                                                  S.Context.getTargetInfo()))
8198       H.DoneProcessing();
8199   } // TODO: handle other formats
8200 }
8201 
8202 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8203   // Str - The format string.  NOTE: this is NOT null-terminated!
8204   StringRef StrRef = FExpr->getString();
8205   const char *Str = StrRef.data();
8206   // Account for cases where the string literal is truncated in a declaration.
8207   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8208   assert(T && "String literal not of constant array type!");
8209   size_t TypeSize = T->getSize().getZExtValue();
8210   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8211   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8212                                                          getLangOpts(),
8213                                                          Context.getTargetInfo());
8214 }
8215 
8216 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8217 
8218 // Returns the related absolute value function that is larger, of 0 if one
8219 // does not exist.
8220 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8221   switch (AbsFunction) {
8222   default:
8223     return 0;
8224 
8225   case Builtin::BI__builtin_abs:
8226     return Builtin::BI__builtin_labs;
8227   case Builtin::BI__builtin_labs:
8228     return Builtin::BI__builtin_llabs;
8229   case Builtin::BI__builtin_llabs:
8230     return 0;
8231 
8232   case Builtin::BI__builtin_fabsf:
8233     return Builtin::BI__builtin_fabs;
8234   case Builtin::BI__builtin_fabs:
8235     return Builtin::BI__builtin_fabsl;
8236   case Builtin::BI__builtin_fabsl:
8237     return 0;
8238 
8239   case Builtin::BI__builtin_cabsf:
8240     return Builtin::BI__builtin_cabs;
8241   case Builtin::BI__builtin_cabs:
8242     return Builtin::BI__builtin_cabsl;
8243   case Builtin::BI__builtin_cabsl:
8244     return 0;
8245 
8246   case Builtin::BIabs:
8247     return Builtin::BIlabs;
8248   case Builtin::BIlabs:
8249     return Builtin::BIllabs;
8250   case Builtin::BIllabs:
8251     return 0;
8252 
8253   case Builtin::BIfabsf:
8254     return Builtin::BIfabs;
8255   case Builtin::BIfabs:
8256     return Builtin::BIfabsl;
8257   case Builtin::BIfabsl:
8258     return 0;
8259 
8260   case Builtin::BIcabsf:
8261    return Builtin::BIcabs;
8262   case Builtin::BIcabs:
8263     return Builtin::BIcabsl;
8264   case Builtin::BIcabsl:
8265     return 0;
8266   }
8267 }
8268 
8269 // Returns the argument type of the absolute value function.
8270 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8271                                              unsigned AbsType) {
8272   if (AbsType == 0)
8273     return QualType();
8274 
8275   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8276   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8277   if (Error != ASTContext::GE_None)
8278     return QualType();
8279 
8280   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8281   if (!FT)
8282     return QualType();
8283 
8284   if (FT->getNumParams() != 1)
8285     return QualType();
8286 
8287   return FT->getParamType(0);
8288 }
8289 
8290 // Returns the best absolute value function, or zero, based on type and
8291 // current absolute value function.
8292 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8293                                    unsigned AbsFunctionKind) {
8294   unsigned BestKind = 0;
8295   uint64_t ArgSize = Context.getTypeSize(ArgType);
8296   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8297        Kind = getLargerAbsoluteValueFunction(Kind)) {
8298     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8299     if (Context.getTypeSize(ParamType) >= ArgSize) {
8300       if (BestKind == 0)
8301         BestKind = Kind;
8302       else if (Context.hasSameType(ParamType, ArgType)) {
8303         BestKind = Kind;
8304         break;
8305       }
8306     }
8307   }
8308   return BestKind;
8309 }
8310 
8311 enum AbsoluteValueKind {
8312   AVK_Integer,
8313   AVK_Floating,
8314   AVK_Complex
8315 };
8316 
8317 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8318   if (T->isIntegralOrEnumerationType())
8319     return AVK_Integer;
8320   if (T->isRealFloatingType())
8321     return AVK_Floating;
8322   if (T->isAnyComplexType())
8323     return AVK_Complex;
8324 
8325   llvm_unreachable("Type not integer, floating, or complex");
8326 }
8327 
8328 // Changes the absolute value function to a different type.  Preserves whether
8329 // the function is a builtin.
8330 static unsigned changeAbsFunction(unsigned AbsKind,
8331                                   AbsoluteValueKind ValueKind) {
8332   switch (ValueKind) {
8333   case AVK_Integer:
8334     switch (AbsKind) {
8335     default:
8336       return 0;
8337     case Builtin::BI__builtin_fabsf:
8338     case Builtin::BI__builtin_fabs:
8339     case Builtin::BI__builtin_fabsl:
8340     case Builtin::BI__builtin_cabsf:
8341     case Builtin::BI__builtin_cabs:
8342     case Builtin::BI__builtin_cabsl:
8343       return Builtin::BI__builtin_abs;
8344     case Builtin::BIfabsf:
8345     case Builtin::BIfabs:
8346     case Builtin::BIfabsl:
8347     case Builtin::BIcabsf:
8348     case Builtin::BIcabs:
8349     case Builtin::BIcabsl:
8350       return Builtin::BIabs;
8351     }
8352   case AVK_Floating:
8353     switch (AbsKind) {
8354     default:
8355       return 0;
8356     case Builtin::BI__builtin_abs:
8357     case Builtin::BI__builtin_labs:
8358     case Builtin::BI__builtin_llabs:
8359     case Builtin::BI__builtin_cabsf:
8360     case Builtin::BI__builtin_cabs:
8361     case Builtin::BI__builtin_cabsl:
8362       return Builtin::BI__builtin_fabsf;
8363     case Builtin::BIabs:
8364     case Builtin::BIlabs:
8365     case Builtin::BIllabs:
8366     case Builtin::BIcabsf:
8367     case Builtin::BIcabs:
8368     case Builtin::BIcabsl:
8369       return Builtin::BIfabsf;
8370     }
8371   case AVK_Complex:
8372     switch (AbsKind) {
8373     default:
8374       return 0;
8375     case Builtin::BI__builtin_abs:
8376     case Builtin::BI__builtin_labs:
8377     case Builtin::BI__builtin_llabs:
8378     case Builtin::BI__builtin_fabsf:
8379     case Builtin::BI__builtin_fabs:
8380     case Builtin::BI__builtin_fabsl:
8381       return Builtin::BI__builtin_cabsf;
8382     case Builtin::BIabs:
8383     case Builtin::BIlabs:
8384     case Builtin::BIllabs:
8385     case Builtin::BIfabsf:
8386     case Builtin::BIfabs:
8387     case Builtin::BIfabsl:
8388       return Builtin::BIcabsf;
8389     }
8390   }
8391   llvm_unreachable("Unable to convert function");
8392 }
8393 
8394 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8395   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8396   if (!FnInfo)
8397     return 0;
8398 
8399   switch (FDecl->getBuiltinID()) {
8400   default:
8401     return 0;
8402   case Builtin::BI__builtin_abs:
8403   case Builtin::BI__builtin_fabs:
8404   case Builtin::BI__builtin_fabsf:
8405   case Builtin::BI__builtin_fabsl:
8406   case Builtin::BI__builtin_labs:
8407   case Builtin::BI__builtin_llabs:
8408   case Builtin::BI__builtin_cabs:
8409   case Builtin::BI__builtin_cabsf:
8410   case Builtin::BI__builtin_cabsl:
8411   case Builtin::BIabs:
8412   case Builtin::BIlabs:
8413   case Builtin::BIllabs:
8414   case Builtin::BIfabs:
8415   case Builtin::BIfabsf:
8416   case Builtin::BIfabsl:
8417   case Builtin::BIcabs:
8418   case Builtin::BIcabsf:
8419   case Builtin::BIcabsl:
8420     return FDecl->getBuiltinID();
8421   }
8422   llvm_unreachable("Unknown Builtin type");
8423 }
8424 
8425 // If the replacement is valid, emit a note with replacement function.
8426 // Additionally, suggest including the proper header if not already included.
8427 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8428                             unsigned AbsKind, QualType ArgType) {
8429   bool EmitHeaderHint = true;
8430   const char *HeaderName = nullptr;
8431   const char *FunctionName = nullptr;
8432   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8433     FunctionName = "std::abs";
8434     if (ArgType->isIntegralOrEnumerationType()) {
8435       HeaderName = "cstdlib";
8436     } else if (ArgType->isRealFloatingType()) {
8437       HeaderName = "cmath";
8438     } else {
8439       llvm_unreachable("Invalid Type");
8440     }
8441 
8442     // Lookup all std::abs
8443     if (NamespaceDecl *Std = S.getStdNamespace()) {
8444       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8445       R.suppressDiagnostics();
8446       S.LookupQualifiedName(R, Std);
8447 
8448       for (const auto *I : R) {
8449         const FunctionDecl *FDecl = nullptr;
8450         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8451           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8452         } else {
8453           FDecl = dyn_cast<FunctionDecl>(I);
8454         }
8455         if (!FDecl)
8456           continue;
8457 
8458         // Found std::abs(), check that they are the right ones.
8459         if (FDecl->getNumParams() != 1)
8460           continue;
8461 
8462         // Check that the parameter type can handle the argument.
8463         QualType ParamType = FDecl->getParamDecl(0)->getType();
8464         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8465             S.Context.getTypeSize(ArgType) <=
8466                 S.Context.getTypeSize(ParamType)) {
8467           // Found a function, don't need the header hint.
8468           EmitHeaderHint = false;
8469           break;
8470         }
8471       }
8472     }
8473   } else {
8474     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8475     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8476 
8477     if (HeaderName) {
8478       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8479       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8480       R.suppressDiagnostics();
8481       S.LookupName(R, S.getCurScope());
8482 
8483       if (R.isSingleResult()) {
8484         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8485         if (FD && FD->getBuiltinID() == AbsKind) {
8486           EmitHeaderHint = false;
8487         } else {
8488           return;
8489         }
8490       } else if (!R.empty()) {
8491         return;
8492       }
8493     }
8494   }
8495 
8496   S.Diag(Loc, diag::note_replace_abs_function)
8497       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8498 
8499   if (!HeaderName)
8500     return;
8501 
8502   if (!EmitHeaderHint)
8503     return;
8504 
8505   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8506                                                     << FunctionName;
8507 }
8508 
8509 template <std::size_t StrLen>
8510 static bool IsStdFunction(const FunctionDecl *FDecl,
8511                           const char (&Str)[StrLen]) {
8512   if (!FDecl)
8513     return false;
8514   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8515     return false;
8516   if (!FDecl->isInStdNamespace())
8517     return false;
8518 
8519   return true;
8520 }
8521 
8522 // Warn when using the wrong abs() function.
8523 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8524                                       const FunctionDecl *FDecl) {
8525   if (Call->getNumArgs() != 1)
8526     return;
8527 
8528   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8529   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8530   if (AbsKind == 0 && !IsStdAbs)
8531     return;
8532 
8533   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8534   QualType ParamType = Call->getArg(0)->getType();
8535 
8536   // Unsigned types cannot be negative.  Suggest removing the absolute value
8537   // function call.
8538   if (ArgType->isUnsignedIntegerType()) {
8539     const char *FunctionName =
8540         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8541     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8542     Diag(Call->getExprLoc(), diag::note_remove_abs)
8543         << FunctionName
8544         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8545     return;
8546   }
8547 
8548   // Taking the absolute value of a pointer is very suspicious, they probably
8549   // wanted to index into an array, dereference a pointer, call a function, etc.
8550   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8551     unsigned DiagType = 0;
8552     if (ArgType->isFunctionType())
8553       DiagType = 1;
8554     else if (ArgType->isArrayType())
8555       DiagType = 2;
8556 
8557     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8558     return;
8559   }
8560 
8561   // std::abs has overloads which prevent most of the absolute value problems
8562   // from occurring.
8563   if (IsStdAbs)
8564     return;
8565 
8566   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8567   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8568 
8569   // The argument and parameter are the same kind.  Check if they are the right
8570   // size.
8571   if (ArgValueKind == ParamValueKind) {
8572     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8573       return;
8574 
8575     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8576     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8577         << FDecl << ArgType << ParamType;
8578 
8579     if (NewAbsKind == 0)
8580       return;
8581 
8582     emitReplacement(*this, Call->getExprLoc(),
8583                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8584     return;
8585   }
8586 
8587   // ArgValueKind != ParamValueKind
8588   // The wrong type of absolute value function was used.  Attempt to find the
8589   // proper one.
8590   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8591   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8592   if (NewAbsKind == 0)
8593     return;
8594 
8595   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8596       << FDecl << ParamValueKind << ArgValueKind;
8597 
8598   emitReplacement(*this, Call->getExprLoc(),
8599                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8600 }
8601 
8602 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8603 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8604                                 const FunctionDecl *FDecl) {
8605   if (!Call || !FDecl) return;
8606 
8607   // Ignore template specializations and macros.
8608   if (inTemplateInstantiation()) return;
8609   if (Call->getExprLoc().isMacroID()) return;
8610 
8611   // Only care about the one template argument, two function parameter std::max
8612   if (Call->getNumArgs() != 2) return;
8613   if (!IsStdFunction(FDecl, "max")) return;
8614   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8615   if (!ArgList) return;
8616   if (ArgList->size() != 1) return;
8617 
8618   // Check that template type argument is unsigned integer.
8619   const auto& TA = ArgList->get(0);
8620   if (TA.getKind() != TemplateArgument::Type) return;
8621   QualType ArgType = TA.getAsType();
8622   if (!ArgType->isUnsignedIntegerType()) return;
8623 
8624   // See if either argument is a literal zero.
8625   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8626     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8627     if (!MTE) return false;
8628     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8629     if (!Num) return false;
8630     if (Num->getValue() != 0) return false;
8631     return true;
8632   };
8633 
8634   const Expr *FirstArg = Call->getArg(0);
8635   const Expr *SecondArg = Call->getArg(1);
8636   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8637   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8638 
8639   // Only warn when exactly one argument is zero.
8640   if (IsFirstArgZero == IsSecondArgZero) return;
8641 
8642   SourceRange FirstRange = FirstArg->getSourceRange();
8643   SourceRange SecondRange = SecondArg->getSourceRange();
8644 
8645   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8646 
8647   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8648       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8649 
8650   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8651   SourceRange RemovalRange;
8652   if (IsFirstArgZero) {
8653     RemovalRange = SourceRange(FirstRange.getBegin(),
8654                                SecondRange.getBegin().getLocWithOffset(-1));
8655   } else {
8656     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8657                                SecondRange.getEnd());
8658   }
8659 
8660   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8661         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8662         << FixItHint::CreateRemoval(RemovalRange);
8663 }
8664 
8665 //===--- CHECK: Standard memory functions ---------------------------------===//
8666 
8667 /// Takes the expression passed to the size_t parameter of functions
8668 /// such as memcmp, strncat, etc and warns if it's a comparison.
8669 ///
8670 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8671 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8672                                            IdentifierInfo *FnName,
8673                                            SourceLocation FnLoc,
8674                                            SourceLocation RParenLoc) {
8675   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8676   if (!Size)
8677     return false;
8678 
8679   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8680   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8681     return false;
8682 
8683   SourceRange SizeRange = Size->getSourceRange();
8684   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8685       << SizeRange << FnName;
8686   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8687       << FnName
8688       << FixItHint::CreateInsertion(
8689              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8690       << FixItHint::CreateRemoval(RParenLoc);
8691   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8692       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8693       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8694                                     ")");
8695 
8696   return true;
8697 }
8698 
8699 /// Determine whether the given type is or contains a dynamic class type
8700 /// (e.g., whether it has a vtable).
8701 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8702                                                      bool &IsContained) {
8703   // Look through array types while ignoring qualifiers.
8704   const Type *Ty = T->getBaseElementTypeUnsafe();
8705   IsContained = false;
8706 
8707   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8708   RD = RD ? RD->getDefinition() : nullptr;
8709   if (!RD || RD->isInvalidDecl())
8710     return nullptr;
8711 
8712   if (RD->isDynamicClass())
8713     return RD;
8714 
8715   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8716   // It's impossible for a class to transitively contain itself by value, so
8717   // infinite recursion is impossible.
8718   for (auto *FD : RD->fields()) {
8719     bool SubContained;
8720     if (const CXXRecordDecl *ContainedRD =
8721             getContainedDynamicClass(FD->getType(), SubContained)) {
8722       IsContained = true;
8723       return ContainedRD;
8724     }
8725   }
8726 
8727   return nullptr;
8728 }
8729 
8730 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8731   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8732     if (Unary->getKind() == UETT_SizeOf)
8733       return Unary;
8734   return nullptr;
8735 }
8736 
8737 /// If E is a sizeof expression, returns its argument expression,
8738 /// otherwise returns NULL.
8739 static const Expr *getSizeOfExprArg(const Expr *E) {
8740   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8741     if (!SizeOf->isArgumentType())
8742       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8743   return nullptr;
8744 }
8745 
8746 /// If E is a sizeof expression, returns its argument type.
8747 static QualType getSizeOfArgType(const Expr *E) {
8748   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8749     return SizeOf->getTypeOfArgument();
8750   return QualType();
8751 }
8752 
8753 namespace {
8754 
8755 struct SearchNonTrivialToInitializeField
8756     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8757   using Super =
8758       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8759 
8760   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8761 
8762   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8763                      SourceLocation SL) {
8764     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8765       asDerived().visitArray(PDIK, AT, SL);
8766       return;
8767     }
8768 
8769     Super::visitWithKind(PDIK, FT, SL);
8770   }
8771 
8772   void visitARCStrong(QualType FT, SourceLocation SL) {
8773     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8774   }
8775   void visitARCWeak(QualType FT, SourceLocation SL) {
8776     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8777   }
8778   void visitStruct(QualType FT, SourceLocation SL) {
8779     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8780       visit(FD->getType(), FD->getLocation());
8781   }
8782   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8783                   const ArrayType *AT, SourceLocation SL) {
8784     visit(getContext().getBaseElementType(AT), SL);
8785   }
8786   void visitTrivial(QualType FT, SourceLocation SL) {}
8787 
8788   static void diag(QualType RT, const Expr *E, Sema &S) {
8789     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8790   }
8791 
8792   ASTContext &getContext() { return S.getASTContext(); }
8793 
8794   const Expr *E;
8795   Sema &S;
8796 };
8797 
8798 struct SearchNonTrivialToCopyField
8799     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8800   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8801 
8802   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8803 
8804   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8805                      SourceLocation SL) {
8806     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8807       asDerived().visitArray(PCK, AT, SL);
8808       return;
8809     }
8810 
8811     Super::visitWithKind(PCK, FT, SL);
8812   }
8813 
8814   void visitARCStrong(QualType FT, SourceLocation SL) {
8815     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8816   }
8817   void visitARCWeak(QualType FT, SourceLocation SL) {
8818     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8819   }
8820   void visitStruct(QualType FT, SourceLocation SL) {
8821     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8822       visit(FD->getType(), FD->getLocation());
8823   }
8824   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8825                   SourceLocation SL) {
8826     visit(getContext().getBaseElementType(AT), SL);
8827   }
8828   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8829                 SourceLocation SL) {}
8830   void visitTrivial(QualType FT, SourceLocation SL) {}
8831   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8832 
8833   static void diag(QualType RT, const Expr *E, Sema &S) {
8834     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8835   }
8836 
8837   ASTContext &getContext() { return S.getASTContext(); }
8838 
8839   const Expr *E;
8840   Sema &S;
8841 };
8842 
8843 }
8844 
8845 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8846 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8847   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8848 
8849   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8850     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8851       return false;
8852 
8853     return doesExprLikelyComputeSize(BO->getLHS()) ||
8854            doesExprLikelyComputeSize(BO->getRHS());
8855   }
8856 
8857   return getAsSizeOfExpr(SizeofExpr) != nullptr;
8858 }
8859 
8860 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8861 ///
8862 /// \code
8863 ///   #define MACRO 0
8864 ///   foo(MACRO);
8865 ///   foo(0);
8866 /// \endcode
8867 ///
8868 /// This should return true for the first call to foo, but not for the second
8869 /// (regardless of whether foo is a macro or function).
8870 static bool isArgumentExpandedFromMacro(SourceManager &SM,
8871                                         SourceLocation CallLoc,
8872                                         SourceLocation ArgLoc) {
8873   if (!CallLoc.isMacroID())
8874     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8875 
8876   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8877          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8878 }
8879 
8880 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8881 /// last two arguments transposed.
8882 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8883   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8884     return;
8885 
8886   const Expr *SizeArg =
8887     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8888 
8889   auto isLiteralZero = [](const Expr *E) {
8890     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8891   };
8892 
8893   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8894   SourceLocation CallLoc = Call->getRParenLoc();
8895   SourceManager &SM = S.getSourceManager();
8896   if (isLiteralZero(SizeArg) &&
8897       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8898 
8899     SourceLocation DiagLoc = SizeArg->getExprLoc();
8900 
8901     // Some platforms #define bzero to __builtin_memset. See if this is the
8902     // case, and if so, emit a better diagnostic.
8903     if (BId == Builtin::BIbzero ||
8904         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
8905                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
8906       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
8907       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
8908     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
8909       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
8910       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
8911     }
8912     return;
8913   }
8914 
8915   // If the second argument to a memset is a sizeof expression and the third
8916   // isn't, this is also likely an error. This should catch
8917   // 'memset(buf, sizeof(buf), 0xff)'.
8918   if (BId == Builtin::BImemset &&
8919       doesExprLikelyComputeSize(Call->getArg(1)) &&
8920       !doesExprLikelyComputeSize(Call->getArg(2))) {
8921     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8922     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
8923     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
8924     return;
8925   }
8926 }
8927 
8928 /// Check for dangerous or invalid arguments to memset().
8929 ///
8930 /// This issues warnings on known problematic, dangerous or unspecified
8931 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
8932 /// function calls.
8933 ///
8934 /// \param Call The call expression to diagnose.
8935 void Sema::CheckMemaccessArguments(const CallExpr *Call,
8936                                    unsigned BId,
8937                                    IdentifierInfo *FnName) {
8938   assert(BId != 0);
8939 
8940   // It is possible to have a non-standard definition of memset.  Validate
8941   // we have enough arguments, and if not, abort further checking.
8942   unsigned ExpectedNumArgs =
8943       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
8944   if (Call->getNumArgs() < ExpectedNumArgs)
8945     return;
8946 
8947   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
8948                       BId == Builtin::BIstrndup ? 1 : 2);
8949   unsigned LenArg =
8950       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
8951   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
8952 
8953   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
8954                                      Call->getBeginLoc(), Call->getRParenLoc()))
8955     return;
8956 
8957   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
8958   CheckMemaccessSize(*this, BId, Call);
8959 
8960   // We have special checking when the length is a sizeof expression.
8961   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8962   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8963   llvm::FoldingSetNodeID SizeOfArgID;
8964 
8965   // Although widely used, 'bzero' is not a standard function. Be more strict
8966   // with the argument types before allowing diagnostics and only allow the
8967   // form bzero(ptr, sizeof(...)).
8968   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8969   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8970     return;
8971 
8972   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8973     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
8974     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
8975 
8976     QualType DestTy = Dest->getType();
8977     QualType PointeeTy;
8978     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8979       PointeeTy = DestPtrTy->getPointeeType();
8980 
8981       // Never warn about void type pointers. This can be used to suppress
8982       // false positives.
8983       if (PointeeTy->isVoidType())
8984         continue;
8985 
8986       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8987       // actually comparing the expressions for equality. Because computing the
8988       // expression IDs can be expensive, we only do this if the diagnostic is
8989       // enabled.
8990       if (SizeOfArg &&
8991           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8992                            SizeOfArg->getExprLoc())) {
8993         // We only compute IDs for expressions if the warning is enabled, and
8994         // cache the sizeof arg's ID.
8995         if (SizeOfArgID == llvm::FoldingSetNodeID())
8996           SizeOfArg->Profile(SizeOfArgID, Context, true);
8997         llvm::FoldingSetNodeID DestID;
8998         Dest->Profile(DestID, Context, true);
8999         if (DestID == SizeOfArgID) {
9000           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9001           //       over sizeof(src) as well.
9002           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9003           StringRef ReadableName = FnName->getName();
9004 
9005           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9006             if (UnaryOp->getOpcode() == UO_AddrOf)
9007               ActionIdx = 1; // If its an address-of operator, just remove it.
9008           if (!PointeeTy->isIncompleteType() &&
9009               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9010             ActionIdx = 2; // If the pointee's size is sizeof(char),
9011                            // suggest an explicit length.
9012 
9013           // If the function is defined as a builtin macro, do not show macro
9014           // expansion.
9015           SourceLocation SL = SizeOfArg->getExprLoc();
9016           SourceRange DSR = Dest->getSourceRange();
9017           SourceRange SSR = SizeOfArg->getSourceRange();
9018           SourceManager &SM = getSourceManager();
9019 
9020           if (SM.isMacroArgExpansion(SL)) {
9021             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9022             SL = SM.getSpellingLoc(SL);
9023             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9024                              SM.getSpellingLoc(DSR.getEnd()));
9025             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9026                              SM.getSpellingLoc(SSR.getEnd()));
9027           }
9028 
9029           DiagRuntimeBehavior(SL, SizeOfArg,
9030                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9031                                 << ReadableName
9032                                 << PointeeTy
9033                                 << DestTy
9034                                 << DSR
9035                                 << SSR);
9036           DiagRuntimeBehavior(SL, SizeOfArg,
9037                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9038                                 << ActionIdx
9039                                 << SSR);
9040 
9041           break;
9042         }
9043       }
9044 
9045       // Also check for cases where the sizeof argument is the exact same
9046       // type as the memory argument, and where it points to a user-defined
9047       // record type.
9048       if (SizeOfArgTy != QualType()) {
9049         if (PointeeTy->isRecordType() &&
9050             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9051           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9052                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9053                                 << FnName << SizeOfArgTy << ArgIdx
9054                                 << PointeeTy << Dest->getSourceRange()
9055                                 << LenExpr->getSourceRange());
9056           break;
9057         }
9058       }
9059     } else if (DestTy->isArrayType()) {
9060       PointeeTy = DestTy;
9061     }
9062 
9063     if (PointeeTy == QualType())
9064       continue;
9065 
9066     // Always complain about dynamic classes.
9067     bool IsContained;
9068     if (const CXXRecordDecl *ContainedRD =
9069             getContainedDynamicClass(PointeeTy, IsContained)) {
9070 
9071       unsigned OperationType = 0;
9072       // "overwritten" if we're warning about the destination for any call
9073       // but memcmp; otherwise a verb appropriate to the call.
9074       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
9075         if (BId == Builtin::BImemcpy)
9076           OperationType = 1;
9077         else if(BId == Builtin::BImemmove)
9078           OperationType = 2;
9079         else if (BId == Builtin::BImemcmp)
9080           OperationType = 3;
9081       }
9082 
9083       DiagRuntimeBehavior(
9084         Dest->getExprLoc(), Dest,
9085         PDiag(diag::warn_dyn_class_memaccess)
9086           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
9087           << FnName << IsContained << ContainedRD << OperationType
9088           << Call->getCallee()->getSourceRange());
9089     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9090              BId != Builtin::BImemset)
9091       DiagRuntimeBehavior(
9092         Dest->getExprLoc(), Dest,
9093         PDiag(diag::warn_arc_object_memaccess)
9094           << ArgIdx << FnName << PointeeTy
9095           << Call->getCallee()->getSourceRange());
9096     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9097       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9098           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9099         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9100                             PDiag(diag::warn_cstruct_memaccess)
9101                                 << ArgIdx << FnName << PointeeTy << 0);
9102         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9103       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9104                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9105         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9106                             PDiag(diag::warn_cstruct_memaccess)
9107                                 << ArgIdx << FnName << PointeeTy << 1);
9108         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9109       } else {
9110         continue;
9111       }
9112     } else
9113       continue;
9114 
9115     DiagRuntimeBehavior(
9116       Dest->getExprLoc(), Dest,
9117       PDiag(diag::note_bad_memaccess_silence)
9118         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9119     break;
9120   }
9121 }
9122 
9123 // A little helper routine: ignore addition and subtraction of integer literals.
9124 // This intentionally does not ignore all integer constant expressions because
9125 // we don't want to remove sizeof().
9126 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9127   Ex = Ex->IgnoreParenCasts();
9128 
9129   while (true) {
9130     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9131     if (!BO || !BO->isAdditiveOp())
9132       break;
9133 
9134     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9135     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9136 
9137     if (isa<IntegerLiteral>(RHS))
9138       Ex = LHS;
9139     else if (isa<IntegerLiteral>(LHS))
9140       Ex = RHS;
9141     else
9142       break;
9143   }
9144 
9145   return Ex;
9146 }
9147 
9148 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9149                                                       ASTContext &Context) {
9150   // Only handle constant-sized or VLAs, but not flexible members.
9151   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9152     // Only issue the FIXIT for arrays of size > 1.
9153     if (CAT->getSize().getSExtValue() <= 1)
9154       return false;
9155   } else if (!Ty->isVariableArrayType()) {
9156     return false;
9157   }
9158   return true;
9159 }
9160 
9161 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9162 // be the size of the source, instead of the destination.
9163 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9164                                     IdentifierInfo *FnName) {
9165 
9166   // Don't crash if the user has the wrong number of arguments
9167   unsigned NumArgs = Call->getNumArgs();
9168   if ((NumArgs != 3) && (NumArgs != 4))
9169     return;
9170 
9171   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9172   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9173   const Expr *CompareWithSrc = nullptr;
9174 
9175   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9176                                      Call->getBeginLoc(), Call->getRParenLoc()))
9177     return;
9178 
9179   // Look for 'strlcpy(dst, x, sizeof(x))'
9180   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9181     CompareWithSrc = Ex;
9182   else {
9183     // Look for 'strlcpy(dst, x, strlen(x))'
9184     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9185       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9186           SizeCall->getNumArgs() == 1)
9187         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9188     }
9189   }
9190 
9191   if (!CompareWithSrc)
9192     return;
9193 
9194   // Determine if the argument to sizeof/strlen is equal to the source
9195   // argument.  In principle there's all kinds of things you could do
9196   // here, for instance creating an == expression and evaluating it with
9197   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9198   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9199   if (!SrcArgDRE)
9200     return;
9201 
9202   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9203   if (!CompareWithSrcDRE ||
9204       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9205     return;
9206 
9207   const Expr *OriginalSizeArg = Call->getArg(2);
9208   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9209       << OriginalSizeArg->getSourceRange() << FnName;
9210 
9211   // Output a FIXIT hint if the destination is an array (rather than a
9212   // pointer to an array).  This could be enhanced to handle some
9213   // pointers if we know the actual size, like if DstArg is 'array+2'
9214   // we could say 'sizeof(array)-2'.
9215   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9216   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9217     return;
9218 
9219   SmallString<128> sizeString;
9220   llvm::raw_svector_ostream OS(sizeString);
9221   OS << "sizeof(";
9222   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9223   OS << ")";
9224 
9225   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9226       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9227                                       OS.str());
9228 }
9229 
9230 /// Check if two expressions refer to the same declaration.
9231 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9232   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9233     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9234       return D1->getDecl() == D2->getDecl();
9235   return false;
9236 }
9237 
9238 static const Expr *getStrlenExprArg(const Expr *E) {
9239   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9240     const FunctionDecl *FD = CE->getDirectCallee();
9241     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9242       return nullptr;
9243     return CE->getArg(0)->IgnoreParenCasts();
9244   }
9245   return nullptr;
9246 }
9247 
9248 // Warn on anti-patterns as the 'size' argument to strncat.
9249 // The correct size argument should look like following:
9250 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9251 void Sema::CheckStrncatArguments(const CallExpr *CE,
9252                                  IdentifierInfo *FnName) {
9253   // Don't crash if the user has the wrong number of arguments.
9254   if (CE->getNumArgs() < 3)
9255     return;
9256   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9257   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9258   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9259 
9260   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9261                                      CE->getRParenLoc()))
9262     return;
9263 
9264   // Identify common expressions, which are wrongly used as the size argument
9265   // to strncat and may lead to buffer overflows.
9266   unsigned PatternType = 0;
9267   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9268     // - sizeof(dst)
9269     if (referToTheSameDecl(SizeOfArg, DstArg))
9270       PatternType = 1;
9271     // - sizeof(src)
9272     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9273       PatternType = 2;
9274   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9275     if (BE->getOpcode() == BO_Sub) {
9276       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9277       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9278       // - sizeof(dst) - strlen(dst)
9279       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9280           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9281         PatternType = 1;
9282       // - sizeof(src) - (anything)
9283       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9284         PatternType = 2;
9285     }
9286   }
9287 
9288   if (PatternType == 0)
9289     return;
9290 
9291   // Generate the diagnostic.
9292   SourceLocation SL = LenArg->getBeginLoc();
9293   SourceRange SR = LenArg->getSourceRange();
9294   SourceManager &SM = getSourceManager();
9295 
9296   // If the function is defined as a builtin macro, do not show macro expansion.
9297   if (SM.isMacroArgExpansion(SL)) {
9298     SL = SM.getSpellingLoc(SL);
9299     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9300                      SM.getSpellingLoc(SR.getEnd()));
9301   }
9302 
9303   // Check if the destination is an array (rather than a pointer to an array).
9304   QualType DstTy = DstArg->getType();
9305   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9306                                                                     Context);
9307   if (!isKnownSizeArray) {
9308     if (PatternType == 1)
9309       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9310     else
9311       Diag(SL, diag::warn_strncat_src_size) << SR;
9312     return;
9313   }
9314 
9315   if (PatternType == 1)
9316     Diag(SL, diag::warn_strncat_large_size) << SR;
9317   else
9318     Diag(SL, diag::warn_strncat_src_size) << SR;
9319 
9320   SmallString<128> sizeString;
9321   llvm::raw_svector_ostream OS(sizeString);
9322   OS << "sizeof(";
9323   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9324   OS << ") - ";
9325   OS << "strlen(";
9326   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9327   OS << ") - 1";
9328 
9329   Diag(SL, diag::note_strncat_wrong_size)
9330     << FixItHint::CreateReplacement(SR, OS.str());
9331 }
9332 
9333 void
9334 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9335                          SourceLocation ReturnLoc,
9336                          bool isObjCMethod,
9337                          const AttrVec *Attrs,
9338                          const FunctionDecl *FD) {
9339   // Check if the return value is null but should not be.
9340   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9341        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9342       CheckNonNullExpr(*this, RetValExp))
9343     Diag(ReturnLoc, diag::warn_null_ret)
9344       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9345 
9346   // C++11 [basic.stc.dynamic.allocation]p4:
9347   //   If an allocation function declared with a non-throwing
9348   //   exception-specification fails to allocate storage, it shall return
9349   //   a null pointer. Any other allocation function that fails to allocate
9350   //   storage shall indicate failure only by throwing an exception [...]
9351   if (FD) {
9352     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9353     if (Op == OO_New || Op == OO_Array_New) {
9354       const FunctionProtoType *Proto
9355         = FD->getType()->castAs<FunctionProtoType>();
9356       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9357           CheckNonNullExpr(*this, RetValExp))
9358         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9359           << FD << getLangOpts().CPlusPlus11;
9360     }
9361   }
9362 }
9363 
9364 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9365 
9366 /// Check for comparisons of floating point operands using != and ==.
9367 /// Issue a warning if these are no self-comparisons, as they are not likely
9368 /// to do what the programmer intended.
9369 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9370   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9371   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9372 
9373   // Special case: check for x == x (which is OK).
9374   // Do not emit warnings for such cases.
9375   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9376     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9377       if (DRL->getDecl() == DRR->getDecl())
9378         return;
9379 
9380   // Special case: check for comparisons against literals that can be exactly
9381   //  represented by APFloat.  In such cases, do not emit a warning.  This
9382   //  is a heuristic: often comparison against such literals are used to
9383   //  detect if a value in a variable has not changed.  This clearly can
9384   //  lead to false negatives.
9385   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9386     if (FLL->isExact())
9387       return;
9388   } else
9389     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9390       if (FLR->isExact())
9391         return;
9392 
9393   // Check for comparisons with builtin types.
9394   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9395     if (CL->getBuiltinCallee())
9396       return;
9397 
9398   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9399     if (CR->getBuiltinCallee())
9400       return;
9401 
9402   // Emit the diagnostic.
9403   Diag(Loc, diag::warn_floatingpoint_eq)
9404     << LHS->getSourceRange() << RHS->getSourceRange();
9405 }
9406 
9407 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9408 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9409 
9410 namespace {
9411 
9412 /// Structure recording the 'active' range of an integer-valued
9413 /// expression.
9414 struct IntRange {
9415   /// The number of bits active in the int.
9416   unsigned Width;
9417 
9418   /// True if the int is known not to have negative values.
9419   bool NonNegative;
9420 
9421   IntRange(unsigned Width, bool NonNegative)
9422       : Width(Width), NonNegative(NonNegative) {}
9423 
9424   /// Returns the range of the bool type.
9425   static IntRange forBoolType() {
9426     return IntRange(1, true);
9427   }
9428 
9429   /// Returns the range of an opaque value of the given integral type.
9430   static IntRange forValueOfType(ASTContext &C, QualType T) {
9431     return forValueOfCanonicalType(C,
9432                           T->getCanonicalTypeInternal().getTypePtr());
9433   }
9434 
9435   /// Returns the range of an opaque value of a canonical integral type.
9436   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9437     assert(T->isCanonicalUnqualified());
9438 
9439     if (const VectorType *VT = dyn_cast<VectorType>(T))
9440       T = VT->getElementType().getTypePtr();
9441     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9442       T = CT->getElementType().getTypePtr();
9443     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9444       T = AT->getValueType().getTypePtr();
9445 
9446     if (!C.getLangOpts().CPlusPlus) {
9447       // For enum types in C code, use the underlying datatype.
9448       if (const EnumType *ET = dyn_cast<EnumType>(T))
9449         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9450     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9451       // For enum types in C++, use the known bit width of the enumerators.
9452       EnumDecl *Enum = ET->getDecl();
9453       // In C++11, enums can have a fixed underlying type. Use this type to
9454       // compute the range.
9455       if (Enum->isFixed()) {
9456         return IntRange(C.getIntWidth(QualType(T, 0)),
9457                         !ET->isSignedIntegerOrEnumerationType());
9458       }
9459 
9460       unsigned NumPositive = Enum->getNumPositiveBits();
9461       unsigned NumNegative = Enum->getNumNegativeBits();
9462 
9463       if (NumNegative == 0)
9464         return IntRange(NumPositive, true/*NonNegative*/);
9465       else
9466         return IntRange(std::max(NumPositive + 1, NumNegative),
9467                         false/*NonNegative*/);
9468     }
9469 
9470     const BuiltinType *BT = cast<BuiltinType>(T);
9471     assert(BT->isInteger());
9472 
9473     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9474   }
9475 
9476   /// Returns the "target" range of a canonical integral type, i.e.
9477   /// the range of values expressible in the type.
9478   ///
9479   /// This matches forValueOfCanonicalType except that enums have the
9480   /// full range of their type, not the range of their enumerators.
9481   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9482     assert(T->isCanonicalUnqualified());
9483 
9484     if (const VectorType *VT = dyn_cast<VectorType>(T))
9485       T = VT->getElementType().getTypePtr();
9486     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9487       T = CT->getElementType().getTypePtr();
9488     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9489       T = AT->getValueType().getTypePtr();
9490     if (const EnumType *ET = dyn_cast<EnumType>(T))
9491       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9492 
9493     const BuiltinType *BT = cast<BuiltinType>(T);
9494     assert(BT->isInteger());
9495 
9496     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9497   }
9498 
9499   /// Returns the supremum of two ranges: i.e. their conservative merge.
9500   static IntRange join(IntRange L, IntRange R) {
9501     return IntRange(std::max(L.Width, R.Width),
9502                     L.NonNegative && R.NonNegative);
9503   }
9504 
9505   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9506   static IntRange meet(IntRange L, IntRange R) {
9507     return IntRange(std::min(L.Width, R.Width),
9508                     L.NonNegative || R.NonNegative);
9509   }
9510 };
9511 
9512 } // namespace
9513 
9514 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9515                               unsigned MaxWidth) {
9516   if (value.isSigned() && value.isNegative())
9517     return IntRange(value.getMinSignedBits(), false);
9518 
9519   if (value.getBitWidth() > MaxWidth)
9520     value = value.trunc(MaxWidth);
9521 
9522   // isNonNegative() just checks the sign bit without considering
9523   // signedness.
9524   return IntRange(value.getActiveBits(), true);
9525 }
9526 
9527 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9528                               unsigned MaxWidth) {
9529   if (result.isInt())
9530     return GetValueRange(C, result.getInt(), MaxWidth);
9531 
9532   if (result.isVector()) {
9533     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9534     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9535       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9536       R = IntRange::join(R, El);
9537     }
9538     return R;
9539   }
9540 
9541   if (result.isComplexInt()) {
9542     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9543     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9544     return IntRange::join(R, I);
9545   }
9546 
9547   // This can happen with lossless casts to intptr_t of "based" lvalues.
9548   // Assume it might use arbitrary bits.
9549   // FIXME: The only reason we need to pass the type in here is to get
9550   // the sign right on this one case.  It would be nice if APValue
9551   // preserved this.
9552   assert(result.isLValue() || result.isAddrLabelDiff());
9553   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9554 }
9555 
9556 static QualType GetExprType(const Expr *E) {
9557   QualType Ty = E->getType();
9558   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9559     Ty = AtomicRHS->getValueType();
9560   return Ty;
9561 }
9562 
9563 /// Pseudo-evaluate the given integer expression, estimating the
9564 /// range of values it might take.
9565 ///
9566 /// \param MaxWidth - the width to which the value will be truncated
9567 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9568   E = E->IgnoreParens();
9569 
9570   // Try a full evaluation first.
9571   Expr::EvalResult result;
9572   if (E->EvaluateAsRValue(result, C))
9573     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9574 
9575   // I think we only want to look through implicit casts here; if the
9576   // user has an explicit widening cast, we should treat the value as
9577   // being of the new, wider type.
9578   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9579     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9580       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9581 
9582     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9583 
9584     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9585                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9586 
9587     // Assume that non-integer casts can span the full range of the type.
9588     if (!isIntegerCast)
9589       return OutputTypeRange;
9590 
9591     IntRange SubRange
9592       = GetExprRange(C, CE->getSubExpr(),
9593                      std::min(MaxWidth, OutputTypeRange.Width));
9594 
9595     // Bail out if the subexpr's range is as wide as the cast type.
9596     if (SubRange.Width >= OutputTypeRange.Width)
9597       return OutputTypeRange;
9598 
9599     // Otherwise, we take the smaller width, and we're non-negative if
9600     // either the output type or the subexpr is.
9601     return IntRange(SubRange.Width,
9602                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9603   }
9604 
9605   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9606     // If we can fold the condition, just take that operand.
9607     bool CondResult;
9608     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9609       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9610                                         : CO->getFalseExpr(),
9611                           MaxWidth);
9612 
9613     // Otherwise, conservatively merge.
9614     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9615     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9616     return IntRange::join(L, R);
9617   }
9618 
9619   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9620     switch (BO->getOpcode()) {
9621     case BO_Cmp:
9622       llvm_unreachable("builtin <=> should have class type");
9623 
9624     // Boolean-valued operations are single-bit and positive.
9625     case BO_LAnd:
9626     case BO_LOr:
9627     case BO_LT:
9628     case BO_GT:
9629     case BO_LE:
9630     case BO_GE:
9631     case BO_EQ:
9632     case BO_NE:
9633       return IntRange::forBoolType();
9634 
9635     // The type of the assignments is the type of the LHS, so the RHS
9636     // is not necessarily the same type.
9637     case BO_MulAssign:
9638     case BO_DivAssign:
9639     case BO_RemAssign:
9640     case BO_AddAssign:
9641     case BO_SubAssign:
9642     case BO_XorAssign:
9643     case BO_OrAssign:
9644       // TODO: bitfields?
9645       return IntRange::forValueOfType(C, GetExprType(E));
9646 
9647     // Simple assignments just pass through the RHS, which will have
9648     // been coerced to the LHS type.
9649     case BO_Assign:
9650       // TODO: bitfields?
9651       return GetExprRange(C, BO->getRHS(), MaxWidth);
9652 
9653     // Operations with opaque sources are black-listed.
9654     case BO_PtrMemD:
9655     case BO_PtrMemI:
9656       return IntRange::forValueOfType(C, GetExprType(E));
9657 
9658     // Bitwise-and uses the *infinum* of the two source ranges.
9659     case BO_And:
9660     case BO_AndAssign:
9661       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9662                             GetExprRange(C, BO->getRHS(), MaxWidth));
9663 
9664     // Left shift gets black-listed based on a judgement call.
9665     case BO_Shl:
9666       // ...except that we want to treat '1 << (blah)' as logically
9667       // positive.  It's an important idiom.
9668       if (IntegerLiteral *I
9669             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9670         if (I->getValue() == 1) {
9671           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9672           return IntRange(R.Width, /*NonNegative*/ true);
9673         }
9674       }
9675       LLVM_FALLTHROUGH;
9676 
9677     case BO_ShlAssign:
9678       return IntRange::forValueOfType(C, GetExprType(E));
9679 
9680     // Right shift by a constant can narrow its left argument.
9681     case BO_Shr:
9682     case BO_ShrAssign: {
9683       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9684 
9685       // If the shift amount is a positive constant, drop the width by
9686       // that much.
9687       llvm::APSInt shift;
9688       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9689           shift.isNonNegative()) {
9690         unsigned zext = shift.getZExtValue();
9691         if (zext >= L.Width)
9692           L.Width = (L.NonNegative ? 0 : 1);
9693         else
9694           L.Width -= zext;
9695       }
9696 
9697       return L;
9698     }
9699 
9700     // Comma acts as its right operand.
9701     case BO_Comma:
9702       return GetExprRange(C, BO->getRHS(), MaxWidth);
9703 
9704     // Black-list pointer subtractions.
9705     case BO_Sub:
9706       if (BO->getLHS()->getType()->isPointerType())
9707         return IntRange::forValueOfType(C, GetExprType(E));
9708       break;
9709 
9710     // The width of a division result is mostly determined by the size
9711     // of the LHS.
9712     case BO_Div: {
9713       // Don't 'pre-truncate' the operands.
9714       unsigned opWidth = C.getIntWidth(GetExprType(E));
9715       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9716 
9717       // If the divisor is constant, use that.
9718       llvm::APSInt divisor;
9719       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9720         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9721         if (log2 >= L.Width)
9722           L.Width = (L.NonNegative ? 0 : 1);
9723         else
9724           L.Width = std::min(L.Width - log2, MaxWidth);
9725         return L;
9726       }
9727 
9728       // Otherwise, just use the LHS's width.
9729       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9730       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9731     }
9732 
9733     // The result of a remainder can't be larger than the result of
9734     // either side.
9735     case BO_Rem: {
9736       // Don't 'pre-truncate' the operands.
9737       unsigned opWidth = C.getIntWidth(GetExprType(E));
9738       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9739       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9740 
9741       IntRange meet = IntRange::meet(L, R);
9742       meet.Width = std::min(meet.Width, MaxWidth);
9743       return meet;
9744     }
9745 
9746     // The default behavior is okay for these.
9747     case BO_Mul:
9748     case BO_Add:
9749     case BO_Xor:
9750     case BO_Or:
9751       break;
9752     }
9753 
9754     // The default case is to treat the operation as if it were closed
9755     // on the narrowest type that encompasses both operands.
9756     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9757     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9758     return IntRange::join(L, R);
9759   }
9760 
9761   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9762     switch (UO->getOpcode()) {
9763     // Boolean-valued operations are white-listed.
9764     case UO_LNot:
9765       return IntRange::forBoolType();
9766 
9767     // Operations with opaque sources are black-listed.
9768     case UO_Deref:
9769     case UO_AddrOf: // should be impossible
9770       return IntRange::forValueOfType(C, GetExprType(E));
9771 
9772     default:
9773       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9774     }
9775   }
9776 
9777   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9778     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9779 
9780   if (const auto *BitField = E->getSourceBitField())
9781     return IntRange(BitField->getBitWidthValue(C),
9782                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9783 
9784   return IntRange::forValueOfType(C, GetExprType(E));
9785 }
9786 
9787 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9788   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9789 }
9790 
9791 /// Checks whether the given value, which currently has the given
9792 /// source semantics, has the same value when coerced through the
9793 /// target semantics.
9794 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9795                                  const llvm::fltSemantics &Src,
9796                                  const llvm::fltSemantics &Tgt) {
9797   llvm::APFloat truncated = value;
9798 
9799   bool ignored;
9800   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9801   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9802 
9803   return truncated.bitwiseIsEqual(value);
9804 }
9805 
9806 /// Checks whether the given value, which currently has the given
9807 /// source semantics, has the same value when coerced through the
9808 /// target semantics.
9809 ///
9810 /// The value might be a vector of floats (or a complex number).
9811 static bool IsSameFloatAfterCast(const APValue &value,
9812                                  const llvm::fltSemantics &Src,
9813                                  const llvm::fltSemantics &Tgt) {
9814   if (value.isFloat())
9815     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9816 
9817   if (value.isVector()) {
9818     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9819       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9820         return false;
9821     return true;
9822   }
9823 
9824   assert(value.isComplexFloat());
9825   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9826           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9827 }
9828 
9829 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9830 
9831 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9832   // Suppress cases where we are comparing against an enum constant.
9833   if (const DeclRefExpr *DR =
9834       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9835     if (isa<EnumConstantDecl>(DR->getDecl()))
9836       return true;
9837 
9838   // Suppress cases where the '0' value is expanded from a macro.
9839   if (E->getBeginLoc().isMacroID())
9840     return true;
9841 
9842   return false;
9843 }
9844 
9845 static bool isKnownToHaveUnsignedValue(Expr *E) {
9846   return E->getType()->isIntegerType() &&
9847          (!E->getType()->isSignedIntegerType() ||
9848           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9849 }
9850 
9851 namespace {
9852 /// The promoted range of values of a type. In general this has the
9853 /// following structure:
9854 ///
9855 ///     |-----------| . . . |-----------|
9856 ///     ^           ^       ^           ^
9857 ///    Min       HoleMin  HoleMax      Max
9858 ///
9859 /// ... where there is only a hole if a signed type is promoted to unsigned
9860 /// (in which case Min and Max are the smallest and largest representable
9861 /// values).
9862 struct PromotedRange {
9863   // Min, or HoleMax if there is a hole.
9864   llvm::APSInt PromotedMin;
9865   // Max, or HoleMin if there is a hole.
9866   llvm::APSInt PromotedMax;
9867 
9868   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9869     if (R.Width == 0)
9870       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9871     else if (R.Width >= BitWidth && !Unsigned) {
9872       // Promotion made the type *narrower*. This happens when promoting
9873       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9874       // Treat all values of 'signed int' as being in range for now.
9875       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9876       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9877     } else {
9878       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9879                         .extOrTrunc(BitWidth);
9880       PromotedMin.setIsUnsigned(Unsigned);
9881 
9882       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9883                         .extOrTrunc(BitWidth);
9884       PromotedMax.setIsUnsigned(Unsigned);
9885     }
9886   }
9887 
9888   // Determine whether this range is contiguous (has no hole).
9889   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9890 
9891   // Where a constant value is within the range.
9892   enum ComparisonResult {
9893     LT = 0x1,
9894     LE = 0x2,
9895     GT = 0x4,
9896     GE = 0x8,
9897     EQ = 0x10,
9898     NE = 0x20,
9899     InRangeFlag = 0x40,
9900 
9901     Less = LE | LT | NE,
9902     Min = LE | InRangeFlag,
9903     InRange = InRangeFlag,
9904     Max = GE | InRangeFlag,
9905     Greater = GE | GT | NE,
9906 
9907     OnlyValue = LE | GE | EQ | InRangeFlag,
9908     InHole = NE
9909   };
9910 
9911   ComparisonResult compare(const llvm::APSInt &Value) const {
9912     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9913            Value.isUnsigned() == PromotedMin.isUnsigned());
9914     if (!isContiguous()) {
9915       assert(Value.isUnsigned() && "discontiguous range for signed compare");
9916       if (Value.isMinValue()) return Min;
9917       if (Value.isMaxValue()) return Max;
9918       if (Value >= PromotedMin) return InRange;
9919       if (Value <= PromotedMax) return InRange;
9920       return InHole;
9921     }
9922 
9923     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9924     case -1: return Less;
9925     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9926     case 1:
9927       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9928       case -1: return InRange;
9929       case 0: return Max;
9930       case 1: return Greater;
9931       }
9932     }
9933 
9934     llvm_unreachable("impossible compare result");
9935   }
9936 
9937   static llvm::Optional<StringRef>
9938   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9939     if (Op == BO_Cmp) {
9940       ComparisonResult LTFlag = LT, GTFlag = GT;
9941       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9942 
9943       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9944       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9945       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9946       return llvm::None;
9947     }
9948 
9949     ComparisonResult TrueFlag, FalseFlag;
9950     if (Op == BO_EQ) {
9951       TrueFlag = EQ;
9952       FalseFlag = NE;
9953     } else if (Op == BO_NE) {
9954       TrueFlag = NE;
9955       FalseFlag = EQ;
9956     } else {
9957       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9958         TrueFlag = LT;
9959         FalseFlag = GE;
9960       } else {
9961         TrueFlag = GT;
9962         FalseFlag = LE;
9963       }
9964       if (Op == BO_GE || Op == BO_LE)
9965         std::swap(TrueFlag, FalseFlag);
9966     }
9967     if (R & TrueFlag)
9968       return StringRef("true");
9969     if (R & FalseFlag)
9970       return StringRef("false");
9971     return llvm::None;
9972   }
9973 };
9974 }
9975 
9976 static bool HasEnumType(Expr *E) {
9977   // Strip off implicit integral promotions.
9978   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9979     if (ICE->getCastKind() != CK_IntegralCast &&
9980         ICE->getCastKind() != CK_NoOp)
9981       break;
9982     E = ICE->getSubExpr();
9983   }
9984 
9985   return E->getType()->isEnumeralType();
9986 }
9987 
9988 static int classifyConstantValue(Expr *Constant) {
9989   // The values of this enumeration are used in the diagnostics
9990   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9991   enum ConstantValueKind {
9992     Miscellaneous = 0,
9993     LiteralTrue,
9994     LiteralFalse
9995   };
9996   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9997     return BL->getValue() ? ConstantValueKind::LiteralTrue
9998                           : ConstantValueKind::LiteralFalse;
9999   return ConstantValueKind::Miscellaneous;
10000 }
10001 
10002 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10003                                         Expr *Constant, Expr *Other,
10004                                         const llvm::APSInt &Value,
10005                                         bool RhsConstant) {
10006   if (S.inTemplateInstantiation())
10007     return false;
10008 
10009   Expr *OriginalOther = Other;
10010 
10011   Constant = Constant->IgnoreParenImpCasts();
10012   Other = Other->IgnoreParenImpCasts();
10013 
10014   // Suppress warnings on tautological comparisons between values of the same
10015   // enumeration type. There are only two ways we could warn on this:
10016   //  - If the constant is outside the range of representable values of
10017   //    the enumeration. In such a case, we should warn about the cast
10018   //    to enumeration type, not about the comparison.
10019   //  - If the constant is the maximum / minimum in-range value. For an
10020   //    enumeratin type, such comparisons can be meaningful and useful.
10021   if (Constant->getType()->isEnumeralType() &&
10022       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10023     return false;
10024 
10025   // TODO: Investigate using GetExprRange() to get tighter bounds
10026   // on the bit ranges.
10027   QualType OtherT = Other->getType();
10028   if (const auto *AT = OtherT->getAs<AtomicType>())
10029     OtherT = AT->getValueType();
10030   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10031 
10032   // Whether we're treating Other as being a bool because of the form of
10033   // expression despite it having another type (typically 'int' in C).
10034   bool OtherIsBooleanDespiteType =
10035       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10036   if (OtherIsBooleanDespiteType)
10037     OtherRange = IntRange::forBoolType();
10038 
10039   // Determine the promoted range of the other type and see if a comparison of
10040   // the constant against that range is tautological.
10041   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10042                                    Value.isUnsigned());
10043   auto Cmp = OtherPromotedRange.compare(Value);
10044   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10045   if (!Result)
10046     return false;
10047 
10048   // Suppress the diagnostic for an in-range comparison if the constant comes
10049   // from a macro or enumerator. We don't want to diagnose
10050   //
10051   //   some_long_value <= INT_MAX
10052   //
10053   // when sizeof(int) == sizeof(long).
10054   bool InRange = Cmp & PromotedRange::InRangeFlag;
10055   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10056     return false;
10057 
10058   // If this is a comparison to an enum constant, include that
10059   // constant in the diagnostic.
10060   const EnumConstantDecl *ED = nullptr;
10061   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10062     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10063 
10064   // Should be enough for uint128 (39 decimal digits)
10065   SmallString<64> PrettySourceValue;
10066   llvm::raw_svector_ostream OS(PrettySourceValue);
10067   if (ED)
10068     OS << '\'' << *ED << "' (" << Value << ")";
10069   else
10070     OS << Value;
10071 
10072   // FIXME: We use a somewhat different formatting for the in-range cases and
10073   // cases involving boolean values for historical reasons. We should pick a
10074   // consistent way of presenting these diagnostics.
10075   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10076     S.DiagRuntimeBehavior(
10077       E->getOperatorLoc(), E,
10078       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10079                        : diag::warn_tautological_bool_compare)
10080           << OS.str() << classifyConstantValue(Constant)
10081           << OtherT << OtherIsBooleanDespiteType << *Result
10082           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10083   } else {
10084     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10085                         ? (HasEnumType(OriginalOther)
10086                                ? diag::warn_unsigned_enum_always_true_comparison
10087                                : diag::warn_unsigned_always_true_comparison)
10088                         : diag::warn_tautological_constant_compare;
10089 
10090     S.Diag(E->getOperatorLoc(), Diag)
10091         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10092         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10093   }
10094 
10095   return true;
10096 }
10097 
10098 /// Analyze the operands of the given comparison.  Implements the
10099 /// fallback case from AnalyzeComparison.
10100 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10101   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10102   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10103 }
10104 
10105 /// Implements -Wsign-compare.
10106 ///
10107 /// \param E the binary operator to check for warnings
10108 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10109   // The type the comparison is being performed in.
10110   QualType T = E->getLHS()->getType();
10111 
10112   // Only analyze comparison operators where both sides have been converted to
10113   // the same type.
10114   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10115     return AnalyzeImpConvsInComparison(S, E);
10116 
10117   // Don't analyze value-dependent comparisons directly.
10118   if (E->isValueDependent())
10119     return AnalyzeImpConvsInComparison(S, E);
10120 
10121   Expr *LHS = E->getLHS();
10122   Expr *RHS = E->getRHS();
10123 
10124   if (T->isIntegralType(S.Context)) {
10125     llvm::APSInt RHSValue;
10126     llvm::APSInt LHSValue;
10127 
10128     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10129     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10130 
10131     // We don't care about expressions whose result is a constant.
10132     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10133       return AnalyzeImpConvsInComparison(S, E);
10134 
10135     // We only care about expressions where just one side is literal
10136     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10137       // Is the constant on the RHS or LHS?
10138       const bool RhsConstant = IsRHSIntegralLiteral;
10139       Expr *Const = RhsConstant ? RHS : LHS;
10140       Expr *Other = RhsConstant ? LHS : RHS;
10141       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10142 
10143       // Check whether an integer constant comparison results in a value
10144       // of 'true' or 'false'.
10145       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10146         return AnalyzeImpConvsInComparison(S, E);
10147     }
10148   }
10149 
10150   if (!T->hasUnsignedIntegerRepresentation()) {
10151     // We don't do anything special if this isn't an unsigned integral
10152     // comparison:  we're only interested in integral comparisons, and
10153     // signed comparisons only happen in cases we don't care to warn about.
10154     return AnalyzeImpConvsInComparison(S, E);
10155   }
10156 
10157   LHS = LHS->IgnoreParenImpCasts();
10158   RHS = RHS->IgnoreParenImpCasts();
10159 
10160   if (!S.getLangOpts().CPlusPlus) {
10161     // Avoid warning about comparison of integers with different signs when
10162     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10163     // the type of `E`.
10164     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10165       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10166     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10167       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10168   }
10169 
10170   // Check to see if one of the (unmodified) operands is of different
10171   // signedness.
10172   Expr *signedOperand, *unsignedOperand;
10173   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10174     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10175            "unsigned comparison between two signed integer expressions?");
10176     signedOperand = LHS;
10177     unsignedOperand = RHS;
10178   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10179     signedOperand = RHS;
10180     unsignedOperand = LHS;
10181   } else {
10182     return AnalyzeImpConvsInComparison(S, E);
10183   }
10184 
10185   // Otherwise, calculate the effective range of the signed operand.
10186   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10187 
10188   // Go ahead and analyze implicit conversions in the operands.  Note
10189   // that we skip the implicit conversions on both sides.
10190   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10191   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10192 
10193   // If the signed range is non-negative, -Wsign-compare won't fire.
10194   if (signedRange.NonNegative)
10195     return;
10196 
10197   // For (in)equality comparisons, if the unsigned operand is a
10198   // constant which cannot collide with a overflowed signed operand,
10199   // then reinterpreting the signed operand as unsigned will not
10200   // change the result of the comparison.
10201   if (E->isEqualityOp()) {
10202     unsigned comparisonWidth = S.Context.getIntWidth(T);
10203     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10204 
10205     // We should never be unable to prove that the unsigned operand is
10206     // non-negative.
10207     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10208 
10209     if (unsignedRange.Width < comparisonWidth)
10210       return;
10211   }
10212 
10213   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10214     S.PDiag(diag::warn_mixed_sign_comparison)
10215       << LHS->getType() << RHS->getType()
10216       << LHS->getSourceRange() << RHS->getSourceRange());
10217 }
10218 
10219 /// Analyzes an attempt to assign the given value to a bitfield.
10220 ///
10221 /// Returns true if there was something fishy about the attempt.
10222 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10223                                       SourceLocation InitLoc) {
10224   assert(Bitfield->isBitField());
10225   if (Bitfield->isInvalidDecl())
10226     return false;
10227 
10228   // White-list bool bitfields.
10229   QualType BitfieldType = Bitfield->getType();
10230   if (BitfieldType->isBooleanType())
10231      return false;
10232 
10233   if (BitfieldType->isEnumeralType()) {
10234     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10235     // If the underlying enum type was not explicitly specified as an unsigned
10236     // type and the enum contain only positive values, MSVC++ will cause an
10237     // inconsistency by storing this as a signed type.
10238     if (S.getLangOpts().CPlusPlus11 &&
10239         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10240         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10241         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10242       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10243         << BitfieldEnumDecl->getNameAsString();
10244     }
10245   }
10246 
10247   if (Bitfield->getType()->isBooleanType())
10248     return false;
10249 
10250   // Ignore value- or type-dependent expressions.
10251   if (Bitfield->getBitWidth()->isValueDependent() ||
10252       Bitfield->getBitWidth()->isTypeDependent() ||
10253       Init->isValueDependent() ||
10254       Init->isTypeDependent())
10255     return false;
10256 
10257   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10258   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10259 
10260   llvm::APSInt Value;
10261   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
10262                                    Expr::SE_AllowSideEffects)) {
10263     // The RHS is not constant.  If the RHS has an enum type, make sure the
10264     // bitfield is wide enough to hold all the values of the enum without
10265     // truncation.
10266     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10267       EnumDecl *ED = EnumTy->getDecl();
10268       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10269 
10270       // Enum types are implicitly signed on Windows, so check if there are any
10271       // negative enumerators to see if the enum was intended to be signed or
10272       // not.
10273       bool SignedEnum = ED->getNumNegativeBits() > 0;
10274 
10275       // Check for surprising sign changes when assigning enum values to a
10276       // bitfield of different signedness.  If the bitfield is signed and we
10277       // have exactly the right number of bits to store this unsigned enum,
10278       // suggest changing the enum to an unsigned type. This typically happens
10279       // on Windows where unfixed enums always use an underlying type of 'int'.
10280       unsigned DiagID = 0;
10281       if (SignedEnum && !SignedBitfield) {
10282         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10283       } else if (SignedBitfield && !SignedEnum &&
10284                  ED->getNumPositiveBits() == FieldWidth) {
10285         DiagID = diag::warn_signed_bitfield_enum_conversion;
10286       }
10287 
10288       if (DiagID) {
10289         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10290         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10291         SourceRange TypeRange =
10292             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10293         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10294             << SignedEnum << TypeRange;
10295       }
10296 
10297       // Compute the required bitwidth. If the enum has negative values, we need
10298       // one more bit than the normal number of positive bits to represent the
10299       // sign bit.
10300       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10301                                                   ED->getNumNegativeBits())
10302                                        : ED->getNumPositiveBits();
10303 
10304       // Check the bitwidth.
10305       if (BitsNeeded > FieldWidth) {
10306         Expr *WidthExpr = Bitfield->getBitWidth();
10307         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10308             << Bitfield << ED;
10309         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10310             << BitsNeeded << ED << WidthExpr->getSourceRange();
10311       }
10312     }
10313 
10314     return false;
10315   }
10316 
10317   unsigned OriginalWidth = Value.getBitWidth();
10318 
10319   if (!Value.isSigned() || Value.isNegative())
10320     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10321       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10322         OriginalWidth = Value.getMinSignedBits();
10323 
10324   if (OriginalWidth <= FieldWidth)
10325     return false;
10326 
10327   // Compute the value which the bitfield will contain.
10328   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10329   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10330 
10331   // Check whether the stored value is equal to the original value.
10332   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10333   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10334     return false;
10335 
10336   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10337   // therefore don't strictly fit into a signed bitfield of width 1.
10338   if (FieldWidth == 1 && Value == 1)
10339     return false;
10340 
10341   std::string PrettyValue = Value.toString(10);
10342   std::string PrettyTrunc = TruncatedValue.toString(10);
10343 
10344   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10345     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10346     << Init->getSourceRange();
10347 
10348   return true;
10349 }
10350 
10351 /// Analyze the given simple or compound assignment for warning-worthy
10352 /// operations.
10353 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10354   // Just recurse on the LHS.
10355   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10356 
10357   // We want to recurse on the RHS as normal unless we're assigning to
10358   // a bitfield.
10359   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10360     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10361                                   E->getOperatorLoc())) {
10362       // Recurse, ignoring any implicit conversions on the RHS.
10363       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10364                                         E->getOperatorLoc());
10365     }
10366   }
10367 
10368   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10369 
10370   // Diagnose implicitly sequentially-consistent atomic assignment.
10371   if (E->getLHS()->getType()->isAtomicType())
10372     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10373 }
10374 
10375 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10376 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10377                             SourceLocation CContext, unsigned diag,
10378                             bool pruneControlFlow = false) {
10379   if (pruneControlFlow) {
10380     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10381                           S.PDiag(diag)
10382                             << SourceType << T << E->getSourceRange()
10383                             << SourceRange(CContext));
10384     return;
10385   }
10386   S.Diag(E->getExprLoc(), diag)
10387     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10388 }
10389 
10390 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10391 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10392                             SourceLocation CContext,
10393                             unsigned diag, bool pruneControlFlow = false) {
10394   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10395 }
10396 
10397 /// Diagnose an implicit cast from a floating point value to an integer value.
10398 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10399                                     SourceLocation CContext) {
10400   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10401   const bool PruneWarnings = S.inTemplateInstantiation();
10402 
10403   Expr *InnerE = E->IgnoreParenImpCasts();
10404   // We also want to warn on, e.g., "int i = -1.234"
10405   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10406     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10407       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10408 
10409   const bool IsLiteral =
10410       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10411 
10412   llvm::APFloat Value(0.0);
10413   bool IsConstant =
10414     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10415   if (!IsConstant) {
10416     return DiagnoseImpCast(S, E, T, CContext,
10417                            diag::warn_impcast_float_integer, PruneWarnings);
10418   }
10419 
10420   bool isExact = false;
10421 
10422   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10423                             T->hasUnsignedIntegerRepresentation());
10424   llvm::APFloat::opStatus Result = Value.convertToInteger(
10425       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10426 
10427   if (Result == llvm::APFloat::opOK && isExact) {
10428     if (IsLiteral) return;
10429     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10430                            PruneWarnings);
10431   }
10432 
10433   // Conversion of a floating-point value to a non-bool integer where the
10434   // integral part cannot be represented by the integer type is undefined.
10435   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10436     return DiagnoseImpCast(
10437         S, E, T, CContext,
10438         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10439                   : diag::warn_impcast_float_to_integer_out_of_range,
10440         PruneWarnings);
10441 
10442   unsigned DiagID = 0;
10443   if (IsLiteral) {
10444     // Warn on floating point literal to integer.
10445     DiagID = diag::warn_impcast_literal_float_to_integer;
10446   } else if (IntegerValue == 0) {
10447     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10448       return DiagnoseImpCast(S, E, T, CContext,
10449                              diag::warn_impcast_float_integer, PruneWarnings);
10450     }
10451     // Warn on non-zero to zero conversion.
10452     DiagID = diag::warn_impcast_float_to_integer_zero;
10453   } else {
10454     if (IntegerValue.isUnsigned()) {
10455       if (!IntegerValue.isMaxValue()) {
10456         return DiagnoseImpCast(S, E, T, CContext,
10457                                diag::warn_impcast_float_integer, PruneWarnings);
10458       }
10459     } else {  // IntegerValue.isSigned()
10460       if (!IntegerValue.isMaxSignedValue() &&
10461           !IntegerValue.isMinSignedValue()) {
10462         return DiagnoseImpCast(S, E, T, CContext,
10463                                diag::warn_impcast_float_integer, PruneWarnings);
10464       }
10465     }
10466     // Warn on evaluatable floating point expression to integer conversion.
10467     DiagID = diag::warn_impcast_float_to_integer;
10468   }
10469 
10470   // FIXME: Force the precision of the source value down so we don't print
10471   // digits which are usually useless (we don't really care here if we
10472   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10473   // would automatically print the shortest representation, but it's a bit
10474   // tricky to implement.
10475   SmallString<16> PrettySourceValue;
10476   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10477   precision = (precision * 59 + 195) / 196;
10478   Value.toString(PrettySourceValue, precision);
10479 
10480   SmallString<16> PrettyTargetValue;
10481   if (IsBool)
10482     PrettyTargetValue = Value.isZero() ? "false" : "true";
10483   else
10484     IntegerValue.toString(PrettyTargetValue);
10485 
10486   if (PruneWarnings) {
10487     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10488                           S.PDiag(DiagID)
10489                               << E->getType() << T.getUnqualifiedType()
10490                               << PrettySourceValue << PrettyTargetValue
10491                               << E->getSourceRange() << SourceRange(CContext));
10492   } else {
10493     S.Diag(E->getExprLoc(), DiagID)
10494         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10495         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10496   }
10497 }
10498 
10499 /// Analyze the given compound assignment for the possible losing of
10500 /// floating-point precision.
10501 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10502   assert(isa<CompoundAssignOperator>(E) &&
10503          "Must be compound assignment operation");
10504   // Recurse on the LHS and RHS in here
10505   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10506   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10507 
10508   if (E->getLHS()->getType()->isAtomicType())
10509     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10510 
10511   // Now check the outermost expression
10512   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10513   const auto *RBT = cast<CompoundAssignOperator>(E)
10514                         ->getComputationResultType()
10515                         ->getAs<BuiltinType>();
10516 
10517   // The below checks assume source is floating point.
10518   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10519 
10520   // If source is floating point but target is not.
10521   if (!ResultBT->isFloatingPoint())
10522     return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
10523                                    E->getExprLoc());
10524 
10525   // If both source and target are floating points.
10526   // Builtin FP kinds are ordered by increasing FP rank.
10527   if (ResultBT->getKind() < RBT->getKind() &&
10528       // We don't want to warn for system macro.
10529       !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10530     // warn about dropping FP rank.
10531     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10532                     diag::warn_impcast_float_result_precision);
10533 }
10534 
10535 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10536                                       IntRange Range) {
10537   if (!Range.Width) return "0";
10538 
10539   llvm::APSInt ValueInRange = Value;
10540   ValueInRange.setIsSigned(!Range.NonNegative);
10541   ValueInRange = ValueInRange.trunc(Range.Width);
10542   return ValueInRange.toString(10);
10543 }
10544 
10545 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10546   if (!isa<ImplicitCastExpr>(Ex))
10547     return false;
10548 
10549   Expr *InnerE = Ex->IgnoreParenImpCasts();
10550   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10551   const Type *Source =
10552     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10553   if (Target->isDependentType())
10554     return false;
10555 
10556   const BuiltinType *FloatCandidateBT =
10557     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10558   const Type *BoolCandidateType = ToBool ? Target : Source;
10559 
10560   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10561           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10562 }
10563 
10564 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10565                                              SourceLocation CC) {
10566   unsigned NumArgs = TheCall->getNumArgs();
10567   for (unsigned i = 0; i < NumArgs; ++i) {
10568     Expr *CurrA = TheCall->getArg(i);
10569     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10570       continue;
10571 
10572     bool IsSwapped = ((i > 0) &&
10573         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10574     IsSwapped |= ((i < (NumArgs - 1)) &&
10575         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10576     if (IsSwapped) {
10577       // Warn on this floating-point to bool conversion.
10578       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10579                       CurrA->getType(), CC,
10580                       diag::warn_impcast_floating_point_to_bool);
10581     }
10582   }
10583 }
10584 
10585 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10586                                    SourceLocation CC) {
10587   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10588                         E->getExprLoc()))
10589     return;
10590 
10591   // Don't warn on functions which have return type nullptr_t.
10592   if (isa<CallExpr>(E))
10593     return;
10594 
10595   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10596   const Expr::NullPointerConstantKind NullKind =
10597       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10598   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10599     return;
10600 
10601   // Return if target type is a safe conversion.
10602   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10603       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10604     return;
10605 
10606   SourceLocation Loc = E->getSourceRange().getBegin();
10607 
10608   // Venture through the macro stacks to get to the source of macro arguments.
10609   // The new location is a better location than the complete location that was
10610   // passed in.
10611   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10612   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10613 
10614   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10615   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10616     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10617         Loc, S.SourceMgr, S.getLangOpts());
10618     if (MacroName == "NULL")
10619       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10620   }
10621 
10622   // Only warn if the null and context location are in the same macro expansion.
10623   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10624     return;
10625 
10626   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10627       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10628       << FixItHint::CreateReplacement(Loc,
10629                                       S.getFixItZeroLiteralForType(T, Loc));
10630 }
10631 
10632 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10633                                   ObjCArrayLiteral *ArrayLiteral);
10634 
10635 static void
10636 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10637                            ObjCDictionaryLiteral *DictionaryLiteral);
10638 
10639 /// Check a single element within a collection literal against the
10640 /// target element type.
10641 static void checkObjCCollectionLiteralElement(Sema &S,
10642                                               QualType TargetElementType,
10643                                               Expr *Element,
10644                                               unsigned ElementKind) {
10645   // Skip a bitcast to 'id' or qualified 'id'.
10646   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10647     if (ICE->getCastKind() == CK_BitCast &&
10648         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10649       Element = ICE->getSubExpr();
10650   }
10651 
10652   QualType ElementType = Element->getType();
10653   ExprResult ElementResult(Element);
10654   if (ElementType->getAs<ObjCObjectPointerType>() &&
10655       S.CheckSingleAssignmentConstraints(TargetElementType,
10656                                          ElementResult,
10657                                          false, false)
10658         != Sema::Compatible) {
10659     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10660         << ElementType << ElementKind << TargetElementType
10661         << Element->getSourceRange();
10662   }
10663 
10664   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10665     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10666   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10667     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10668 }
10669 
10670 /// Check an Objective-C array literal being converted to the given
10671 /// target type.
10672 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10673                                   ObjCArrayLiteral *ArrayLiteral) {
10674   if (!S.NSArrayDecl)
10675     return;
10676 
10677   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10678   if (!TargetObjCPtr)
10679     return;
10680 
10681   if (TargetObjCPtr->isUnspecialized() ||
10682       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10683         != S.NSArrayDecl->getCanonicalDecl())
10684     return;
10685 
10686   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10687   if (TypeArgs.size() != 1)
10688     return;
10689 
10690   QualType TargetElementType = TypeArgs[0];
10691   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10692     checkObjCCollectionLiteralElement(S, TargetElementType,
10693                                       ArrayLiteral->getElement(I),
10694                                       0);
10695   }
10696 }
10697 
10698 /// Check an Objective-C dictionary literal being converted to the given
10699 /// target type.
10700 static void
10701 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10702                            ObjCDictionaryLiteral *DictionaryLiteral) {
10703   if (!S.NSDictionaryDecl)
10704     return;
10705 
10706   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10707   if (!TargetObjCPtr)
10708     return;
10709 
10710   if (TargetObjCPtr->isUnspecialized() ||
10711       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10712         != S.NSDictionaryDecl->getCanonicalDecl())
10713     return;
10714 
10715   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10716   if (TypeArgs.size() != 2)
10717     return;
10718 
10719   QualType TargetKeyType = TypeArgs[0];
10720   QualType TargetObjectType = TypeArgs[1];
10721   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10722     auto Element = DictionaryLiteral->getKeyValueElement(I);
10723     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10724     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10725   }
10726 }
10727 
10728 // Helper function to filter out cases for constant width constant conversion.
10729 // Don't warn on char array initialization or for non-decimal values.
10730 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10731                                           SourceLocation CC) {
10732   // If initializing from a constant, and the constant starts with '0',
10733   // then it is a binary, octal, or hexadecimal.  Allow these constants
10734   // to fill all the bits, even if there is a sign change.
10735   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10736     const char FirstLiteralCharacter =
10737         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10738     if (FirstLiteralCharacter == '0')
10739       return false;
10740   }
10741 
10742   // If the CC location points to a '{', and the type is char, then assume
10743   // assume it is an array initialization.
10744   if (CC.isValid() && T->isCharType()) {
10745     const char FirstContextCharacter =
10746         S.getSourceManager().getCharacterData(CC)[0];
10747     if (FirstContextCharacter == '{')
10748       return false;
10749   }
10750 
10751   return true;
10752 }
10753 
10754 static void
10755 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10756                         bool *ICContext = nullptr) {
10757   if (E->isTypeDependent() || E->isValueDependent()) return;
10758 
10759   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10760   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10761   if (Source == Target) return;
10762   if (Target->isDependentType()) return;
10763 
10764   // If the conversion context location is invalid don't complain. We also
10765   // don't want to emit a warning if the issue occurs from the expansion of
10766   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10767   // delay this check as long as possible. Once we detect we are in that
10768   // scenario, we just return.
10769   if (CC.isInvalid())
10770     return;
10771 
10772   if (Source->isAtomicType())
10773     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10774 
10775   // Diagnose implicit casts to bool.
10776   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10777     if (isa<StringLiteral>(E))
10778       // Warn on string literal to bool.  Checks for string literals in logical
10779       // and expressions, for instance, assert(0 && "error here"), are
10780       // prevented by a check in AnalyzeImplicitConversions().
10781       return DiagnoseImpCast(S, E, T, CC,
10782                              diag::warn_impcast_string_literal_to_bool);
10783     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10784         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10785       // This covers the literal expressions that evaluate to Objective-C
10786       // objects.
10787       return DiagnoseImpCast(S, E, T, CC,
10788                              diag::warn_impcast_objective_c_literal_to_bool);
10789     }
10790     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10791       // Warn on pointer to bool conversion that is always true.
10792       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10793                                      SourceRange(CC));
10794     }
10795   }
10796 
10797   // Check implicit casts from Objective-C collection literals to specialized
10798   // collection types, e.g., NSArray<NSString *> *.
10799   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10800     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10801   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10802     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10803 
10804   // Strip vector types.
10805   if (isa<VectorType>(Source)) {
10806     if (!isa<VectorType>(Target)) {
10807       if (S.SourceMgr.isInSystemMacro(CC))
10808         return;
10809       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10810     }
10811 
10812     // If the vector cast is cast between two vectors of the same size, it is
10813     // a bitcast, not a conversion.
10814     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10815       return;
10816 
10817     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10818     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10819   }
10820   if (auto VecTy = dyn_cast<VectorType>(Target))
10821     Target = VecTy->getElementType().getTypePtr();
10822 
10823   // Strip complex types.
10824   if (isa<ComplexType>(Source)) {
10825     if (!isa<ComplexType>(Target)) {
10826       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10827         return;
10828 
10829       return DiagnoseImpCast(S, E, T, CC,
10830                              S.getLangOpts().CPlusPlus
10831                                  ? diag::err_impcast_complex_scalar
10832                                  : diag::warn_impcast_complex_scalar);
10833     }
10834 
10835     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10836     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10837   }
10838 
10839   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10840   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10841 
10842   // If the source is floating point...
10843   if (SourceBT && SourceBT->isFloatingPoint()) {
10844     // ...and the target is floating point...
10845     if (TargetBT && TargetBT->isFloatingPoint()) {
10846       // ...then warn if we're dropping FP rank.
10847 
10848       // Builtin FP kinds are ordered by increasing FP rank.
10849       if (SourceBT->getKind() > TargetBT->getKind()) {
10850         // Don't warn about float constants that are precisely
10851         // representable in the target type.
10852         Expr::EvalResult result;
10853         if (E->EvaluateAsRValue(result, S.Context)) {
10854           // Value might be a float, a float vector, or a float complex.
10855           if (IsSameFloatAfterCast(result.Val,
10856                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10857                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10858             return;
10859         }
10860 
10861         if (S.SourceMgr.isInSystemMacro(CC))
10862           return;
10863 
10864         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10865       }
10866       // ... or possibly if we're increasing rank, too
10867       else if (TargetBT->getKind() > SourceBT->getKind()) {
10868         if (S.SourceMgr.isInSystemMacro(CC))
10869           return;
10870 
10871         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10872       }
10873       return;
10874     }
10875 
10876     // If the target is integral, always warn.
10877     if (TargetBT && TargetBT->isInteger()) {
10878       if (S.SourceMgr.isInSystemMacro(CC))
10879         return;
10880 
10881       DiagnoseFloatingImpCast(S, E, T, CC);
10882     }
10883 
10884     // Detect the case where a call result is converted from floating-point to
10885     // to bool, and the final argument to the call is converted from bool, to
10886     // discover this typo:
10887     //
10888     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10889     //
10890     // FIXME: This is an incredibly special case; is there some more general
10891     // way to detect this class of misplaced-parentheses bug?
10892     if (Target->isBooleanType() && isa<CallExpr>(E)) {
10893       // Check last argument of function call to see if it is an
10894       // implicit cast from a type matching the type the result
10895       // is being cast to.
10896       CallExpr *CEx = cast<CallExpr>(E);
10897       if (unsigned NumArgs = CEx->getNumArgs()) {
10898         Expr *LastA = CEx->getArg(NumArgs - 1);
10899         Expr *InnerE = LastA->IgnoreParenImpCasts();
10900         if (isa<ImplicitCastExpr>(LastA) &&
10901             InnerE->getType()->isBooleanType()) {
10902           // Warn on this floating-point to bool conversion
10903           DiagnoseImpCast(S, E, T, CC,
10904                           diag::warn_impcast_floating_point_to_bool);
10905         }
10906       }
10907     }
10908     return;
10909   }
10910 
10911   DiagnoseNullConversion(S, E, T, CC);
10912 
10913   S.DiscardMisalignedMemberAddress(Target, E);
10914 
10915   if (!Source->isIntegerType() || !Target->isIntegerType())
10916     return;
10917 
10918   // TODO: remove this early return once the false positives for constant->bool
10919   // in templates, macros, etc, are reduced or removed.
10920   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10921     return;
10922 
10923   IntRange SourceRange = GetExprRange(S.Context, E);
10924   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
10925 
10926   if (SourceRange.Width > TargetRange.Width) {
10927     // If the source is a constant, use a default-on diagnostic.
10928     // TODO: this should happen for bitfield stores, too.
10929     llvm::APSInt Value(32);
10930     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
10931       if (S.SourceMgr.isInSystemMacro(CC))
10932         return;
10933 
10934       std::string PrettySourceValue = Value.toString(10);
10935       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10936 
10937       S.DiagRuntimeBehavior(E->getExprLoc(), E,
10938         S.PDiag(diag::warn_impcast_integer_precision_constant)
10939             << PrettySourceValue << PrettyTargetValue
10940             << E->getType() << T << E->getSourceRange()
10941             << clang::SourceRange(CC));
10942       return;
10943     }
10944 
10945     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10946     if (S.SourceMgr.isInSystemMacro(CC))
10947       return;
10948 
10949     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
10950       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10951                              /* pruneControlFlow */ true);
10952     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
10953   }
10954 
10955   if (TargetRange.Width > SourceRange.Width) {
10956     if (auto *UO = dyn_cast<UnaryOperator>(E))
10957       if (UO->getOpcode() == UO_Minus)
10958         if (Source->isUnsignedIntegerType()) {
10959           if (Target->isUnsignedIntegerType())
10960             return DiagnoseImpCast(S, E, T, CC,
10961                                    diag::warn_impcast_high_order_zero_bits);
10962           if (Target->isSignedIntegerType())
10963             return DiagnoseImpCast(S, E, T, CC,
10964                                    diag::warn_impcast_nonnegative_result);
10965         }
10966   }
10967 
10968   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10969       SourceRange.NonNegative && Source->isSignedIntegerType()) {
10970     // Warn when doing a signed to signed conversion, warn if the positive
10971     // source value is exactly the width of the target type, which will
10972     // cause a negative value to be stored.
10973 
10974     llvm::APSInt Value;
10975     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10976         !S.SourceMgr.isInSystemMacro(CC)) {
10977       if (isSameWidthConstantConversion(S, E, T, CC)) {
10978         std::string PrettySourceValue = Value.toString(10);
10979         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10980 
10981         S.DiagRuntimeBehavior(
10982             E->getExprLoc(), E,
10983             S.PDiag(diag::warn_impcast_integer_precision_constant)
10984                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10985                 << E->getSourceRange() << clang::SourceRange(CC));
10986         return;
10987       }
10988     }
10989 
10990     // Fall through for non-constants to give a sign conversion warning.
10991   }
10992 
10993   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10994       (!TargetRange.NonNegative && SourceRange.NonNegative &&
10995        SourceRange.Width == TargetRange.Width)) {
10996     if (S.SourceMgr.isInSystemMacro(CC))
10997       return;
10998 
10999     unsigned DiagID = diag::warn_impcast_integer_sign;
11000 
11001     // Traditionally, gcc has warned about this under -Wsign-compare.
11002     // We also want to warn about it in -Wconversion.
11003     // So if -Wconversion is off, use a completely identical diagnostic
11004     // in the sign-compare group.
11005     // The conditional-checking code will
11006     if (ICContext) {
11007       DiagID = diag::warn_impcast_integer_sign_conditional;
11008       *ICContext = true;
11009     }
11010 
11011     return DiagnoseImpCast(S, E, T, CC, DiagID);
11012   }
11013 
11014   // Diagnose conversions between different enumeration types.
11015   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11016   // type, to give us better diagnostics.
11017   QualType SourceType = E->getType();
11018   if (!S.getLangOpts().CPlusPlus) {
11019     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11020       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11021         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11022         SourceType = S.Context.getTypeDeclType(Enum);
11023         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11024       }
11025   }
11026 
11027   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11028     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11029       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11030           TargetEnum->getDecl()->hasNameForLinkage() &&
11031           SourceEnum != TargetEnum) {
11032         if (S.SourceMgr.isInSystemMacro(CC))
11033           return;
11034 
11035         return DiagnoseImpCast(S, E, SourceType, T, CC,
11036                                diag::warn_impcast_different_enum_types);
11037       }
11038 }
11039 
11040 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11041                                      SourceLocation CC, QualType T);
11042 
11043 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11044                                     SourceLocation CC, bool &ICContext) {
11045   E = E->IgnoreParenImpCasts();
11046 
11047   if (isa<ConditionalOperator>(E))
11048     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11049 
11050   AnalyzeImplicitConversions(S, E, CC);
11051   if (E->getType() != T)
11052     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11053 }
11054 
11055 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11056                                      SourceLocation CC, QualType T) {
11057   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11058 
11059   bool Suspicious = false;
11060   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11061   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11062 
11063   // If -Wconversion would have warned about either of the candidates
11064   // for a signedness conversion to the context type...
11065   if (!Suspicious) return;
11066 
11067   // ...but it's currently ignored...
11068   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11069     return;
11070 
11071   // ...then check whether it would have warned about either of the
11072   // candidates for a signedness conversion to the condition type.
11073   if (E->getType() == T) return;
11074 
11075   Suspicious = false;
11076   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11077                           E->getType(), CC, &Suspicious);
11078   if (!Suspicious)
11079     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11080                             E->getType(), CC, &Suspicious);
11081 }
11082 
11083 /// Check conversion of given expression to boolean.
11084 /// Input argument E is a logical expression.
11085 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11086   if (S.getLangOpts().Bool)
11087     return;
11088   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11089     return;
11090   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11091 }
11092 
11093 /// AnalyzeImplicitConversions - Find and report any interesting
11094 /// implicit conversions in the given expression.  There are a couple
11095 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11096 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11097                                        SourceLocation CC) {
11098   QualType T = OrigE->getType();
11099   Expr *E = OrigE->IgnoreParenImpCasts();
11100 
11101   if (E->isTypeDependent() || E->isValueDependent())
11102     return;
11103 
11104   // For conditional operators, we analyze the arguments as if they
11105   // were being fed directly into the output.
11106   if (isa<ConditionalOperator>(E)) {
11107     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11108     CheckConditionalOperator(S, CO, CC, T);
11109     return;
11110   }
11111 
11112   // Check implicit argument conversions for function calls.
11113   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11114     CheckImplicitArgumentConversions(S, Call, CC);
11115 
11116   // Go ahead and check any implicit conversions we might have skipped.
11117   // The non-canonical typecheck is just an optimization;
11118   // CheckImplicitConversion will filter out dead implicit conversions.
11119   if (E->getType() != T)
11120     CheckImplicitConversion(S, E, T, CC);
11121 
11122   // Now continue drilling into this expression.
11123 
11124   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11125     // The bound subexpressions in a PseudoObjectExpr are not reachable
11126     // as transitive children.
11127     // FIXME: Use a more uniform representation for this.
11128     for (auto *SE : POE->semantics())
11129       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11130         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11131   }
11132 
11133   // Skip past explicit casts.
11134   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11135     E = CE->getSubExpr()->IgnoreParenImpCasts();
11136     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11137       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11138     return AnalyzeImplicitConversions(S, E, CC);
11139   }
11140 
11141   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11142     // Do a somewhat different check with comparison operators.
11143     if (BO->isComparisonOp())
11144       return AnalyzeComparison(S, BO);
11145 
11146     // And with simple assignments.
11147     if (BO->getOpcode() == BO_Assign)
11148       return AnalyzeAssignment(S, BO);
11149     // And with compound assignments.
11150     if (BO->isAssignmentOp())
11151       return AnalyzeCompoundAssignment(S, BO);
11152   }
11153 
11154   // These break the otherwise-useful invariant below.  Fortunately,
11155   // we don't really need to recurse into them, because any internal
11156   // expressions should have been analyzed already when they were
11157   // built into statements.
11158   if (isa<StmtExpr>(E)) return;
11159 
11160   // Don't descend into unevaluated contexts.
11161   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11162 
11163   // Now just recurse over the expression's children.
11164   CC = E->getExprLoc();
11165   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11166   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11167   for (Stmt *SubStmt : E->children()) {
11168     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11169     if (!ChildExpr)
11170       continue;
11171 
11172     if (IsLogicalAndOperator &&
11173         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11174       // Ignore checking string literals that are in logical and operators.
11175       // This is a common pattern for asserts.
11176       continue;
11177     AnalyzeImplicitConversions(S, ChildExpr, CC);
11178   }
11179 
11180   if (BO && BO->isLogicalOp()) {
11181     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11182     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11183       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11184 
11185     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11186     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11187       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11188   }
11189 
11190   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11191     if (U->getOpcode() == UO_LNot) {
11192       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11193     } else if (U->getOpcode() != UO_AddrOf) {
11194       if (U->getSubExpr()->getType()->isAtomicType())
11195         S.Diag(U->getSubExpr()->getBeginLoc(),
11196                diag::warn_atomic_implicit_seq_cst);
11197     }
11198   }
11199 }
11200 
11201 /// Diagnose integer type and any valid implicit conversion to it.
11202 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11203   // Taking into account implicit conversions,
11204   // allow any integer.
11205   if (!E->getType()->isIntegerType()) {
11206     S.Diag(E->getBeginLoc(),
11207            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11208     return true;
11209   }
11210   // Potentially emit standard warnings for implicit conversions if enabled
11211   // using -Wconversion.
11212   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11213   return false;
11214 }
11215 
11216 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11217 // Returns true when emitting a warning about taking the address of a reference.
11218 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11219                               const PartialDiagnostic &PD) {
11220   E = E->IgnoreParenImpCasts();
11221 
11222   const FunctionDecl *FD = nullptr;
11223 
11224   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11225     if (!DRE->getDecl()->getType()->isReferenceType())
11226       return false;
11227   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11228     if (!M->getMemberDecl()->getType()->isReferenceType())
11229       return false;
11230   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11231     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11232       return false;
11233     FD = Call->getDirectCallee();
11234   } else {
11235     return false;
11236   }
11237 
11238   SemaRef.Diag(E->getExprLoc(), PD);
11239 
11240   // If possible, point to location of function.
11241   if (FD) {
11242     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11243   }
11244 
11245   return true;
11246 }
11247 
11248 // Returns true if the SourceLocation is expanded from any macro body.
11249 // Returns false if the SourceLocation is invalid, is from not in a macro
11250 // expansion, or is from expanded from a top-level macro argument.
11251 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11252   if (Loc.isInvalid())
11253     return false;
11254 
11255   while (Loc.isMacroID()) {
11256     if (SM.isMacroBodyExpansion(Loc))
11257       return true;
11258     Loc = SM.getImmediateMacroCallerLoc(Loc);
11259   }
11260 
11261   return false;
11262 }
11263 
11264 /// Diagnose pointers that are always non-null.
11265 /// \param E the expression containing the pointer
11266 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11267 /// compared to a null pointer
11268 /// \param IsEqual True when the comparison is equal to a null pointer
11269 /// \param Range Extra SourceRange to highlight in the diagnostic
11270 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11271                                         Expr::NullPointerConstantKind NullKind,
11272                                         bool IsEqual, SourceRange Range) {
11273   if (!E)
11274     return;
11275 
11276   // Don't warn inside macros.
11277   if (E->getExprLoc().isMacroID()) {
11278     const SourceManager &SM = getSourceManager();
11279     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11280         IsInAnyMacroBody(SM, Range.getBegin()))
11281       return;
11282   }
11283   E = E->IgnoreImpCasts();
11284 
11285   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11286 
11287   if (isa<CXXThisExpr>(E)) {
11288     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11289                                 : diag::warn_this_bool_conversion;
11290     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11291     return;
11292   }
11293 
11294   bool IsAddressOf = false;
11295 
11296   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11297     if (UO->getOpcode() != UO_AddrOf)
11298       return;
11299     IsAddressOf = true;
11300     E = UO->getSubExpr();
11301   }
11302 
11303   if (IsAddressOf) {
11304     unsigned DiagID = IsCompare
11305                           ? diag::warn_address_of_reference_null_compare
11306                           : diag::warn_address_of_reference_bool_conversion;
11307     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11308                                          << IsEqual;
11309     if (CheckForReference(*this, E, PD)) {
11310       return;
11311     }
11312   }
11313 
11314   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11315     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11316     std::string Str;
11317     llvm::raw_string_ostream S(Str);
11318     E->printPretty(S, nullptr, getPrintingPolicy());
11319     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11320                                 : diag::warn_cast_nonnull_to_bool;
11321     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11322       << E->getSourceRange() << Range << IsEqual;
11323     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11324   };
11325 
11326   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11327   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11328     if (auto *Callee = Call->getDirectCallee()) {
11329       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11330         ComplainAboutNonnullParamOrCall(A);
11331         return;
11332       }
11333     }
11334   }
11335 
11336   // Expect to find a single Decl.  Skip anything more complicated.
11337   ValueDecl *D = nullptr;
11338   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11339     D = R->getDecl();
11340   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11341     D = M->getMemberDecl();
11342   }
11343 
11344   // Weak Decls can be null.
11345   if (!D || D->isWeak())
11346     return;
11347 
11348   // Check for parameter decl with nonnull attribute
11349   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11350     if (getCurFunction() &&
11351         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11352       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11353         ComplainAboutNonnullParamOrCall(A);
11354         return;
11355       }
11356 
11357       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11358         auto ParamIter = llvm::find(FD->parameters(), PV);
11359         assert(ParamIter != FD->param_end());
11360         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11361 
11362         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11363           if (!NonNull->args_size()) {
11364               ComplainAboutNonnullParamOrCall(NonNull);
11365               return;
11366           }
11367 
11368           for (const ParamIdx &ArgNo : NonNull->args()) {
11369             if (ArgNo.getASTIndex() == ParamNo) {
11370               ComplainAboutNonnullParamOrCall(NonNull);
11371               return;
11372             }
11373           }
11374         }
11375       }
11376     }
11377   }
11378 
11379   QualType T = D->getType();
11380   const bool IsArray = T->isArrayType();
11381   const bool IsFunction = T->isFunctionType();
11382 
11383   // Address of function is used to silence the function warning.
11384   if (IsAddressOf && IsFunction) {
11385     return;
11386   }
11387 
11388   // Found nothing.
11389   if (!IsAddressOf && !IsFunction && !IsArray)
11390     return;
11391 
11392   // Pretty print the expression for the diagnostic.
11393   std::string Str;
11394   llvm::raw_string_ostream S(Str);
11395   E->printPretty(S, nullptr, getPrintingPolicy());
11396 
11397   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11398                               : diag::warn_impcast_pointer_to_bool;
11399   enum {
11400     AddressOf,
11401     FunctionPointer,
11402     ArrayPointer
11403   } DiagType;
11404   if (IsAddressOf)
11405     DiagType = AddressOf;
11406   else if (IsFunction)
11407     DiagType = FunctionPointer;
11408   else if (IsArray)
11409     DiagType = ArrayPointer;
11410   else
11411     llvm_unreachable("Could not determine diagnostic.");
11412   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11413                                 << Range << IsEqual;
11414 
11415   if (!IsFunction)
11416     return;
11417 
11418   // Suggest '&' to silence the function warning.
11419   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11420       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11421 
11422   // Check to see if '()' fixit should be emitted.
11423   QualType ReturnType;
11424   UnresolvedSet<4> NonTemplateOverloads;
11425   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11426   if (ReturnType.isNull())
11427     return;
11428 
11429   if (IsCompare) {
11430     // There are two cases here.  If there is null constant, the only suggest
11431     // for a pointer return type.  If the null is 0, then suggest if the return
11432     // type is a pointer or an integer type.
11433     if (!ReturnType->isPointerType()) {
11434       if (NullKind == Expr::NPCK_ZeroExpression ||
11435           NullKind == Expr::NPCK_ZeroLiteral) {
11436         if (!ReturnType->isIntegerType())
11437           return;
11438       } else {
11439         return;
11440       }
11441     }
11442   } else { // !IsCompare
11443     // For function to bool, only suggest if the function pointer has bool
11444     // return type.
11445     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11446       return;
11447   }
11448   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11449       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11450 }
11451 
11452 /// Diagnoses "dangerous" implicit conversions within the given
11453 /// expression (which is a full expression).  Implements -Wconversion
11454 /// and -Wsign-compare.
11455 ///
11456 /// \param CC the "context" location of the implicit conversion, i.e.
11457 ///   the most location of the syntactic entity requiring the implicit
11458 ///   conversion
11459 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11460   // Don't diagnose in unevaluated contexts.
11461   if (isUnevaluatedContext())
11462     return;
11463 
11464   // Don't diagnose for value- or type-dependent expressions.
11465   if (E->isTypeDependent() || E->isValueDependent())
11466     return;
11467 
11468   // Check for array bounds violations in cases where the check isn't triggered
11469   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11470   // ArraySubscriptExpr is on the RHS of a variable initialization.
11471   CheckArrayAccess(E);
11472 
11473   // This is not the right CC for (e.g.) a variable initialization.
11474   AnalyzeImplicitConversions(*this, E, CC);
11475 }
11476 
11477 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11478 /// Input argument E is a logical expression.
11479 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11480   ::CheckBoolLikeConversion(*this, E, CC);
11481 }
11482 
11483 /// Diagnose when expression is an integer constant expression and its evaluation
11484 /// results in integer overflow
11485 void Sema::CheckForIntOverflow (Expr *E) {
11486   // Use a work list to deal with nested struct initializers.
11487   SmallVector<Expr *, 2> Exprs(1, E);
11488 
11489   do {
11490     Expr *OriginalE = Exprs.pop_back_val();
11491     Expr *E = OriginalE->IgnoreParenCasts();
11492 
11493     if (isa<BinaryOperator>(E)) {
11494       E->EvaluateForOverflow(Context);
11495       continue;
11496     }
11497 
11498     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11499       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11500     else if (isa<ObjCBoxedExpr>(OriginalE))
11501       E->EvaluateForOverflow(Context);
11502     else if (auto Call = dyn_cast<CallExpr>(E))
11503       Exprs.append(Call->arg_begin(), Call->arg_end());
11504     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11505       Exprs.append(Message->arg_begin(), Message->arg_end());
11506   } while (!Exprs.empty());
11507 }
11508 
11509 namespace {
11510 
11511 /// Visitor for expressions which looks for unsequenced operations on the
11512 /// same object.
11513 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11514   using Base = EvaluatedExprVisitor<SequenceChecker>;
11515 
11516   /// A tree of sequenced regions within an expression. Two regions are
11517   /// unsequenced if one is an ancestor or a descendent of the other. When we
11518   /// finish processing an expression with sequencing, such as a comma
11519   /// expression, we fold its tree nodes into its parent, since they are
11520   /// unsequenced with respect to nodes we will visit later.
11521   class SequenceTree {
11522     struct Value {
11523       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11524       unsigned Parent : 31;
11525       unsigned Merged : 1;
11526     };
11527     SmallVector<Value, 8> Values;
11528 
11529   public:
11530     /// A region within an expression which may be sequenced with respect
11531     /// to some other region.
11532     class Seq {
11533       friend class SequenceTree;
11534 
11535       unsigned Index = 0;
11536 
11537       explicit Seq(unsigned N) : Index(N) {}
11538 
11539     public:
11540       Seq() = default;
11541     };
11542 
11543     SequenceTree() { Values.push_back(Value(0)); }
11544     Seq root() const { return Seq(0); }
11545 
11546     /// Create a new sequence of operations, which is an unsequenced
11547     /// subset of \p Parent. This sequence of operations is sequenced with
11548     /// respect to other children of \p Parent.
11549     Seq allocate(Seq Parent) {
11550       Values.push_back(Value(Parent.Index));
11551       return Seq(Values.size() - 1);
11552     }
11553 
11554     /// Merge a sequence of operations into its parent.
11555     void merge(Seq S) {
11556       Values[S.Index].Merged = true;
11557     }
11558 
11559     /// Determine whether two operations are unsequenced. This operation
11560     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11561     /// should have been merged into its parent as appropriate.
11562     bool isUnsequenced(Seq Cur, Seq Old) {
11563       unsigned C = representative(Cur.Index);
11564       unsigned Target = representative(Old.Index);
11565       while (C >= Target) {
11566         if (C == Target)
11567           return true;
11568         C = Values[C].Parent;
11569       }
11570       return false;
11571     }
11572 
11573   private:
11574     /// Pick a representative for a sequence.
11575     unsigned representative(unsigned K) {
11576       if (Values[K].Merged)
11577         // Perform path compression as we go.
11578         return Values[K].Parent = representative(Values[K].Parent);
11579       return K;
11580     }
11581   };
11582 
11583   /// An object for which we can track unsequenced uses.
11584   using Object = NamedDecl *;
11585 
11586   /// Different flavors of object usage which we track. We only track the
11587   /// least-sequenced usage of each kind.
11588   enum UsageKind {
11589     /// A read of an object. Multiple unsequenced reads are OK.
11590     UK_Use,
11591 
11592     /// A modification of an object which is sequenced before the value
11593     /// computation of the expression, such as ++n in C++.
11594     UK_ModAsValue,
11595 
11596     /// A modification of an object which is not sequenced before the value
11597     /// computation of the expression, such as n++.
11598     UK_ModAsSideEffect,
11599 
11600     UK_Count = UK_ModAsSideEffect + 1
11601   };
11602 
11603   struct Usage {
11604     Expr *Use = nullptr;
11605     SequenceTree::Seq Seq;
11606 
11607     Usage() = default;
11608   };
11609 
11610   struct UsageInfo {
11611     Usage Uses[UK_Count];
11612 
11613     /// Have we issued a diagnostic for this variable already?
11614     bool Diagnosed = false;
11615 
11616     UsageInfo() = default;
11617   };
11618   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11619 
11620   Sema &SemaRef;
11621 
11622   /// Sequenced regions within the expression.
11623   SequenceTree Tree;
11624 
11625   /// Declaration modifications and references which we have seen.
11626   UsageInfoMap UsageMap;
11627 
11628   /// The region we are currently within.
11629   SequenceTree::Seq Region;
11630 
11631   /// Filled in with declarations which were modified as a side-effect
11632   /// (that is, post-increment operations).
11633   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11634 
11635   /// Expressions to check later. We defer checking these to reduce
11636   /// stack usage.
11637   SmallVectorImpl<Expr *> &WorkList;
11638 
11639   /// RAII object wrapping the visitation of a sequenced subexpression of an
11640   /// expression. At the end of this process, the side-effects of the evaluation
11641   /// become sequenced with respect to the value computation of the result, so
11642   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11643   /// UK_ModAsValue.
11644   struct SequencedSubexpression {
11645     SequencedSubexpression(SequenceChecker &Self)
11646       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11647       Self.ModAsSideEffect = &ModAsSideEffect;
11648     }
11649 
11650     ~SequencedSubexpression() {
11651       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11652         UsageInfo &U = Self.UsageMap[M.first];
11653         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11654         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11655         SideEffectUsage = M.second;
11656       }
11657       Self.ModAsSideEffect = OldModAsSideEffect;
11658     }
11659 
11660     SequenceChecker &Self;
11661     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11662     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11663   };
11664 
11665   /// RAII object wrapping the visitation of a subexpression which we might
11666   /// choose to evaluate as a constant. If any subexpression is evaluated and
11667   /// found to be non-constant, this allows us to suppress the evaluation of
11668   /// the outer expression.
11669   class EvaluationTracker {
11670   public:
11671     EvaluationTracker(SequenceChecker &Self)
11672         : Self(Self), Prev(Self.EvalTracker) {
11673       Self.EvalTracker = this;
11674     }
11675 
11676     ~EvaluationTracker() {
11677       Self.EvalTracker = Prev;
11678       if (Prev)
11679         Prev->EvalOK &= EvalOK;
11680     }
11681 
11682     bool evaluate(const Expr *E, bool &Result) {
11683       if (!EvalOK || E->isValueDependent())
11684         return false;
11685       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11686       return EvalOK;
11687     }
11688 
11689   private:
11690     SequenceChecker &Self;
11691     EvaluationTracker *Prev;
11692     bool EvalOK = true;
11693   } *EvalTracker = nullptr;
11694 
11695   /// Find the object which is produced by the specified expression,
11696   /// if any.
11697   Object getObject(Expr *E, bool Mod) const {
11698     E = E->IgnoreParenCasts();
11699     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11700       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11701         return getObject(UO->getSubExpr(), Mod);
11702     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11703       if (BO->getOpcode() == BO_Comma)
11704         return getObject(BO->getRHS(), Mod);
11705       if (Mod && BO->isAssignmentOp())
11706         return getObject(BO->getLHS(), Mod);
11707     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11708       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11709       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11710         return ME->getMemberDecl();
11711     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11712       // FIXME: If this is a reference, map through to its value.
11713       return DRE->getDecl();
11714     return nullptr;
11715   }
11716 
11717   /// Note that an object was modified or used by an expression.
11718   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11719     Usage &U = UI.Uses[UK];
11720     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11721       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11722         ModAsSideEffect->push_back(std::make_pair(O, U));
11723       U.Use = Ref;
11724       U.Seq = Region;
11725     }
11726   }
11727 
11728   /// Check whether a modification or use conflicts with a prior usage.
11729   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11730                   bool IsModMod) {
11731     if (UI.Diagnosed)
11732       return;
11733 
11734     const Usage &U = UI.Uses[OtherKind];
11735     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11736       return;
11737 
11738     Expr *Mod = U.Use;
11739     Expr *ModOrUse = Ref;
11740     if (OtherKind == UK_Use)
11741       std::swap(Mod, ModOrUse);
11742 
11743     SemaRef.Diag(Mod->getExprLoc(),
11744                  IsModMod ? diag::warn_unsequenced_mod_mod
11745                           : diag::warn_unsequenced_mod_use)
11746       << O << SourceRange(ModOrUse->getExprLoc());
11747     UI.Diagnosed = true;
11748   }
11749 
11750   void notePreUse(Object O, Expr *Use) {
11751     UsageInfo &U = UsageMap[O];
11752     // Uses conflict with other modifications.
11753     checkUsage(O, U, Use, UK_ModAsValue, false);
11754   }
11755 
11756   void notePostUse(Object O, Expr *Use) {
11757     UsageInfo &U = UsageMap[O];
11758     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11759     addUsage(U, O, Use, UK_Use);
11760   }
11761 
11762   void notePreMod(Object O, Expr *Mod) {
11763     UsageInfo &U = UsageMap[O];
11764     // Modifications conflict with other modifications and with uses.
11765     checkUsage(O, U, Mod, UK_ModAsValue, true);
11766     checkUsage(O, U, Mod, UK_Use, false);
11767   }
11768 
11769   void notePostMod(Object O, Expr *Use, UsageKind UK) {
11770     UsageInfo &U = UsageMap[O];
11771     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11772     addUsage(U, O, Use, UK);
11773   }
11774 
11775 public:
11776   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
11777       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
11778     Visit(E);
11779   }
11780 
11781   void VisitStmt(Stmt *S) {
11782     // Skip all statements which aren't expressions for now.
11783   }
11784 
11785   void VisitExpr(Expr *E) {
11786     // By default, just recurse to evaluated subexpressions.
11787     Base::VisitStmt(E);
11788   }
11789 
11790   void VisitCastExpr(CastExpr *E) {
11791     Object O = Object();
11792     if (E->getCastKind() == CK_LValueToRValue)
11793       O = getObject(E->getSubExpr(), false);
11794 
11795     if (O)
11796       notePreUse(O, E);
11797     VisitExpr(E);
11798     if (O)
11799       notePostUse(O, E);
11800   }
11801 
11802   void VisitBinComma(BinaryOperator *BO) {
11803     // C++11 [expr.comma]p1:
11804     //   Every value computation and side effect associated with the left
11805     //   expression is sequenced before every value computation and side
11806     //   effect associated with the right expression.
11807     SequenceTree::Seq LHS = Tree.allocate(Region);
11808     SequenceTree::Seq RHS = Tree.allocate(Region);
11809     SequenceTree::Seq OldRegion = Region;
11810 
11811     {
11812       SequencedSubexpression SeqLHS(*this);
11813       Region = LHS;
11814       Visit(BO->getLHS());
11815     }
11816 
11817     Region = RHS;
11818     Visit(BO->getRHS());
11819 
11820     Region = OldRegion;
11821 
11822     // Forget that LHS and RHS are sequenced. They are both unsequenced
11823     // with respect to other stuff.
11824     Tree.merge(LHS);
11825     Tree.merge(RHS);
11826   }
11827 
11828   void VisitBinAssign(BinaryOperator *BO) {
11829     // The modification is sequenced after the value computation of the LHS
11830     // and RHS, so check it before inspecting the operands and update the
11831     // map afterwards.
11832     Object O = getObject(BO->getLHS(), true);
11833     if (!O)
11834       return VisitExpr(BO);
11835 
11836     notePreMod(O, BO);
11837 
11838     // C++11 [expr.ass]p7:
11839     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11840     //   only once.
11841     //
11842     // Therefore, for a compound assignment operator, O is considered used
11843     // everywhere except within the evaluation of E1 itself.
11844     if (isa<CompoundAssignOperator>(BO))
11845       notePreUse(O, BO);
11846 
11847     Visit(BO->getLHS());
11848 
11849     if (isa<CompoundAssignOperator>(BO))
11850       notePostUse(O, BO);
11851 
11852     Visit(BO->getRHS());
11853 
11854     // C++11 [expr.ass]p1:
11855     //   the assignment is sequenced [...] before the value computation of the
11856     //   assignment expression.
11857     // C11 6.5.16/3 has no such rule.
11858     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11859                                                        : UK_ModAsSideEffect);
11860   }
11861 
11862   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11863     VisitBinAssign(CAO);
11864   }
11865 
11866   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11867   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11868   void VisitUnaryPreIncDec(UnaryOperator *UO) {
11869     Object O = getObject(UO->getSubExpr(), true);
11870     if (!O)
11871       return VisitExpr(UO);
11872 
11873     notePreMod(O, UO);
11874     Visit(UO->getSubExpr());
11875     // C++11 [expr.pre.incr]p1:
11876     //   the expression ++x is equivalent to x+=1
11877     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11878                                                        : UK_ModAsSideEffect);
11879   }
11880 
11881   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11882   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11883   void VisitUnaryPostIncDec(UnaryOperator *UO) {
11884     Object O = getObject(UO->getSubExpr(), true);
11885     if (!O)
11886       return VisitExpr(UO);
11887 
11888     notePreMod(O, UO);
11889     Visit(UO->getSubExpr());
11890     notePostMod(O, UO, UK_ModAsSideEffect);
11891   }
11892 
11893   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11894   void VisitBinLOr(BinaryOperator *BO) {
11895     // The side-effects of the LHS of an '&&' are sequenced before the
11896     // value computation of the RHS, and hence before the value computation
11897     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11898     // as if they were unconditionally sequenced.
11899     EvaluationTracker Eval(*this);
11900     {
11901       SequencedSubexpression Sequenced(*this);
11902       Visit(BO->getLHS());
11903     }
11904 
11905     bool Result;
11906     if (Eval.evaluate(BO->getLHS(), Result)) {
11907       if (!Result)
11908         Visit(BO->getRHS());
11909     } else {
11910       // Check for unsequenced operations in the RHS, treating it as an
11911       // entirely separate evaluation.
11912       //
11913       // FIXME: If there are operations in the RHS which are unsequenced
11914       // with respect to operations outside the RHS, and those operations
11915       // are unconditionally evaluated, diagnose them.
11916       WorkList.push_back(BO->getRHS());
11917     }
11918   }
11919   void VisitBinLAnd(BinaryOperator *BO) {
11920     EvaluationTracker Eval(*this);
11921     {
11922       SequencedSubexpression Sequenced(*this);
11923       Visit(BO->getLHS());
11924     }
11925 
11926     bool Result;
11927     if (Eval.evaluate(BO->getLHS(), Result)) {
11928       if (Result)
11929         Visit(BO->getRHS());
11930     } else {
11931       WorkList.push_back(BO->getRHS());
11932     }
11933   }
11934 
11935   // Only visit the condition, unless we can be sure which subexpression will
11936   // be chosen.
11937   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
11938     EvaluationTracker Eval(*this);
11939     {
11940       SequencedSubexpression Sequenced(*this);
11941       Visit(CO->getCond());
11942     }
11943 
11944     bool Result;
11945     if (Eval.evaluate(CO->getCond(), Result))
11946       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
11947     else {
11948       WorkList.push_back(CO->getTrueExpr());
11949       WorkList.push_back(CO->getFalseExpr());
11950     }
11951   }
11952 
11953   void VisitCallExpr(CallExpr *CE) {
11954     // C++11 [intro.execution]p15:
11955     //   When calling a function [...], every value computation and side effect
11956     //   associated with any argument expression, or with the postfix expression
11957     //   designating the called function, is sequenced before execution of every
11958     //   expression or statement in the body of the function [and thus before
11959     //   the value computation of its result].
11960     SequencedSubexpression Sequenced(*this);
11961     Base::VisitCallExpr(CE);
11962 
11963     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11964   }
11965 
11966   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
11967     // This is a call, so all subexpressions are sequenced before the result.
11968     SequencedSubexpression Sequenced(*this);
11969 
11970     if (!CCE->isListInitialization())
11971       return VisitExpr(CCE);
11972 
11973     // In C++11, list initializations are sequenced.
11974     SmallVector<SequenceTree::Seq, 32> Elts;
11975     SequenceTree::Seq Parent = Region;
11976     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11977                                         E = CCE->arg_end();
11978          I != E; ++I) {
11979       Region = Tree.allocate(Parent);
11980       Elts.push_back(Region);
11981       Visit(*I);
11982     }
11983 
11984     // Forget that the initializers are sequenced.
11985     Region = Parent;
11986     for (unsigned I = 0; I < Elts.size(); ++I)
11987       Tree.merge(Elts[I]);
11988   }
11989 
11990   void VisitInitListExpr(InitListExpr *ILE) {
11991     if (!SemaRef.getLangOpts().CPlusPlus11)
11992       return VisitExpr(ILE);
11993 
11994     // In C++11, list initializations are sequenced.
11995     SmallVector<SequenceTree::Seq, 32> Elts;
11996     SequenceTree::Seq Parent = Region;
11997     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11998       Expr *E = ILE->getInit(I);
11999       if (!E) continue;
12000       Region = Tree.allocate(Parent);
12001       Elts.push_back(Region);
12002       Visit(E);
12003     }
12004 
12005     // Forget that the initializers are sequenced.
12006     Region = Parent;
12007     for (unsigned I = 0; I < Elts.size(); ++I)
12008       Tree.merge(Elts[I]);
12009   }
12010 };
12011 
12012 } // namespace
12013 
12014 void Sema::CheckUnsequencedOperations(Expr *E) {
12015   SmallVector<Expr *, 8> WorkList;
12016   WorkList.push_back(E);
12017   while (!WorkList.empty()) {
12018     Expr *Item = WorkList.pop_back_val();
12019     SequenceChecker(*this, Item, WorkList);
12020   }
12021 }
12022 
12023 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12024                               bool IsConstexpr) {
12025   CheckImplicitConversions(E, CheckLoc);
12026   if (!E->isInstantiationDependent())
12027     CheckUnsequencedOperations(E);
12028   if (!IsConstexpr && !E->isValueDependent())
12029     CheckForIntOverflow(E);
12030   DiagnoseMisalignedMembers();
12031 }
12032 
12033 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12034                                        FieldDecl *BitField,
12035                                        Expr *Init) {
12036   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12037 }
12038 
12039 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12040                                          SourceLocation Loc) {
12041   if (!PType->isVariablyModifiedType())
12042     return;
12043   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12044     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12045     return;
12046   }
12047   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12048     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12049     return;
12050   }
12051   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12052     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12053     return;
12054   }
12055 
12056   const ArrayType *AT = S.Context.getAsArrayType(PType);
12057   if (!AT)
12058     return;
12059 
12060   if (AT->getSizeModifier() != ArrayType::Star) {
12061     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12062     return;
12063   }
12064 
12065   S.Diag(Loc, diag::err_array_star_in_function_definition);
12066 }
12067 
12068 /// CheckParmsForFunctionDef - Check that the parameters of the given
12069 /// function are appropriate for the definition of a function. This
12070 /// takes care of any checks that cannot be performed on the
12071 /// declaration itself, e.g., that the types of each of the function
12072 /// parameters are complete.
12073 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12074                                     bool CheckParameterNames) {
12075   bool HasInvalidParm = false;
12076   for (ParmVarDecl *Param : Parameters) {
12077     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12078     // function declarator that is part of a function definition of
12079     // that function shall not have incomplete type.
12080     //
12081     // This is also C++ [dcl.fct]p6.
12082     if (!Param->isInvalidDecl() &&
12083         RequireCompleteType(Param->getLocation(), Param->getType(),
12084                             diag::err_typecheck_decl_incomplete_type)) {
12085       Param->setInvalidDecl();
12086       HasInvalidParm = true;
12087     }
12088 
12089     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12090     // declaration of each parameter shall include an identifier.
12091     if (CheckParameterNames &&
12092         Param->getIdentifier() == nullptr &&
12093         !Param->isImplicit() &&
12094         !getLangOpts().CPlusPlus)
12095       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12096 
12097     // C99 6.7.5.3p12:
12098     //   If the function declarator is not part of a definition of that
12099     //   function, parameters may have incomplete type and may use the [*]
12100     //   notation in their sequences of declarator specifiers to specify
12101     //   variable length array types.
12102     QualType PType = Param->getOriginalType();
12103     // FIXME: This diagnostic should point the '[*]' if source-location
12104     // information is added for it.
12105     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12106 
12107     // If the parameter is a c++ class type and it has to be destructed in the
12108     // callee function, declare the destructor so that it can be called by the
12109     // callee function. Do not perform any direct access check on the dtor here.
12110     if (!Param->isInvalidDecl()) {
12111       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12112         if (!ClassDecl->isInvalidDecl() &&
12113             !ClassDecl->hasIrrelevantDestructor() &&
12114             !ClassDecl->isDependentContext() &&
12115             ClassDecl->isParamDestroyedInCallee()) {
12116           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12117           MarkFunctionReferenced(Param->getLocation(), Destructor);
12118           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12119         }
12120       }
12121     }
12122 
12123     // Parameters with the pass_object_size attribute only need to be marked
12124     // constant at function definitions. Because we lack information about
12125     // whether we're on a declaration or definition when we're instantiating the
12126     // attribute, we need to check for constness here.
12127     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12128       if (!Param->getType().isConstQualified())
12129         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12130             << Attr->getSpelling() << 1;
12131   }
12132 
12133   return HasInvalidParm;
12134 }
12135 
12136 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12137 /// or MemberExpr.
12138 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12139                               ASTContext &Context) {
12140   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12141     return Context.getDeclAlign(DRE->getDecl());
12142 
12143   if (const auto *ME = dyn_cast<MemberExpr>(E))
12144     return Context.getDeclAlign(ME->getMemberDecl());
12145 
12146   return TypeAlign;
12147 }
12148 
12149 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12150 /// pointer cast increases the alignment requirements.
12151 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12152   // This is actually a lot of work to potentially be doing on every
12153   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12154   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12155     return;
12156 
12157   // Ignore dependent types.
12158   if (T->isDependentType() || Op->getType()->isDependentType())
12159     return;
12160 
12161   // Require that the destination be a pointer type.
12162   const PointerType *DestPtr = T->getAs<PointerType>();
12163   if (!DestPtr) return;
12164 
12165   // If the destination has alignment 1, we're done.
12166   QualType DestPointee = DestPtr->getPointeeType();
12167   if (DestPointee->isIncompleteType()) return;
12168   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12169   if (DestAlign.isOne()) return;
12170 
12171   // Require that the source be a pointer type.
12172   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12173   if (!SrcPtr) return;
12174   QualType SrcPointee = SrcPtr->getPointeeType();
12175 
12176   // Whitelist casts from cv void*.  We already implicitly
12177   // whitelisted casts to cv void*, since they have alignment 1.
12178   // Also whitelist casts involving incomplete types, which implicitly
12179   // includes 'void'.
12180   if (SrcPointee->isIncompleteType()) return;
12181 
12182   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12183 
12184   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12185     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12186       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12187   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12188     if (UO->getOpcode() == UO_AddrOf)
12189       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12190   }
12191 
12192   if (SrcAlign >= DestAlign) return;
12193 
12194   Diag(TRange.getBegin(), diag::warn_cast_align)
12195     << Op->getType() << T
12196     << static_cast<unsigned>(SrcAlign.getQuantity())
12197     << static_cast<unsigned>(DestAlign.getQuantity())
12198     << TRange << Op->getSourceRange();
12199 }
12200 
12201 /// Check whether this array fits the idiom of a size-one tail padded
12202 /// array member of a struct.
12203 ///
12204 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12205 /// commonly used to emulate flexible arrays in C89 code.
12206 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12207                                     const NamedDecl *ND) {
12208   if (Size != 1 || !ND) return false;
12209 
12210   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12211   if (!FD) return false;
12212 
12213   // Don't consider sizes resulting from macro expansions or template argument
12214   // substitution to form C89 tail-padded arrays.
12215 
12216   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12217   while (TInfo) {
12218     TypeLoc TL = TInfo->getTypeLoc();
12219     // Look through typedefs.
12220     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12221       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12222       TInfo = TDL->getTypeSourceInfo();
12223       continue;
12224     }
12225     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12226       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12227       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12228         return false;
12229     }
12230     break;
12231   }
12232 
12233   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12234   if (!RD) return false;
12235   if (RD->isUnion()) return false;
12236   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12237     if (!CRD->isStandardLayout()) return false;
12238   }
12239 
12240   // See if this is the last field decl in the record.
12241   const Decl *D = FD;
12242   while ((D = D->getNextDeclInContext()))
12243     if (isa<FieldDecl>(D))
12244       return false;
12245   return true;
12246 }
12247 
12248 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12249                             const ArraySubscriptExpr *ASE,
12250                             bool AllowOnePastEnd, bool IndexNegated) {
12251   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12252   if (IndexExpr->isValueDependent())
12253     return;
12254 
12255   const Type *EffectiveType =
12256       BaseExpr->getType()->getPointeeOrArrayElementType();
12257   BaseExpr = BaseExpr->IgnoreParenCasts();
12258   const ConstantArrayType *ArrayTy =
12259     Context.getAsConstantArrayType(BaseExpr->getType());
12260   if (!ArrayTy)
12261     return;
12262 
12263   llvm::APSInt index;
12264   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
12265     return;
12266   if (IndexNegated)
12267     index = -index;
12268 
12269   const NamedDecl *ND = nullptr;
12270   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12271     ND = DRE->getDecl();
12272   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12273     ND = ME->getMemberDecl();
12274 
12275   if (index.isUnsigned() || !index.isNegative()) {
12276     llvm::APInt size = ArrayTy->getSize();
12277     if (!size.isStrictlyPositive())
12278       return;
12279 
12280     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
12281     if (BaseType != EffectiveType) {
12282       // Make sure we're comparing apples to apples when comparing index to size
12283       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12284       uint64_t array_typesize = Context.getTypeSize(BaseType);
12285       // Handle ptrarith_typesize being zero, such as when casting to void*
12286       if (!ptrarith_typesize) ptrarith_typesize = 1;
12287       if (ptrarith_typesize != array_typesize) {
12288         // There's a cast to a different size type involved
12289         uint64_t ratio = array_typesize / ptrarith_typesize;
12290         // TODO: Be smarter about handling cases where array_typesize is not a
12291         // multiple of ptrarith_typesize
12292         if (ptrarith_typesize * ratio == array_typesize)
12293           size *= llvm::APInt(size.getBitWidth(), ratio);
12294       }
12295     }
12296 
12297     if (size.getBitWidth() > index.getBitWidth())
12298       index = index.zext(size.getBitWidth());
12299     else if (size.getBitWidth() < index.getBitWidth())
12300       size = size.zext(index.getBitWidth());
12301 
12302     // For array subscripting the index must be less than size, but for pointer
12303     // arithmetic also allow the index (offset) to be equal to size since
12304     // computing the next address after the end of the array is legal and
12305     // commonly done e.g. in C++ iterators and range-based for loops.
12306     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12307       return;
12308 
12309     // Also don't warn for arrays of size 1 which are members of some
12310     // structure. These are often used to approximate flexible arrays in C89
12311     // code.
12312     if (IsTailPaddedMemberArray(*this, size, ND))
12313       return;
12314 
12315     // Suppress the warning if the subscript expression (as identified by the
12316     // ']' location) and the index expression are both from macro expansions
12317     // within a system header.
12318     if (ASE) {
12319       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12320           ASE->getRBracketLoc());
12321       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12322         SourceLocation IndexLoc =
12323             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12324         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12325           return;
12326       }
12327     }
12328 
12329     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12330     if (ASE)
12331       DiagID = diag::warn_array_index_exceeds_bounds;
12332 
12333     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12334                         PDiag(DiagID) << index.toString(10, true)
12335                                       << size.toString(10, true)
12336                                       << (unsigned)size.getLimitedValue(~0U)
12337                                       << IndexExpr->getSourceRange());
12338   } else {
12339     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12340     if (!ASE) {
12341       DiagID = diag::warn_ptr_arith_precedes_bounds;
12342       if (index.isNegative()) index = -index;
12343     }
12344 
12345     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12346                         PDiag(DiagID) << index.toString(10, true)
12347                                       << IndexExpr->getSourceRange());
12348   }
12349 
12350   if (!ND) {
12351     // Try harder to find a NamedDecl to point at in the note.
12352     while (const ArraySubscriptExpr *ASE =
12353            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12354       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12355     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12356       ND = DRE->getDecl();
12357     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12358       ND = ME->getMemberDecl();
12359   }
12360 
12361   if (ND)
12362     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12363                         PDiag(diag::note_array_index_out_of_bounds)
12364                             << ND->getDeclName());
12365 }
12366 
12367 void Sema::CheckArrayAccess(const Expr *expr) {
12368   int AllowOnePastEnd = 0;
12369   while (expr) {
12370     expr = expr->IgnoreParenImpCasts();
12371     switch (expr->getStmtClass()) {
12372       case Stmt::ArraySubscriptExprClass: {
12373         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12374         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12375                          AllowOnePastEnd > 0);
12376         expr = ASE->getBase();
12377         break;
12378       }
12379       case Stmt::MemberExprClass: {
12380         expr = cast<MemberExpr>(expr)->getBase();
12381         break;
12382       }
12383       case Stmt::OMPArraySectionExprClass: {
12384         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12385         if (ASE->getLowerBound())
12386           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12387                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12388         return;
12389       }
12390       case Stmt::UnaryOperatorClass: {
12391         // Only unwrap the * and & unary operators
12392         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12393         expr = UO->getSubExpr();
12394         switch (UO->getOpcode()) {
12395           case UO_AddrOf:
12396             AllowOnePastEnd++;
12397             break;
12398           case UO_Deref:
12399             AllowOnePastEnd--;
12400             break;
12401           default:
12402             return;
12403         }
12404         break;
12405       }
12406       case Stmt::ConditionalOperatorClass: {
12407         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12408         if (const Expr *lhs = cond->getLHS())
12409           CheckArrayAccess(lhs);
12410         if (const Expr *rhs = cond->getRHS())
12411           CheckArrayAccess(rhs);
12412         return;
12413       }
12414       case Stmt::CXXOperatorCallExprClass: {
12415         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12416         for (const auto *Arg : OCE->arguments())
12417           CheckArrayAccess(Arg);
12418         return;
12419       }
12420       default:
12421         return;
12422     }
12423   }
12424 }
12425 
12426 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12427 
12428 namespace {
12429 
12430 struct RetainCycleOwner {
12431   VarDecl *Variable = nullptr;
12432   SourceRange Range;
12433   SourceLocation Loc;
12434   bool Indirect = false;
12435 
12436   RetainCycleOwner() = default;
12437 
12438   void setLocsFrom(Expr *e) {
12439     Loc = e->getExprLoc();
12440     Range = e->getSourceRange();
12441   }
12442 };
12443 
12444 } // namespace
12445 
12446 /// Consider whether capturing the given variable can possibly lead to
12447 /// a retain cycle.
12448 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12449   // In ARC, it's captured strongly iff the variable has __strong
12450   // lifetime.  In MRR, it's captured strongly if the variable is
12451   // __block and has an appropriate type.
12452   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12453     return false;
12454 
12455   owner.Variable = var;
12456   if (ref)
12457     owner.setLocsFrom(ref);
12458   return true;
12459 }
12460 
12461 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12462   while (true) {
12463     e = e->IgnoreParens();
12464     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12465       switch (cast->getCastKind()) {
12466       case CK_BitCast:
12467       case CK_LValueBitCast:
12468       case CK_LValueToRValue:
12469       case CK_ARCReclaimReturnedObject:
12470         e = cast->getSubExpr();
12471         continue;
12472 
12473       default:
12474         return false;
12475       }
12476     }
12477 
12478     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12479       ObjCIvarDecl *ivar = ref->getDecl();
12480       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12481         return false;
12482 
12483       // Try to find a retain cycle in the base.
12484       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12485         return false;
12486 
12487       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12488       owner.Indirect = true;
12489       return true;
12490     }
12491 
12492     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12493       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12494       if (!var) return false;
12495       return considerVariable(var, ref, owner);
12496     }
12497 
12498     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12499       if (member->isArrow()) return false;
12500 
12501       // Don't count this as an indirect ownership.
12502       e = member->getBase();
12503       continue;
12504     }
12505 
12506     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12507       // Only pay attention to pseudo-objects on property references.
12508       ObjCPropertyRefExpr *pre
12509         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12510                                               ->IgnoreParens());
12511       if (!pre) return false;
12512       if (pre->isImplicitProperty()) return false;
12513       ObjCPropertyDecl *property = pre->getExplicitProperty();
12514       if (!property->isRetaining() &&
12515           !(property->getPropertyIvarDecl() &&
12516             property->getPropertyIvarDecl()->getType()
12517               .getObjCLifetime() == Qualifiers::OCL_Strong))
12518           return false;
12519 
12520       owner.Indirect = true;
12521       if (pre->isSuperReceiver()) {
12522         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12523         if (!owner.Variable)
12524           return false;
12525         owner.Loc = pre->getLocation();
12526         owner.Range = pre->getSourceRange();
12527         return true;
12528       }
12529       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12530                               ->getSourceExpr());
12531       continue;
12532     }
12533 
12534     // Array ivars?
12535 
12536     return false;
12537   }
12538 }
12539 
12540 namespace {
12541 
12542   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12543     ASTContext &Context;
12544     VarDecl *Variable;
12545     Expr *Capturer = nullptr;
12546     bool VarWillBeReased = false;
12547 
12548     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12549         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12550           Context(Context), Variable(variable) {}
12551 
12552     void VisitDeclRefExpr(DeclRefExpr *ref) {
12553       if (ref->getDecl() == Variable && !Capturer)
12554         Capturer = ref;
12555     }
12556 
12557     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12558       if (Capturer) return;
12559       Visit(ref->getBase());
12560       if (Capturer && ref->isFreeIvar())
12561         Capturer = ref;
12562     }
12563 
12564     void VisitBlockExpr(BlockExpr *block) {
12565       // Look inside nested blocks
12566       if (block->getBlockDecl()->capturesVariable(Variable))
12567         Visit(block->getBlockDecl()->getBody());
12568     }
12569 
12570     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12571       if (Capturer) return;
12572       if (OVE->getSourceExpr())
12573         Visit(OVE->getSourceExpr());
12574     }
12575 
12576     void VisitBinaryOperator(BinaryOperator *BinOp) {
12577       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12578         return;
12579       Expr *LHS = BinOp->getLHS();
12580       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12581         if (DRE->getDecl() != Variable)
12582           return;
12583         if (Expr *RHS = BinOp->getRHS()) {
12584           RHS = RHS->IgnoreParenCasts();
12585           llvm::APSInt Value;
12586           VarWillBeReased =
12587             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12588         }
12589       }
12590     }
12591   };
12592 
12593 } // namespace
12594 
12595 /// Check whether the given argument is a block which captures a
12596 /// variable.
12597 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12598   assert(owner.Variable && owner.Loc.isValid());
12599 
12600   e = e->IgnoreParenCasts();
12601 
12602   // Look through [^{...} copy] and Block_copy(^{...}).
12603   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12604     Selector Cmd = ME->getSelector();
12605     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12606       e = ME->getInstanceReceiver();
12607       if (!e)
12608         return nullptr;
12609       e = e->IgnoreParenCasts();
12610     }
12611   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12612     if (CE->getNumArgs() == 1) {
12613       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12614       if (Fn) {
12615         const IdentifierInfo *FnI = Fn->getIdentifier();
12616         if (FnI && FnI->isStr("_Block_copy")) {
12617           e = CE->getArg(0)->IgnoreParenCasts();
12618         }
12619       }
12620     }
12621   }
12622 
12623   BlockExpr *block = dyn_cast<BlockExpr>(e);
12624   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12625     return nullptr;
12626 
12627   FindCaptureVisitor visitor(S.Context, owner.Variable);
12628   visitor.Visit(block->getBlockDecl()->getBody());
12629   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12630 }
12631 
12632 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12633                                 RetainCycleOwner &owner) {
12634   assert(capturer);
12635   assert(owner.Variable && owner.Loc.isValid());
12636 
12637   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12638     << owner.Variable << capturer->getSourceRange();
12639   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12640     << owner.Indirect << owner.Range;
12641 }
12642 
12643 /// Check for a keyword selector that starts with the word 'add' or
12644 /// 'set'.
12645 static bool isSetterLikeSelector(Selector sel) {
12646   if (sel.isUnarySelector()) return false;
12647 
12648   StringRef str = sel.getNameForSlot(0);
12649   while (!str.empty() && str.front() == '_') str = str.substr(1);
12650   if (str.startswith("set"))
12651     str = str.substr(3);
12652   else if (str.startswith("add")) {
12653     // Specially whitelist 'addOperationWithBlock:'.
12654     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12655       return false;
12656     str = str.substr(3);
12657   }
12658   else
12659     return false;
12660 
12661   if (str.empty()) return true;
12662   return !isLowercase(str.front());
12663 }
12664 
12665 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12666                                                     ObjCMessageExpr *Message) {
12667   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12668                                                 Message->getReceiverInterface(),
12669                                                 NSAPI::ClassId_NSMutableArray);
12670   if (!IsMutableArray) {
12671     return None;
12672   }
12673 
12674   Selector Sel = Message->getSelector();
12675 
12676   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12677     S.NSAPIObj->getNSArrayMethodKind(Sel);
12678   if (!MKOpt) {
12679     return None;
12680   }
12681 
12682   NSAPI::NSArrayMethodKind MK = *MKOpt;
12683 
12684   switch (MK) {
12685     case NSAPI::NSMutableArr_addObject:
12686     case NSAPI::NSMutableArr_insertObjectAtIndex:
12687     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12688       return 0;
12689     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12690       return 1;
12691 
12692     default:
12693       return None;
12694   }
12695 
12696   return None;
12697 }
12698 
12699 static
12700 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12701                                                   ObjCMessageExpr *Message) {
12702   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12703                                             Message->getReceiverInterface(),
12704                                             NSAPI::ClassId_NSMutableDictionary);
12705   if (!IsMutableDictionary) {
12706     return None;
12707   }
12708 
12709   Selector Sel = Message->getSelector();
12710 
12711   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12712     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12713   if (!MKOpt) {
12714     return None;
12715   }
12716 
12717   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12718 
12719   switch (MK) {
12720     case NSAPI::NSMutableDict_setObjectForKey:
12721     case NSAPI::NSMutableDict_setValueForKey:
12722     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12723       return 0;
12724 
12725     default:
12726       return None;
12727   }
12728 
12729   return None;
12730 }
12731 
12732 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
12733   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12734                                                 Message->getReceiverInterface(),
12735                                                 NSAPI::ClassId_NSMutableSet);
12736 
12737   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12738                                             Message->getReceiverInterface(),
12739                                             NSAPI::ClassId_NSMutableOrderedSet);
12740   if (!IsMutableSet && !IsMutableOrderedSet) {
12741     return None;
12742   }
12743 
12744   Selector Sel = Message->getSelector();
12745 
12746   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12747   if (!MKOpt) {
12748     return None;
12749   }
12750 
12751   NSAPI::NSSetMethodKind MK = *MKOpt;
12752 
12753   switch (MK) {
12754     case NSAPI::NSMutableSet_addObject:
12755     case NSAPI::NSOrderedSet_setObjectAtIndex:
12756     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12757     case NSAPI::NSOrderedSet_insertObjectAtIndex:
12758       return 0;
12759     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12760       return 1;
12761   }
12762 
12763   return None;
12764 }
12765 
12766 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12767   if (!Message->isInstanceMessage()) {
12768     return;
12769   }
12770 
12771   Optional<int> ArgOpt;
12772 
12773   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12774       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12775       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12776     return;
12777   }
12778 
12779   int ArgIndex = *ArgOpt;
12780 
12781   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12782   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12783     Arg = OE->getSourceExpr()->IgnoreImpCasts();
12784   }
12785 
12786   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12787     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12788       if (ArgRE->isObjCSelfExpr()) {
12789         Diag(Message->getSourceRange().getBegin(),
12790              diag::warn_objc_circular_container)
12791           << ArgRE->getDecl() << StringRef("'super'");
12792       }
12793     }
12794   } else {
12795     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12796 
12797     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12798       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12799     }
12800 
12801     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12802       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12803         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12804           ValueDecl *Decl = ReceiverRE->getDecl();
12805           Diag(Message->getSourceRange().getBegin(),
12806                diag::warn_objc_circular_container)
12807             << Decl << Decl;
12808           if (!ArgRE->isObjCSelfExpr()) {
12809             Diag(Decl->getLocation(),
12810                  diag::note_objc_circular_container_declared_here)
12811               << Decl;
12812           }
12813         }
12814       }
12815     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12816       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12817         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12818           ObjCIvarDecl *Decl = IvarRE->getDecl();
12819           Diag(Message->getSourceRange().getBegin(),
12820                diag::warn_objc_circular_container)
12821             << Decl << Decl;
12822           Diag(Decl->getLocation(),
12823                diag::note_objc_circular_container_declared_here)
12824             << Decl;
12825         }
12826       }
12827     }
12828   }
12829 }
12830 
12831 /// Check a message send to see if it's likely to cause a retain cycle.
12832 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12833   // Only check instance methods whose selector looks like a setter.
12834   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12835     return;
12836 
12837   // Try to find a variable that the receiver is strongly owned by.
12838   RetainCycleOwner owner;
12839   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
12840     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
12841       return;
12842   } else {
12843     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12844     owner.Variable = getCurMethodDecl()->getSelfDecl();
12845     owner.Loc = msg->getSuperLoc();
12846     owner.Range = msg->getSuperLoc();
12847   }
12848 
12849   // Check whether the receiver is captured by any of the arguments.
12850   const ObjCMethodDecl *MD = msg->getMethodDecl();
12851   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12852     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12853       // noescape blocks should not be retained by the method.
12854       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12855         continue;
12856       return diagnoseRetainCycle(*this, capturer, owner);
12857     }
12858   }
12859 }
12860 
12861 /// Check a property assign to see if it's likely to cause a retain cycle.
12862 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12863   RetainCycleOwner owner;
12864   if (!findRetainCycleOwner(*this, receiver, owner))
12865     return;
12866 
12867   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12868     diagnoseRetainCycle(*this, capturer, owner);
12869 }
12870 
12871 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12872   RetainCycleOwner Owner;
12873   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
12874     return;
12875 
12876   // Because we don't have an expression for the variable, we have to set the
12877   // location explicitly here.
12878   Owner.Loc = Var->getLocation();
12879   Owner.Range = Var->getSourceRange();
12880 
12881   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12882     diagnoseRetainCycle(*this, Capturer, Owner);
12883 }
12884 
12885 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12886                                      Expr *RHS, bool isProperty) {
12887   // Check if RHS is an Objective-C object literal, which also can get
12888   // immediately zapped in a weak reference.  Note that we explicitly
12889   // allow ObjCStringLiterals, since those are designed to never really die.
12890   RHS = RHS->IgnoreParenImpCasts();
12891 
12892   // This enum needs to match with the 'select' in
12893   // warn_objc_arc_literal_assign (off-by-1).
12894   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12895   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12896     return false;
12897 
12898   S.Diag(Loc, diag::warn_arc_literal_assign)
12899     << (unsigned) Kind
12900     << (isProperty ? 0 : 1)
12901     << RHS->getSourceRange();
12902 
12903   return true;
12904 }
12905 
12906 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12907                                     Qualifiers::ObjCLifetime LT,
12908                                     Expr *RHS, bool isProperty) {
12909   // Strip off any implicit cast added to get to the one ARC-specific.
12910   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12911     if (cast->getCastKind() == CK_ARCConsumeObject) {
12912       S.Diag(Loc, diag::warn_arc_retained_assign)
12913         << (LT == Qualifiers::OCL_ExplicitNone)
12914         << (isProperty ? 0 : 1)
12915         << RHS->getSourceRange();
12916       return true;
12917     }
12918     RHS = cast->getSubExpr();
12919   }
12920 
12921   if (LT == Qualifiers::OCL_Weak &&
12922       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12923     return true;
12924 
12925   return false;
12926 }
12927 
12928 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12929                               QualType LHS, Expr *RHS) {
12930   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12931 
12932   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12933     return false;
12934 
12935   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12936     return true;
12937 
12938   return false;
12939 }
12940 
12941 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12942                               Expr *LHS, Expr *RHS) {
12943   QualType LHSType;
12944   // PropertyRef on LHS type need be directly obtained from
12945   // its declaration as it has a PseudoType.
12946   ObjCPropertyRefExpr *PRE
12947     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12948   if (PRE && !PRE->isImplicitProperty()) {
12949     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12950     if (PD)
12951       LHSType = PD->getType();
12952   }
12953 
12954   if (LHSType.isNull())
12955     LHSType = LHS->getType();
12956 
12957   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12958 
12959   if (LT == Qualifiers::OCL_Weak) {
12960     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
12961       getCurFunction()->markSafeWeakUse(LHS);
12962   }
12963 
12964   if (checkUnsafeAssigns(Loc, LHSType, RHS))
12965     return;
12966 
12967   // FIXME. Check for other life times.
12968   if (LT != Qualifiers::OCL_None)
12969     return;
12970 
12971   if (PRE) {
12972     if (PRE->isImplicitProperty())
12973       return;
12974     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12975     if (!PD)
12976       return;
12977 
12978     unsigned Attributes = PD->getPropertyAttributes();
12979     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
12980       // when 'assign' attribute was not explicitly specified
12981       // by user, ignore it and rely on property type itself
12982       // for lifetime info.
12983       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12984       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12985           LHSType->isObjCRetainableType())
12986         return;
12987 
12988       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12989         if (cast->getCastKind() == CK_ARCConsumeObject) {
12990           Diag(Loc, diag::warn_arc_retained_property_assign)
12991           << RHS->getSourceRange();
12992           return;
12993         }
12994         RHS = cast->getSubExpr();
12995       }
12996     }
12997     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
12998       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12999         return;
13000     }
13001   }
13002 }
13003 
13004 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13005 
13006 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13007                                         SourceLocation StmtLoc,
13008                                         const NullStmt *Body) {
13009   // Do not warn if the body is a macro that expands to nothing, e.g:
13010   //
13011   // #define CALL(x)
13012   // if (condition)
13013   //   CALL(0);
13014   if (Body->hasLeadingEmptyMacro())
13015     return false;
13016 
13017   // Get line numbers of statement and body.
13018   bool StmtLineInvalid;
13019   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13020                                                       &StmtLineInvalid);
13021   if (StmtLineInvalid)
13022     return false;
13023 
13024   bool BodyLineInvalid;
13025   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13026                                                       &BodyLineInvalid);
13027   if (BodyLineInvalid)
13028     return false;
13029 
13030   // Warn if null statement and body are on the same line.
13031   if (StmtLine != BodyLine)
13032     return false;
13033 
13034   return true;
13035 }
13036 
13037 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13038                                  const Stmt *Body,
13039                                  unsigned DiagID) {
13040   // Since this is a syntactic check, don't emit diagnostic for template
13041   // instantiations, this just adds noise.
13042   if (CurrentInstantiationScope)
13043     return;
13044 
13045   // The body should be a null statement.
13046   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13047   if (!NBody)
13048     return;
13049 
13050   // Do the usual checks.
13051   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13052     return;
13053 
13054   Diag(NBody->getSemiLoc(), DiagID);
13055   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13056 }
13057 
13058 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13059                                  const Stmt *PossibleBody) {
13060   assert(!CurrentInstantiationScope); // Ensured by caller
13061 
13062   SourceLocation StmtLoc;
13063   const Stmt *Body;
13064   unsigned DiagID;
13065   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13066     StmtLoc = FS->getRParenLoc();
13067     Body = FS->getBody();
13068     DiagID = diag::warn_empty_for_body;
13069   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13070     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13071     Body = WS->getBody();
13072     DiagID = diag::warn_empty_while_body;
13073   } else
13074     return; // Neither `for' nor `while'.
13075 
13076   // The body should be a null statement.
13077   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13078   if (!NBody)
13079     return;
13080 
13081   // Skip expensive checks if diagnostic is disabled.
13082   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13083     return;
13084 
13085   // Do the usual checks.
13086   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13087     return;
13088 
13089   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13090   // noise level low, emit diagnostics only if for/while is followed by a
13091   // CompoundStmt, e.g.:
13092   //    for (int i = 0; i < n; i++);
13093   //    {
13094   //      a(i);
13095   //    }
13096   // or if for/while is followed by a statement with more indentation
13097   // than for/while itself:
13098   //    for (int i = 0; i < n; i++);
13099   //      a(i);
13100   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13101   if (!ProbableTypo) {
13102     bool BodyColInvalid;
13103     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13104         PossibleBody->getBeginLoc(), &BodyColInvalid);
13105     if (BodyColInvalid)
13106       return;
13107 
13108     bool StmtColInvalid;
13109     unsigned StmtCol =
13110         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13111     if (StmtColInvalid)
13112       return;
13113 
13114     if (BodyCol > StmtCol)
13115       ProbableTypo = true;
13116   }
13117 
13118   if (ProbableTypo) {
13119     Diag(NBody->getSemiLoc(), DiagID);
13120     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13121   }
13122 }
13123 
13124 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13125 
13126 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13127 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13128                              SourceLocation OpLoc) {
13129   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13130     return;
13131 
13132   if (inTemplateInstantiation())
13133     return;
13134 
13135   // Strip parens and casts away.
13136   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13137   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13138 
13139   // Check for a call expression
13140   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13141   if (!CE || CE->getNumArgs() != 1)
13142     return;
13143 
13144   // Check for a call to std::move
13145   if (!CE->isCallToStdMove())
13146     return;
13147 
13148   // Get argument from std::move
13149   RHSExpr = CE->getArg(0);
13150 
13151   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13152   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13153 
13154   // Two DeclRefExpr's, check that the decls are the same.
13155   if (LHSDeclRef && RHSDeclRef) {
13156     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13157       return;
13158     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13159         RHSDeclRef->getDecl()->getCanonicalDecl())
13160       return;
13161 
13162     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13163                                         << LHSExpr->getSourceRange()
13164                                         << RHSExpr->getSourceRange();
13165     return;
13166   }
13167 
13168   // Member variables require a different approach to check for self moves.
13169   // MemberExpr's are the same if every nested MemberExpr refers to the same
13170   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13171   // the base Expr's are CXXThisExpr's.
13172   const Expr *LHSBase = LHSExpr;
13173   const Expr *RHSBase = RHSExpr;
13174   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13175   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13176   if (!LHSME || !RHSME)
13177     return;
13178 
13179   while (LHSME && RHSME) {
13180     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13181         RHSME->getMemberDecl()->getCanonicalDecl())
13182       return;
13183 
13184     LHSBase = LHSME->getBase();
13185     RHSBase = RHSME->getBase();
13186     LHSME = dyn_cast<MemberExpr>(LHSBase);
13187     RHSME = dyn_cast<MemberExpr>(RHSBase);
13188   }
13189 
13190   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13191   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13192   if (LHSDeclRef && RHSDeclRef) {
13193     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13194       return;
13195     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13196         RHSDeclRef->getDecl()->getCanonicalDecl())
13197       return;
13198 
13199     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13200                                         << LHSExpr->getSourceRange()
13201                                         << RHSExpr->getSourceRange();
13202     return;
13203   }
13204 
13205   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13206     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13207                                         << LHSExpr->getSourceRange()
13208                                         << RHSExpr->getSourceRange();
13209 }
13210 
13211 //===--- Layout compatibility ----------------------------------------------//
13212 
13213 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13214 
13215 /// Check if two enumeration types are layout-compatible.
13216 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13217   // C++11 [dcl.enum] p8:
13218   // Two enumeration types are layout-compatible if they have the same
13219   // underlying type.
13220   return ED1->isComplete() && ED2->isComplete() &&
13221          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13222 }
13223 
13224 /// Check if two fields are layout-compatible.
13225 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13226                                FieldDecl *Field2) {
13227   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13228     return false;
13229 
13230   if (Field1->isBitField() != Field2->isBitField())
13231     return false;
13232 
13233   if (Field1->isBitField()) {
13234     // Make sure that the bit-fields are the same length.
13235     unsigned Bits1 = Field1->getBitWidthValue(C);
13236     unsigned Bits2 = Field2->getBitWidthValue(C);
13237 
13238     if (Bits1 != Bits2)
13239       return false;
13240   }
13241 
13242   return true;
13243 }
13244 
13245 /// Check if two standard-layout structs are layout-compatible.
13246 /// (C++11 [class.mem] p17)
13247 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13248                                      RecordDecl *RD2) {
13249   // If both records are C++ classes, check that base classes match.
13250   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13251     // If one of records is a CXXRecordDecl we are in C++ mode,
13252     // thus the other one is a CXXRecordDecl, too.
13253     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13254     // Check number of base classes.
13255     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13256       return false;
13257 
13258     // Check the base classes.
13259     for (CXXRecordDecl::base_class_const_iterator
13260                Base1 = D1CXX->bases_begin(),
13261            BaseEnd1 = D1CXX->bases_end(),
13262               Base2 = D2CXX->bases_begin();
13263          Base1 != BaseEnd1;
13264          ++Base1, ++Base2) {
13265       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13266         return false;
13267     }
13268   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13269     // If only RD2 is a C++ class, it should have zero base classes.
13270     if (D2CXX->getNumBases() > 0)
13271       return false;
13272   }
13273 
13274   // Check the fields.
13275   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13276                              Field2End = RD2->field_end(),
13277                              Field1 = RD1->field_begin(),
13278                              Field1End = RD1->field_end();
13279   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13280     if (!isLayoutCompatible(C, *Field1, *Field2))
13281       return false;
13282   }
13283   if (Field1 != Field1End || Field2 != Field2End)
13284     return false;
13285 
13286   return true;
13287 }
13288 
13289 /// Check if two standard-layout unions are layout-compatible.
13290 /// (C++11 [class.mem] p18)
13291 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13292                                     RecordDecl *RD2) {
13293   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13294   for (auto *Field2 : RD2->fields())
13295     UnmatchedFields.insert(Field2);
13296 
13297   for (auto *Field1 : RD1->fields()) {
13298     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13299         I = UnmatchedFields.begin(),
13300         E = UnmatchedFields.end();
13301 
13302     for ( ; I != E; ++I) {
13303       if (isLayoutCompatible(C, Field1, *I)) {
13304         bool Result = UnmatchedFields.erase(*I);
13305         (void) Result;
13306         assert(Result);
13307         break;
13308       }
13309     }
13310     if (I == E)
13311       return false;
13312   }
13313 
13314   return UnmatchedFields.empty();
13315 }
13316 
13317 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13318                                RecordDecl *RD2) {
13319   if (RD1->isUnion() != RD2->isUnion())
13320     return false;
13321 
13322   if (RD1->isUnion())
13323     return isLayoutCompatibleUnion(C, RD1, RD2);
13324   else
13325     return isLayoutCompatibleStruct(C, RD1, RD2);
13326 }
13327 
13328 /// Check if two types are layout-compatible in C++11 sense.
13329 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13330   if (T1.isNull() || T2.isNull())
13331     return false;
13332 
13333   // C++11 [basic.types] p11:
13334   // If two types T1 and T2 are the same type, then T1 and T2 are
13335   // layout-compatible types.
13336   if (C.hasSameType(T1, T2))
13337     return true;
13338 
13339   T1 = T1.getCanonicalType().getUnqualifiedType();
13340   T2 = T2.getCanonicalType().getUnqualifiedType();
13341 
13342   const Type::TypeClass TC1 = T1->getTypeClass();
13343   const Type::TypeClass TC2 = T2->getTypeClass();
13344 
13345   if (TC1 != TC2)
13346     return false;
13347 
13348   if (TC1 == Type::Enum) {
13349     return isLayoutCompatible(C,
13350                               cast<EnumType>(T1)->getDecl(),
13351                               cast<EnumType>(T2)->getDecl());
13352   } else if (TC1 == Type::Record) {
13353     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13354       return false;
13355 
13356     return isLayoutCompatible(C,
13357                               cast<RecordType>(T1)->getDecl(),
13358                               cast<RecordType>(T2)->getDecl());
13359   }
13360 
13361   return false;
13362 }
13363 
13364 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13365 
13366 /// Given a type tag expression find the type tag itself.
13367 ///
13368 /// \param TypeExpr Type tag expression, as it appears in user's code.
13369 ///
13370 /// \param VD Declaration of an identifier that appears in a type tag.
13371 ///
13372 /// \param MagicValue Type tag magic value.
13373 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13374                             const ValueDecl **VD, uint64_t *MagicValue) {
13375   while(true) {
13376     if (!TypeExpr)
13377       return false;
13378 
13379     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13380 
13381     switch (TypeExpr->getStmtClass()) {
13382     case Stmt::UnaryOperatorClass: {
13383       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13384       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13385         TypeExpr = UO->getSubExpr();
13386         continue;
13387       }
13388       return false;
13389     }
13390 
13391     case Stmt::DeclRefExprClass: {
13392       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13393       *VD = DRE->getDecl();
13394       return true;
13395     }
13396 
13397     case Stmt::IntegerLiteralClass: {
13398       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13399       llvm::APInt MagicValueAPInt = IL->getValue();
13400       if (MagicValueAPInt.getActiveBits() <= 64) {
13401         *MagicValue = MagicValueAPInt.getZExtValue();
13402         return true;
13403       } else
13404         return false;
13405     }
13406 
13407     case Stmt::BinaryConditionalOperatorClass:
13408     case Stmt::ConditionalOperatorClass: {
13409       const AbstractConditionalOperator *ACO =
13410           cast<AbstractConditionalOperator>(TypeExpr);
13411       bool Result;
13412       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13413         if (Result)
13414           TypeExpr = ACO->getTrueExpr();
13415         else
13416           TypeExpr = ACO->getFalseExpr();
13417         continue;
13418       }
13419       return false;
13420     }
13421 
13422     case Stmt::BinaryOperatorClass: {
13423       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13424       if (BO->getOpcode() == BO_Comma) {
13425         TypeExpr = BO->getRHS();
13426         continue;
13427       }
13428       return false;
13429     }
13430 
13431     default:
13432       return false;
13433     }
13434   }
13435 }
13436 
13437 /// Retrieve the C type corresponding to type tag TypeExpr.
13438 ///
13439 /// \param TypeExpr Expression that specifies a type tag.
13440 ///
13441 /// \param MagicValues Registered magic values.
13442 ///
13443 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13444 ///        kind.
13445 ///
13446 /// \param TypeInfo Information about the corresponding C type.
13447 ///
13448 /// \returns true if the corresponding C type was found.
13449 static bool GetMatchingCType(
13450         const IdentifierInfo *ArgumentKind,
13451         const Expr *TypeExpr, const ASTContext &Ctx,
13452         const llvm::DenseMap<Sema::TypeTagMagicValue,
13453                              Sema::TypeTagData> *MagicValues,
13454         bool &FoundWrongKind,
13455         Sema::TypeTagData &TypeInfo) {
13456   FoundWrongKind = false;
13457 
13458   // Variable declaration that has type_tag_for_datatype attribute.
13459   const ValueDecl *VD = nullptr;
13460 
13461   uint64_t MagicValue;
13462 
13463   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13464     return false;
13465 
13466   if (VD) {
13467     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13468       if (I->getArgumentKind() != ArgumentKind) {
13469         FoundWrongKind = true;
13470         return false;
13471       }
13472       TypeInfo.Type = I->getMatchingCType();
13473       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13474       TypeInfo.MustBeNull = I->getMustBeNull();
13475       return true;
13476     }
13477     return false;
13478   }
13479 
13480   if (!MagicValues)
13481     return false;
13482 
13483   llvm::DenseMap<Sema::TypeTagMagicValue,
13484                  Sema::TypeTagData>::const_iterator I =
13485       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13486   if (I == MagicValues->end())
13487     return false;
13488 
13489   TypeInfo = I->second;
13490   return true;
13491 }
13492 
13493 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13494                                       uint64_t MagicValue, QualType Type,
13495                                       bool LayoutCompatible,
13496                                       bool MustBeNull) {
13497   if (!TypeTagForDatatypeMagicValues)
13498     TypeTagForDatatypeMagicValues.reset(
13499         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13500 
13501   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13502   (*TypeTagForDatatypeMagicValues)[Magic] =
13503       TypeTagData(Type, LayoutCompatible, MustBeNull);
13504 }
13505 
13506 static bool IsSameCharType(QualType T1, QualType T2) {
13507   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13508   if (!BT1)
13509     return false;
13510 
13511   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13512   if (!BT2)
13513     return false;
13514 
13515   BuiltinType::Kind T1Kind = BT1->getKind();
13516   BuiltinType::Kind T2Kind = BT2->getKind();
13517 
13518   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13519          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13520          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13521          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13522 }
13523 
13524 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13525                                     const ArrayRef<const Expr *> ExprArgs,
13526                                     SourceLocation CallSiteLoc) {
13527   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13528   bool IsPointerAttr = Attr->getIsPointer();
13529 
13530   // Retrieve the argument representing the 'type_tag'.
13531   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13532   if (TypeTagIdxAST >= ExprArgs.size()) {
13533     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13534         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13535     return;
13536   }
13537   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13538   bool FoundWrongKind;
13539   TypeTagData TypeInfo;
13540   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13541                         TypeTagForDatatypeMagicValues.get(),
13542                         FoundWrongKind, TypeInfo)) {
13543     if (FoundWrongKind)
13544       Diag(TypeTagExpr->getExprLoc(),
13545            diag::warn_type_tag_for_datatype_wrong_kind)
13546         << TypeTagExpr->getSourceRange();
13547     return;
13548   }
13549 
13550   // Retrieve the argument representing the 'arg_idx'.
13551   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13552   if (ArgumentIdxAST >= ExprArgs.size()) {
13553     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13554         << 1 << Attr->getArgumentIdx().getSourceIndex();
13555     return;
13556   }
13557   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13558   if (IsPointerAttr) {
13559     // Skip implicit cast of pointer to `void *' (as a function argument).
13560     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13561       if (ICE->getType()->isVoidPointerType() &&
13562           ICE->getCastKind() == CK_BitCast)
13563         ArgumentExpr = ICE->getSubExpr();
13564   }
13565   QualType ArgumentType = ArgumentExpr->getType();
13566 
13567   // Passing a `void*' pointer shouldn't trigger a warning.
13568   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13569     return;
13570 
13571   if (TypeInfo.MustBeNull) {
13572     // Type tag with matching void type requires a null pointer.
13573     if (!ArgumentExpr->isNullPointerConstant(Context,
13574                                              Expr::NPC_ValueDependentIsNotNull)) {
13575       Diag(ArgumentExpr->getExprLoc(),
13576            diag::warn_type_safety_null_pointer_required)
13577           << ArgumentKind->getName()
13578           << ArgumentExpr->getSourceRange()
13579           << TypeTagExpr->getSourceRange();
13580     }
13581     return;
13582   }
13583 
13584   QualType RequiredType = TypeInfo.Type;
13585   if (IsPointerAttr)
13586     RequiredType = Context.getPointerType(RequiredType);
13587 
13588   bool mismatch = false;
13589   if (!TypeInfo.LayoutCompatible) {
13590     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13591 
13592     // C++11 [basic.fundamental] p1:
13593     // Plain char, signed char, and unsigned char are three distinct types.
13594     //
13595     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13596     // char' depending on the current char signedness mode.
13597     if (mismatch)
13598       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13599                                            RequiredType->getPointeeType())) ||
13600           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13601         mismatch = false;
13602   } else
13603     if (IsPointerAttr)
13604       mismatch = !isLayoutCompatible(Context,
13605                                      ArgumentType->getPointeeType(),
13606                                      RequiredType->getPointeeType());
13607     else
13608       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13609 
13610   if (mismatch)
13611     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13612         << ArgumentType << ArgumentKind
13613         << TypeInfo.LayoutCompatible << RequiredType
13614         << ArgumentExpr->getSourceRange()
13615         << TypeTagExpr->getSourceRange();
13616 }
13617 
13618 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13619                                          CharUnits Alignment) {
13620   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13621 }
13622 
13623 void Sema::DiagnoseMisalignedMembers() {
13624   for (MisalignedMember &m : MisalignedMembers) {
13625     const NamedDecl *ND = m.RD;
13626     if (ND->getName().empty()) {
13627       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13628         ND = TD;
13629     }
13630     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
13631         << m.MD << ND << m.E->getSourceRange();
13632   }
13633   MisalignedMembers.clear();
13634 }
13635 
13636 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13637   E = E->IgnoreParens();
13638   if (!T->isPointerType() && !T->isIntegerType())
13639     return;
13640   if (isa<UnaryOperator>(E) &&
13641       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13642     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13643     if (isa<MemberExpr>(Op)) {
13644       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13645                           MisalignedMember(Op));
13646       if (MA != MisalignedMembers.end() &&
13647           (T->isIntegerType() ||
13648            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13649                                    Context.getTypeAlignInChars(
13650                                        T->getPointeeType()) <= MA->Alignment))))
13651         MisalignedMembers.erase(MA);
13652     }
13653   }
13654 }
13655 
13656 void Sema::RefersToMemberWithReducedAlignment(
13657     Expr *E,
13658     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13659         Action) {
13660   const auto *ME = dyn_cast<MemberExpr>(E);
13661   if (!ME)
13662     return;
13663 
13664   // No need to check expressions with an __unaligned-qualified type.
13665   if (E->getType().getQualifiers().hasUnaligned())
13666     return;
13667 
13668   // For a chain of MemberExpr like "a.b.c.d" this list
13669   // will keep FieldDecl's like [d, c, b].
13670   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13671   const MemberExpr *TopME = nullptr;
13672   bool AnyIsPacked = false;
13673   do {
13674     QualType BaseType = ME->getBase()->getType();
13675     if (ME->isArrow())
13676       BaseType = BaseType->getPointeeType();
13677     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13678     if (RD->isInvalidDecl())
13679       return;
13680 
13681     ValueDecl *MD = ME->getMemberDecl();
13682     auto *FD = dyn_cast<FieldDecl>(MD);
13683     // We do not care about non-data members.
13684     if (!FD || FD->isInvalidDecl())
13685       return;
13686 
13687     AnyIsPacked =
13688         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13689     ReverseMemberChain.push_back(FD);
13690 
13691     TopME = ME;
13692     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13693   } while (ME);
13694   assert(TopME && "We did not compute a topmost MemberExpr!");
13695 
13696   // Not the scope of this diagnostic.
13697   if (!AnyIsPacked)
13698     return;
13699 
13700   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13701   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13702   // TODO: The innermost base of the member expression may be too complicated.
13703   // For now, just disregard these cases. This is left for future
13704   // improvement.
13705   if (!DRE && !isa<CXXThisExpr>(TopBase))
13706       return;
13707 
13708   // Alignment expected by the whole expression.
13709   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13710 
13711   // No need to do anything else with this case.
13712   if (ExpectedAlignment.isOne())
13713     return;
13714 
13715   // Synthesize offset of the whole access.
13716   CharUnits Offset;
13717   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13718        I++) {
13719     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13720   }
13721 
13722   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13723   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13724       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13725 
13726   // The base expression of the innermost MemberExpr may give
13727   // stronger guarantees than the class containing the member.
13728   if (DRE && !TopME->isArrow()) {
13729     const ValueDecl *VD = DRE->getDecl();
13730     if (!VD->getType()->isReferenceType())
13731       CompleteObjectAlignment =
13732           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13733   }
13734 
13735   // Check if the synthesized offset fulfills the alignment.
13736   if (Offset % ExpectedAlignment != 0 ||
13737       // It may fulfill the offset it but the effective alignment may still be
13738       // lower than the expected expression alignment.
13739       CompleteObjectAlignment < ExpectedAlignment) {
13740     // If this happens, we want to determine a sensible culprit of this.
13741     // Intuitively, watching the chain of member expressions from right to
13742     // left, we start with the required alignment (as required by the field
13743     // type) but some packed attribute in that chain has reduced the alignment.
13744     // It may happen that another packed structure increases it again. But if
13745     // we are here such increase has not been enough. So pointing the first
13746     // FieldDecl that either is packed or else its RecordDecl is,
13747     // seems reasonable.
13748     FieldDecl *FD = nullptr;
13749     CharUnits Alignment;
13750     for (FieldDecl *FDI : ReverseMemberChain) {
13751       if (FDI->hasAttr<PackedAttr>() ||
13752           FDI->getParent()->hasAttr<PackedAttr>()) {
13753         FD = FDI;
13754         Alignment = std::min(
13755             Context.getTypeAlignInChars(FD->getType()),
13756             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13757         break;
13758       }
13759     }
13760     assert(FD && "We did not find a packed FieldDecl!");
13761     Action(E, FD->getParent(), FD, Alignment);
13762   }
13763 }
13764 
13765 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13766   using namespace std::placeholders;
13767 
13768   RefersToMemberWithReducedAlignment(
13769       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13770                      _2, _3, _4));
13771 }
13772