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/FormatString.h"
31 #include "clang/AST/NSAPI.h"
32 #include "clang/AST/NonTrivialTypeVisitor.h"
33 #include "clang/AST/OperationKinds.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.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   Expr::EvalResult SizeResult, DstSizeResult;
251 
252   // find out if both sizes are known at compile time
253   if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) ||
254       !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context))
255     return;
256 
257   llvm::APSInt Size = SizeResult.Val.getInt();
258   llvm::APSInt DstSize = DstSizeResult.Val.getInt();
259 
260   if (Size.ule(DstSize))
261     return;
262 
263   // Confirmed overflow, so generate the diagnostic.
264   StringRef FunctionName = FDecl->getName();
265   SourceLocation SL = TheCall->getBeginLoc();
266   SourceManager &SM = S.getSourceManager();
267   // If we're in an expansion of a macro whose name corresponds to this builtin,
268   // use the simple macro name and location.
269   if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
270                             LikelyMacroName) {
271     FunctionName = LikelyMacroName;
272     SL = SM.getImmediateMacroCallerLoc(SL);
273   }
274 
275   S.Diag(SL, diag::warn_memcpy_chk_overflow)
276       << FunctionName << DstSize.toString(/*Radix=*/10)
277       << Size.toString(/*Radix=*/10);
278 }
279 
280 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
281   if (checkArgCount(S, BuiltinCall, 2))
282     return true;
283 
284   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
285   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
286   Expr *Call = BuiltinCall->getArg(0);
287   Expr *Chain = BuiltinCall->getArg(1);
288 
289   if (Call->getStmtClass() != Stmt::CallExprClass) {
290     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
291         << Call->getSourceRange();
292     return true;
293   }
294 
295   auto CE = cast<CallExpr>(Call);
296   if (CE->getCallee()->getType()->isBlockPointerType()) {
297     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
298         << Call->getSourceRange();
299     return true;
300   }
301 
302   const Decl *TargetDecl = CE->getCalleeDecl();
303   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
304     if (FD->getBuiltinID()) {
305       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
306           << Call->getSourceRange();
307       return true;
308     }
309 
310   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
311     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
312         << Call->getSourceRange();
313     return true;
314   }
315 
316   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
317   if (ChainResult.isInvalid())
318     return true;
319   if (!ChainResult.get()->getType()->isPointerType()) {
320     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
321         << Chain->getSourceRange();
322     return true;
323   }
324 
325   QualType ReturnTy = CE->getCallReturnType(S.Context);
326   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
327   QualType BuiltinTy = S.Context.getFunctionType(
328       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
329   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
330 
331   Builtin =
332       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
333 
334   BuiltinCall->setType(CE->getType());
335   BuiltinCall->setValueKind(CE->getValueKind());
336   BuiltinCall->setObjectKind(CE->getObjectKind());
337   BuiltinCall->setCallee(Builtin);
338   BuiltinCall->setArg(1, ChainResult.get());
339 
340   return false;
341 }
342 
343 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
344                                      Scope::ScopeFlags NeededScopeFlags,
345                                      unsigned DiagID) {
346   // Scopes aren't available during instantiation. Fortunately, builtin
347   // functions cannot be template args so they cannot be formed through template
348   // instantiation. Therefore checking once during the parse is sufficient.
349   if (SemaRef.inTemplateInstantiation())
350     return false;
351 
352   Scope *S = SemaRef.getCurScope();
353   while (S && !S->isSEHExceptScope())
354     S = S->getParent();
355   if (!S || !(S->getFlags() & NeededScopeFlags)) {
356     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
357     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
358         << DRE->getDecl()->getIdentifier();
359     return true;
360   }
361 
362   return false;
363 }
364 
365 static inline bool isBlockPointer(Expr *Arg) {
366   return Arg->getType()->isBlockPointerType();
367 }
368 
369 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
370 /// void*, which is a requirement of device side enqueue.
371 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
372   const BlockPointerType *BPT =
373       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
374   ArrayRef<QualType> Params =
375       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
376   unsigned ArgCounter = 0;
377   bool IllegalParams = false;
378   // Iterate through the block parameters until either one is found that is not
379   // a local void*, or the block is valid.
380   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
381        I != E; ++I, ++ArgCounter) {
382     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
383         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
384             LangAS::opencl_local) {
385       // Get the location of the error. If a block literal has been passed
386       // (BlockExpr) then we can point straight to the offending argument,
387       // else we just point to the variable reference.
388       SourceLocation ErrorLoc;
389       if (isa<BlockExpr>(BlockArg)) {
390         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
391         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
392       } else if (isa<DeclRefExpr>(BlockArg)) {
393         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
394       }
395       S.Diag(ErrorLoc,
396              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
397       IllegalParams = true;
398     }
399   }
400 
401   return IllegalParams;
402 }
403 
404 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
405   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
406     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
407         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
408     return true;
409   }
410   return false;
411 }
412 
413 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
414   if (checkArgCount(S, TheCall, 2))
415     return true;
416 
417   if (checkOpenCLSubgroupExt(S, TheCall))
418     return true;
419 
420   // First argument is an ndrange_t type.
421   Expr *NDRangeArg = TheCall->getArg(0);
422   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
423     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
424         << TheCall->getDirectCallee() << "'ndrange_t'";
425     return true;
426   }
427 
428   Expr *BlockArg = TheCall->getArg(1);
429   if (!isBlockPointer(BlockArg)) {
430     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
431         << TheCall->getDirectCallee() << "block";
432     return true;
433   }
434   return checkOpenCLBlockArgs(S, BlockArg);
435 }
436 
437 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
438 /// get_kernel_work_group_size
439 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
440 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
441   if (checkArgCount(S, TheCall, 1))
442     return true;
443 
444   Expr *BlockArg = TheCall->getArg(0);
445   if (!isBlockPointer(BlockArg)) {
446     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
447         << TheCall->getDirectCallee() << "block";
448     return true;
449   }
450   return checkOpenCLBlockArgs(S, BlockArg);
451 }
452 
453 /// Diagnose integer type and any valid implicit conversion to it.
454 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
455                                       const QualType &IntType);
456 
457 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
458                                             unsigned Start, unsigned End) {
459   bool IllegalParams = false;
460   for (unsigned I = Start; I <= End; ++I)
461     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
462                                               S.Context.getSizeType());
463   return IllegalParams;
464 }
465 
466 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
467 /// 'local void*' parameter of passed block.
468 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
469                                            Expr *BlockArg,
470                                            unsigned NumNonVarArgs) {
471   const BlockPointerType *BPT =
472       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
473   unsigned NumBlockParams =
474       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
475   unsigned TotalNumArgs = TheCall->getNumArgs();
476 
477   // For each argument passed to the block, a corresponding uint needs to
478   // be passed to describe the size of the local memory.
479   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
480     S.Diag(TheCall->getBeginLoc(),
481            diag::err_opencl_enqueue_kernel_local_size_args);
482     return true;
483   }
484 
485   // Check that the sizes of the local memory are specified by integers.
486   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
487                                          TotalNumArgs - 1);
488 }
489 
490 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
491 /// overload formats specified in Table 6.13.17.1.
492 /// int enqueue_kernel(queue_t queue,
493 ///                    kernel_enqueue_flags_t flags,
494 ///                    const ndrange_t ndrange,
495 ///                    void (^block)(void))
496 /// int enqueue_kernel(queue_t queue,
497 ///                    kernel_enqueue_flags_t flags,
498 ///                    const ndrange_t ndrange,
499 ///                    uint num_events_in_wait_list,
500 ///                    clk_event_t *event_wait_list,
501 ///                    clk_event_t *event_ret,
502 ///                    void (^block)(void))
503 /// int enqueue_kernel(queue_t queue,
504 ///                    kernel_enqueue_flags_t flags,
505 ///                    const ndrange_t ndrange,
506 ///                    void (^block)(local void*, ...),
507 ///                    uint size0, ...)
508 /// int enqueue_kernel(queue_t queue,
509 ///                    kernel_enqueue_flags_t flags,
510 ///                    const ndrange_t ndrange,
511 ///                    uint num_events_in_wait_list,
512 ///                    clk_event_t *event_wait_list,
513 ///                    clk_event_t *event_ret,
514 ///                    void (^block)(local void*, ...),
515 ///                    uint size0, ...)
516 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
517   unsigned NumArgs = TheCall->getNumArgs();
518 
519   if (NumArgs < 4) {
520     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
521     return true;
522   }
523 
524   Expr *Arg0 = TheCall->getArg(0);
525   Expr *Arg1 = TheCall->getArg(1);
526   Expr *Arg2 = TheCall->getArg(2);
527   Expr *Arg3 = TheCall->getArg(3);
528 
529   // First argument always needs to be a queue_t type.
530   if (!Arg0->getType()->isQueueT()) {
531     S.Diag(TheCall->getArg(0)->getBeginLoc(),
532            diag::err_opencl_builtin_expected_type)
533         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
534     return true;
535   }
536 
537   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
538   if (!Arg1->getType()->isIntegerType()) {
539     S.Diag(TheCall->getArg(1)->getBeginLoc(),
540            diag::err_opencl_builtin_expected_type)
541         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
542     return true;
543   }
544 
545   // Third argument is always an ndrange_t type.
546   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
547     S.Diag(TheCall->getArg(2)->getBeginLoc(),
548            diag::err_opencl_builtin_expected_type)
549         << TheCall->getDirectCallee() << "'ndrange_t'";
550     return true;
551   }
552 
553   // With four arguments, there is only one form that the function could be
554   // called in: no events and no variable arguments.
555   if (NumArgs == 4) {
556     // check that the last argument is the right block type.
557     if (!isBlockPointer(Arg3)) {
558       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
559           << TheCall->getDirectCallee() << "block";
560       return true;
561     }
562     // we have a block type, check the prototype
563     const BlockPointerType *BPT =
564         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
565     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
566       S.Diag(Arg3->getBeginLoc(),
567              diag::err_opencl_enqueue_kernel_blocks_no_args);
568       return true;
569     }
570     return false;
571   }
572   // we can have block + varargs.
573   if (isBlockPointer(Arg3))
574     return (checkOpenCLBlockArgs(S, Arg3) ||
575             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
576   // last two cases with either exactly 7 args or 7 args and varargs.
577   if (NumArgs >= 7) {
578     // check common block argument.
579     Expr *Arg6 = TheCall->getArg(6);
580     if (!isBlockPointer(Arg6)) {
581       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
582           << TheCall->getDirectCallee() << "block";
583       return true;
584     }
585     if (checkOpenCLBlockArgs(S, Arg6))
586       return true;
587 
588     // Forth argument has to be any integer type.
589     if (!Arg3->getType()->isIntegerType()) {
590       S.Diag(TheCall->getArg(3)->getBeginLoc(),
591              diag::err_opencl_builtin_expected_type)
592           << TheCall->getDirectCallee() << "integer";
593       return true;
594     }
595     // check remaining common arguments.
596     Expr *Arg4 = TheCall->getArg(4);
597     Expr *Arg5 = TheCall->getArg(5);
598 
599     // Fifth argument is always passed as a pointer to clk_event_t.
600     if (!Arg4->isNullPointerConstant(S.Context,
601                                      Expr::NPC_ValueDependentIsNotNull) &&
602         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
603       S.Diag(TheCall->getArg(4)->getBeginLoc(),
604              diag::err_opencl_builtin_expected_type)
605           << TheCall->getDirectCallee()
606           << S.Context.getPointerType(S.Context.OCLClkEventTy);
607       return true;
608     }
609 
610     // Sixth argument is always passed as a pointer to clk_event_t.
611     if (!Arg5->isNullPointerConstant(S.Context,
612                                      Expr::NPC_ValueDependentIsNotNull) &&
613         !(Arg5->getType()->isPointerType() &&
614           Arg5->getType()->getPointeeType()->isClkEventT())) {
615       S.Diag(TheCall->getArg(5)->getBeginLoc(),
616              diag::err_opencl_builtin_expected_type)
617           << TheCall->getDirectCallee()
618           << S.Context.getPointerType(S.Context.OCLClkEventTy);
619       return true;
620     }
621 
622     if (NumArgs == 7)
623       return false;
624 
625     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
626   }
627 
628   // None of the specific case has been detected, give generic error
629   S.Diag(TheCall->getBeginLoc(),
630          diag::err_opencl_enqueue_kernel_incorrect_args);
631   return true;
632 }
633 
634 /// Returns OpenCL access qual.
635 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
636     return D->getAttr<OpenCLAccessAttr>();
637 }
638 
639 /// Returns true if pipe element type is different from the pointer.
640 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
641   const Expr *Arg0 = Call->getArg(0);
642   // First argument type should always be pipe.
643   if (!Arg0->getType()->isPipeType()) {
644     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
645         << Call->getDirectCallee() << Arg0->getSourceRange();
646     return true;
647   }
648   OpenCLAccessAttr *AccessQual =
649       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
650   // Validates the access qualifier is compatible with the call.
651   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
652   // read_only and write_only, and assumed to be read_only if no qualifier is
653   // specified.
654   switch (Call->getDirectCallee()->getBuiltinID()) {
655   case Builtin::BIread_pipe:
656   case Builtin::BIreserve_read_pipe:
657   case Builtin::BIcommit_read_pipe:
658   case Builtin::BIwork_group_reserve_read_pipe:
659   case Builtin::BIsub_group_reserve_read_pipe:
660   case Builtin::BIwork_group_commit_read_pipe:
661   case Builtin::BIsub_group_commit_read_pipe:
662     if (!(!AccessQual || AccessQual->isReadOnly())) {
663       S.Diag(Arg0->getBeginLoc(),
664              diag::err_opencl_builtin_pipe_invalid_access_modifier)
665           << "read_only" << Arg0->getSourceRange();
666       return true;
667     }
668     break;
669   case Builtin::BIwrite_pipe:
670   case Builtin::BIreserve_write_pipe:
671   case Builtin::BIcommit_write_pipe:
672   case Builtin::BIwork_group_reserve_write_pipe:
673   case Builtin::BIsub_group_reserve_write_pipe:
674   case Builtin::BIwork_group_commit_write_pipe:
675   case Builtin::BIsub_group_commit_write_pipe:
676     if (!(AccessQual && AccessQual->isWriteOnly())) {
677       S.Diag(Arg0->getBeginLoc(),
678              diag::err_opencl_builtin_pipe_invalid_access_modifier)
679           << "write_only" << Arg0->getSourceRange();
680       return true;
681     }
682     break;
683   default:
684     break;
685   }
686   return false;
687 }
688 
689 /// Returns true if pipe element type is different from the pointer.
690 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
691   const Expr *Arg0 = Call->getArg(0);
692   const Expr *ArgIdx = Call->getArg(Idx);
693   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
694   const QualType EltTy = PipeTy->getElementType();
695   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
696   // The Idx argument should be a pointer and the type of the pointer and
697   // the type of pipe element should also be the same.
698   if (!ArgTy ||
699       !S.Context.hasSameType(
700           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
701     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
702         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
703         << ArgIdx->getType() << ArgIdx->getSourceRange();
704     return true;
705   }
706   return false;
707 }
708 
709 // Performs semantic analysis for the read/write_pipe call.
710 // \param S Reference to the semantic analyzer.
711 // \param Call A pointer to the builtin call.
712 // \return True if a semantic error has been found, false otherwise.
713 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
714   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
715   // functions have two forms.
716   switch (Call->getNumArgs()) {
717   case 2:
718     if (checkOpenCLPipeArg(S, Call))
719       return true;
720     // The call with 2 arguments should be
721     // read/write_pipe(pipe T, T*).
722     // Check packet type T.
723     if (checkOpenCLPipePacketType(S, Call, 1))
724       return true;
725     break;
726 
727   case 4: {
728     if (checkOpenCLPipeArg(S, Call))
729       return true;
730     // The call with 4 arguments should be
731     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
732     // Check reserve_id_t.
733     if (!Call->getArg(1)->getType()->isReserveIDT()) {
734       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
735           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
736           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
737       return true;
738     }
739 
740     // Check the index.
741     const Expr *Arg2 = Call->getArg(2);
742     if (!Arg2->getType()->isIntegerType() &&
743         !Arg2->getType()->isUnsignedIntegerType()) {
744       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
745           << Call->getDirectCallee() << S.Context.UnsignedIntTy
746           << Arg2->getType() << Arg2->getSourceRange();
747       return true;
748     }
749 
750     // Check packet type T.
751     if (checkOpenCLPipePacketType(S, Call, 3))
752       return true;
753   } break;
754   default:
755     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
756         << Call->getDirectCallee() << Call->getSourceRange();
757     return true;
758   }
759 
760   return false;
761 }
762 
763 // Performs a semantic analysis on the {work_group_/sub_group_
764 //        /_}reserve_{read/write}_pipe
765 // \param S Reference to the semantic analyzer.
766 // \param Call The call to the builtin function to be analyzed.
767 // \return True if a semantic error was found, false otherwise.
768 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
769   if (checkArgCount(S, Call, 2))
770     return true;
771 
772   if (checkOpenCLPipeArg(S, Call))
773     return true;
774 
775   // Check the reserve size.
776   if (!Call->getArg(1)->getType()->isIntegerType() &&
777       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
778     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
779         << Call->getDirectCallee() << S.Context.UnsignedIntTy
780         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
781     return true;
782   }
783 
784   // Since return type of reserve_read/write_pipe built-in function is
785   // reserve_id_t, which is not defined in the builtin def file , we used int
786   // as return type and need to override the return type of these functions.
787   Call->setType(S.Context.OCLReserveIDTy);
788 
789   return false;
790 }
791 
792 // Performs a semantic analysis on {work_group_/sub_group_
793 //        /_}commit_{read/write}_pipe
794 // \param S Reference to the semantic analyzer.
795 // \param Call The call to the builtin function to be analyzed.
796 // \return True if a semantic error was found, false otherwise.
797 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
798   if (checkArgCount(S, Call, 2))
799     return true;
800 
801   if (checkOpenCLPipeArg(S, Call))
802     return true;
803 
804   // Check reserve_id_t.
805   if (!Call->getArg(1)->getType()->isReserveIDT()) {
806     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
807         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
808         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 // Performs a semantic analysis on the call to built-in Pipe
816 //        Query Functions.
817 // \param S Reference to the semantic analyzer.
818 // \param Call The call to the builtin function to be analyzed.
819 // \return True if a semantic error was found, false otherwise.
820 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
821   if (checkArgCount(S, Call, 1))
822     return true;
823 
824   if (!Call->getArg(0)->getType()->isPipeType()) {
825     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
826         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
827     return true;
828   }
829 
830   return false;
831 }
832 
833 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
834 // Performs semantic analysis for the to_global/local/private call.
835 // \param S Reference to the semantic analyzer.
836 // \param BuiltinID ID of the builtin function.
837 // \param Call A pointer to the builtin call.
838 // \return True if a semantic error has been found, false otherwise.
839 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
840                                     CallExpr *Call) {
841   if (Call->getNumArgs() != 1) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
843         << Call->getDirectCallee() << Call->getSourceRange();
844     return true;
845   }
846 
847   auto RT = Call->getArg(0)->getType();
848   if (!RT->isPointerType() || RT->getPointeeType()
849       .getAddressSpace() == LangAS::opencl_constant) {
850     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
851         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
852     return true;
853   }
854 
855   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
856     S.Diag(Call->getArg(0)->getBeginLoc(),
857            diag::warn_opencl_generic_address_space_arg)
858         << Call->getDirectCallee()->getNameInfo().getAsString()
859         << Call->getArg(0)->getSourceRange();
860   }
861 
862   RT = RT->getPointeeType();
863   auto Qual = RT.getQualifiers();
864   switch (BuiltinID) {
865   case Builtin::BIto_global:
866     Qual.setAddressSpace(LangAS::opencl_global);
867     break;
868   case Builtin::BIto_local:
869     Qual.setAddressSpace(LangAS::opencl_local);
870     break;
871   case Builtin::BIto_private:
872     Qual.setAddressSpace(LangAS::opencl_private);
873     break;
874   default:
875     llvm_unreachable("Invalid builtin function");
876   }
877   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
878       RT.getUnqualifiedType(), Qual)));
879 
880   return false;
881 }
882 
883 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
884   if (checkArgCount(S, TheCall, 1))
885     return ExprError();
886 
887   // Compute __builtin_launder's parameter type from the argument.
888   // The parameter type is:
889   //  * The type of the argument if it's not an array or function type,
890   //  Otherwise,
891   //  * The decayed argument type.
892   QualType ParamTy = [&]() {
893     QualType ArgTy = TheCall->getArg(0)->getType();
894     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
895       return S.Context.getPointerType(Ty->getElementType());
896     if (ArgTy->isFunctionType()) {
897       return S.Context.getPointerType(ArgTy);
898     }
899     return ArgTy;
900   }();
901 
902   TheCall->setType(ParamTy);
903 
904   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
905     if (!ParamTy->isPointerType())
906       return 0;
907     if (ParamTy->isFunctionPointerType())
908       return 1;
909     if (ParamTy->isVoidPointerType())
910       return 2;
911     return llvm::Optional<unsigned>{};
912   }();
913   if (DiagSelect.hasValue()) {
914     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
915         << DiagSelect.getValue() << TheCall->getSourceRange();
916     return ExprError();
917   }
918 
919   // We either have an incomplete class type, or we have a class template
920   // whose instantiation has not been forced. Example:
921   //
922   //   template <class T> struct Foo { T value; };
923   //   Foo<int> *p = nullptr;
924   //   auto *d = __builtin_launder(p);
925   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
926                             diag::err_incomplete_type))
927     return ExprError();
928 
929   assert(ParamTy->getPointeeType()->isObjectType() &&
930          "Unhandled non-object pointer case");
931 
932   InitializedEntity Entity =
933       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
934   ExprResult Arg =
935       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
936   if (Arg.isInvalid())
937     return ExprError();
938   TheCall->setArg(0, Arg.get());
939 
940   return TheCall;
941 }
942 
943 // Emit an error and return true if the current architecture is not in the list
944 // of supported architectures.
945 static bool
946 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
947                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
948   llvm::Triple::ArchType CurArch =
949       S.getASTContext().getTargetInfo().getTriple().getArch();
950   if (llvm::is_contained(SupportedArchs, CurArch))
951     return false;
952   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
953       << TheCall->getSourceRange();
954   return true;
955 }
956 
957 ExprResult
958 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
959                                CallExpr *TheCall) {
960   ExprResult TheCallResult(TheCall);
961 
962   // Find out if any arguments are required to be integer constant expressions.
963   unsigned ICEArguments = 0;
964   ASTContext::GetBuiltinTypeError Error;
965   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
966   if (Error != ASTContext::GE_None)
967     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
968 
969   // If any arguments are required to be ICE's, check and diagnose.
970   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
971     // Skip arguments not required to be ICE's.
972     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
973 
974     llvm::APSInt Result;
975     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
976       return true;
977     ICEArguments &= ~(1 << ArgNo);
978   }
979 
980   switch (BuiltinID) {
981   case Builtin::BI__builtin___CFStringMakeConstantString:
982     assert(TheCall->getNumArgs() == 1 &&
983            "Wrong # arguments to builtin CFStringMakeConstantString");
984     if (CheckObjCString(TheCall->getArg(0)))
985       return ExprError();
986     break;
987   case Builtin::BI__builtin_ms_va_start:
988   case Builtin::BI__builtin_stdarg_start:
989   case Builtin::BI__builtin_va_start:
990     if (SemaBuiltinVAStart(BuiltinID, TheCall))
991       return ExprError();
992     break;
993   case Builtin::BI__va_start: {
994     switch (Context.getTargetInfo().getTriple().getArch()) {
995     case llvm::Triple::aarch64:
996     case llvm::Triple::arm:
997     case llvm::Triple::thumb:
998       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
999         return ExprError();
1000       break;
1001     default:
1002       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1003         return ExprError();
1004       break;
1005     }
1006     break;
1007   }
1008 
1009   // The acquire, release, and no fence variants are ARM and AArch64 only.
1010   case Builtin::BI_interlockedbittestandset_acq:
1011   case Builtin::BI_interlockedbittestandset_rel:
1012   case Builtin::BI_interlockedbittestandset_nf:
1013   case Builtin::BI_interlockedbittestandreset_acq:
1014   case Builtin::BI_interlockedbittestandreset_rel:
1015   case Builtin::BI_interlockedbittestandreset_nf:
1016     if (CheckBuiltinTargetSupport(
1017             *this, BuiltinID, TheCall,
1018             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1019       return ExprError();
1020     break;
1021 
1022   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1023   case Builtin::BI_bittest64:
1024   case Builtin::BI_bittestandcomplement64:
1025   case Builtin::BI_bittestandreset64:
1026   case Builtin::BI_bittestandset64:
1027   case Builtin::BI_interlockedbittestandreset64:
1028   case Builtin::BI_interlockedbittestandset64:
1029     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1030                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1031                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1032       return ExprError();
1033     break;
1034 
1035   case Builtin::BI__builtin_isgreater:
1036   case Builtin::BI__builtin_isgreaterequal:
1037   case Builtin::BI__builtin_isless:
1038   case Builtin::BI__builtin_islessequal:
1039   case Builtin::BI__builtin_islessgreater:
1040   case Builtin::BI__builtin_isunordered:
1041     if (SemaBuiltinUnorderedCompare(TheCall))
1042       return ExprError();
1043     break;
1044   case Builtin::BI__builtin_fpclassify:
1045     if (SemaBuiltinFPClassification(TheCall, 6))
1046       return ExprError();
1047     break;
1048   case Builtin::BI__builtin_isfinite:
1049   case Builtin::BI__builtin_isinf:
1050   case Builtin::BI__builtin_isinf_sign:
1051   case Builtin::BI__builtin_isnan:
1052   case Builtin::BI__builtin_isnormal:
1053   case Builtin::BI__builtin_signbit:
1054   case Builtin::BI__builtin_signbitf:
1055   case Builtin::BI__builtin_signbitl:
1056     if (SemaBuiltinFPClassification(TheCall, 1))
1057       return ExprError();
1058     break;
1059   case Builtin::BI__builtin_shufflevector:
1060     return SemaBuiltinShuffleVector(TheCall);
1061     // TheCall will be freed by the smart pointer here, but that's fine, since
1062     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1063   case Builtin::BI__builtin_prefetch:
1064     if (SemaBuiltinPrefetch(TheCall))
1065       return ExprError();
1066     break;
1067   case Builtin::BI__builtin_alloca_with_align:
1068     if (SemaBuiltinAllocaWithAlign(TheCall))
1069       return ExprError();
1070     break;
1071   case Builtin::BI__assume:
1072   case Builtin::BI__builtin_assume:
1073     if (SemaBuiltinAssume(TheCall))
1074       return ExprError();
1075     break;
1076   case Builtin::BI__builtin_assume_aligned:
1077     if (SemaBuiltinAssumeAligned(TheCall))
1078       return ExprError();
1079     break;
1080   case Builtin::BI__builtin_object_size:
1081     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1082       return ExprError();
1083     break;
1084   case Builtin::BI__builtin_longjmp:
1085     if (SemaBuiltinLongjmp(TheCall))
1086       return ExprError();
1087     break;
1088   case Builtin::BI__builtin_setjmp:
1089     if (SemaBuiltinSetjmp(TheCall))
1090       return ExprError();
1091     break;
1092   case Builtin::BI_setjmp:
1093   case Builtin::BI_setjmpex:
1094     if (checkArgCount(*this, TheCall, 1))
1095       return true;
1096     break;
1097   case Builtin::BI__builtin_classify_type:
1098     if (checkArgCount(*this, TheCall, 1)) return true;
1099     TheCall->setType(Context.IntTy);
1100     break;
1101   case Builtin::BI__builtin_constant_p:
1102     if (checkArgCount(*this, TheCall, 1)) return true;
1103     TheCall->setType(Context.IntTy);
1104     break;
1105   case Builtin::BI__builtin_launder:
1106     return SemaBuiltinLaunder(*this, TheCall);
1107   case Builtin::BI__sync_fetch_and_add:
1108   case Builtin::BI__sync_fetch_and_add_1:
1109   case Builtin::BI__sync_fetch_and_add_2:
1110   case Builtin::BI__sync_fetch_and_add_4:
1111   case Builtin::BI__sync_fetch_and_add_8:
1112   case Builtin::BI__sync_fetch_and_add_16:
1113   case Builtin::BI__sync_fetch_and_sub:
1114   case Builtin::BI__sync_fetch_and_sub_1:
1115   case Builtin::BI__sync_fetch_and_sub_2:
1116   case Builtin::BI__sync_fetch_and_sub_4:
1117   case Builtin::BI__sync_fetch_and_sub_8:
1118   case Builtin::BI__sync_fetch_and_sub_16:
1119   case Builtin::BI__sync_fetch_and_or:
1120   case Builtin::BI__sync_fetch_and_or_1:
1121   case Builtin::BI__sync_fetch_and_or_2:
1122   case Builtin::BI__sync_fetch_and_or_4:
1123   case Builtin::BI__sync_fetch_and_or_8:
1124   case Builtin::BI__sync_fetch_and_or_16:
1125   case Builtin::BI__sync_fetch_and_and:
1126   case Builtin::BI__sync_fetch_and_and_1:
1127   case Builtin::BI__sync_fetch_and_and_2:
1128   case Builtin::BI__sync_fetch_and_and_4:
1129   case Builtin::BI__sync_fetch_and_and_8:
1130   case Builtin::BI__sync_fetch_and_and_16:
1131   case Builtin::BI__sync_fetch_and_xor:
1132   case Builtin::BI__sync_fetch_and_xor_1:
1133   case Builtin::BI__sync_fetch_and_xor_2:
1134   case Builtin::BI__sync_fetch_and_xor_4:
1135   case Builtin::BI__sync_fetch_and_xor_8:
1136   case Builtin::BI__sync_fetch_and_xor_16:
1137   case Builtin::BI__sync_fetch_and_nand:
1138   case Builtin::BI__sync_fetch_and_nand_1:
1139   case Builtin::BI__sync_fetch_and_nand_2:
1140   case Builtin::BI__sync_fetch_and_nand_4:
1141   case Builtin::BI__sync_fetch_and_nand_8:
1142   case Builtin::BI__sync_fetch_and_nand_16:
1143   case Builtin::BI__sync_add_and_fetch:
1144   case Builtin::BI__sync_add_and_fetch_1:
1145   case Builtin::BI__sync_add_and_fetch_2:
1146   case Builtin::BI__sync_add_and_fetch_4:
1147   case Builtin::BI__sync_add_and_fetch_8:
1148   case Builtin::BI__sync_add_and_fetch_16:
1149   case Builtin::BI__sync_sub_and_fetch:
1150   case Builtin::BI__sync_sub_and_fetch_1:
1151   case Builtin::BI__sync_sub_and_fetch_2:
1152   case Builtin::BI__sync_sub_and_fetch_4:
1153   case Builtin::BI__sync_sub_and_fetch_8:
1154   case Builtin::BI__sync_sub_and_fetch_16:
1155   case Builtin::BI__sync_and_and_fetch:
1156   case Builtin::BI__sync_and_and_fetch_1:
1157   case Builtin::BI__sync_and_and_fetch_2:
1158   case Builtin::BI__sync_and_and_fetch_4:
1159   case Builtin::BI__sync_and_and_fetch_8:
1160   case Builtin::BI__sync_and_and_fetch_16:
1161   case Builtin::BI__sync_or_and_fetch:
1162   case Builtin::BI__sync_or_and_fetch_1:
1163   case Builtin::BI__sync_or_and_fetch_2:
1164   case Builtin::BI__sync_or_and_fetch_4:
1165   case Builtin::BI__sync_or_and_fetch_8:
1166   case Builtin::BI__sync_or_and_fetch_16:
1167   case Builtin::BI__sync_xor_and_fetch:
1168   case Builtin::BI__sync_xor_and_fetch_1:
1169   case Builtin::BI__sync_xor_and_fetch_2:
1170   case Builtin::BI__sync_xor_and_fetch_4:
1171   case Builtin::BI__sync_xor_and_fetch_8:
1172   case Builtin::BI__sync_xor_and_fetch_16:
1173   case Builtin::BI__sync_nand_and_fetch:
1174   case Builtin::BI__sync_nand_and_fetch_1:
1175   case Builtin::BI__sync_nand_and_fetch_2:
1176   case Builtin::BI__sync_nand_and_fetch_4:
1177   case Builtin::BI__sync_nand_and_fetch_8:
1178   case Builtin::BI__sync_nand_and_fetch_16:
1179   case Builtin::BI__sync_val_compare_and_swap:
1180   case Builtin::BI__sync_val_compare_and_swap_1:
1181   case Builtin::BI__sync_val_compare_and_swap_2:
1182   case Builtin::BI__sync_val_compare_and_swap_4:
1183   case Builtin::BI__sync_val_compare_and_swap_8:
1184   case Builtin::BI__sync_val_compare_and_swap_16:
1185   case Builtin::BI__sync_bool_compare_and_swap:
1186   case Builtin::BI__sync_bool_compare_and_swap_1:
1187   case Builtin::BI__sync_bool_compare_and_swap_2:
1188   case Builtin::BI__sync_bool_compare_and_swap_4:
1189   case Builtin::BI__sync_bool_compare_and_swap_8:
1190   case Builtin::BI__sync_bool_compare_and_swap_16:
1191   case Builtin::BI__sync_lock_test_and_set:
1192   case Builtin::BI__sync_lock_test_and_set_1:
1193   case Builtin::BI__sync_lock_test_and_set_2:
1194   case Builtin::BI__sync_lock_test_and_set_4:
1195   case Builtin::BI__sync_lock_test_and_set_8:
1196   case Builtin::BI__sync_lock_test_and_set_16:
1197   case Builtin::BI__sync_lock_release:
1198   case Builtin::BI__sync_lock_release_1:
1199   case Builtin::BI__sync_lock_release_2:
1200   case Builtin::BI__sync_lock_release_4:
1201   case Builtin::BI__sync_lock_release_8:
1202   case Builtin::BI__sync_lock_release_16:
1203   case Builtin::BI__sync_swap:
1204   case Builtin::BI__sync_swap_1:
1205   case Builtin::BI__sync_swap_2:
1206   case Builtin::BI__sync_swap_4:
1207   case Builtin::BI__sync_swap_8:
1208   case Builtin::BI__sync_swap_16:
1209     return SemaBuiltinAtomicOverloaded(TheCallResult);
1210   case Builtin::BI__sync_synchronize:
1211     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1212         << TheCall->getCallee()->getSourceRange();
1213     break;
1214   case Builtin::BI__builtin_nontemporal_load:
1215   case Builtin::BI__builtin_nontemporal_store:
1216     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1217 #define BUILTIN(ID, TYPE, ATTRS)
1218 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1219   case Builtin::BI##ID: \
1220     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1221 #include "clang/Basic/Builtins.def"
1222   case Builtin::BI__annotation:
1223     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1224       return ExprError();
1225     break;
1226   case Builtin::BI__builtin_annotation:
1227     if (SemaBuiltinAnnotation(*this, TheCall))
1228       return ExprError();
1229     break;
1230   case Builtin::BI__builtin_addressof:
1231     if (SemaBuiltinAddressof(*this, TheCall))
1232       return ExprError();
1233     break;
1234   case Builtin::BI__builtin_add_overflow:
1235   case Builtin::BI__builtin_sub_overflow:
1236   case Builtin::BI__builtin_mul_overflow:
1237     if (SemaBuiltinOverflow(*this, TheCall))
1238       return ExprError();
1239     break;
1240   case Builtin::BI__builtin_operator_new:
1241   case Builtin::BI__builtin_operator_delete: {
1242     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1243     ExprResult Res =
1244         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1245     if (Res.isInvalid())
1246       CorrectDelayedTyposInExpr(TheCallResult.get());
1247     return Res;
1248   }
1249   case Builtin::BI__builtin_dump_struct: {
1250     // We first want to ensure we are called with 2 arguments
1251     if (checkArgCount(*this, TheCall, 2))
1252       return ExprError();
1253     // Ensure that the first argument is of type 'struct XX *'
1254     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1255     const QualType PtrArgType = PtrArg->getType();
1256     if (!PtrArgType->isPointerType() ||
1257         !PtrArgType->getPointeeType()->isRecordType()) {
1258       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1259           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1260           << "structure pointer";
1261       return ExprError();
1262     }
1263 
1264     // Ensure that the second argument is of type 'FunctionType'
1265     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1266     const QualType FnPtrArgType = FnPtrArg->getType();
1267     if (!FnPtrArgType->isPointerType()) {
1268       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1269           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1270           << FnPtrArgType << "'int (*)(const char *, ...)'";
1271       return ExprError();
1272     }
1273 
1274     const auto *FuncType =
1275         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1276 
1277     if (!FuncType) {
1278       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1279           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1280           << FnPtrArgType << "'int (*)(const char *, ...)'";
1281       return ExprError();
1282     }
1283 
1284     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1285       if (!FT->getNumParams()) {
1286         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1287             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1288             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1289         return ExprError();
1290       }
1291       QualType PT = FT->getParamType(0);
1292       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1293           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1294           !PT->getPointeeType().isConstQualified()) {
1295         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1296             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1297             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1298         return ExprError();
1299       }
1300     }
1301 
1302     TheCall->setType(Context.IntTy);
1303     break;
1304   }
1305 
1306   // check secure string manipulation functions where overflows
1307   // are detectable at compile time
1308   case Builtin::BI__builtin___memcpy_chk:
1309     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
1310     break;
1311   case Builtin::BI__builtin___memmove_chk:
1312     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
1313     break;
1314   case Builtin::BI__builtin___memset_chk:
1315     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
1316     break;
1317   case Builtin::BI__builtin___strlcat_chk:
1318     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
1319     break;
1320   case Builtin::BI__builtin___strlcpy_chk:
1321     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
1322     break;
1323   case Builtin::BI__builtin___strncat_chk:
1324     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
1325     break;
1326   case Builtin::BI__builtin___strncpy_chk:
1327     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
1328     break;
1329   case Builtin::BI__builtin___stpncpy_chk:
1330     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
1331     break;
1332   case Builtin::BI__builtin___memccpy_chk:
1333     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
1334     break;
1335   case Builtin::BI__builtin___snprintf_chk:
1336     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
1337     break;
1338   case Builtin::BI__builtin___vsnprintf_chk:
1339     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
1340     break;
1341   case Builtin::BI__builtin_call_with_static_chain:
1342     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1343       return ExprError();
1344     break;
1345   case Builtin::BI__exception_code:
1346   case Builtin::BI_exception_code:
1347     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1348                                  diag::err_seh___except_block))
1349       return ExprError();
1350     break;
1351   case Builtin::BI__exception_info:
1352   case Builtin::BI_exception_info:
1353     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1354                                  diag::err_seh___except_filter))
1355       return ExprError();
1356     break;
1357   case Builtin::BI__GetExceptionInfo:
1358     if (checkArgCount(*this, TheCall, 1))
1359       return ExprError();
1360 
1361     if (CheckCXXThrowOperand(
1362             TheCall->getBeginLoc(),
1363             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1364             TheCall))
1365       return ExprError();
1366 
1367     TheCall->setType(Context.VoidPtrTy);
1368     break;
1369   // OpenCL v2.0, s6.13.16 - Pipe functions
1370   case Builtin::BIread_pipe:
1371   case Builtin::BIwrite_pipe:
1372     // Since those two functions are declared with var args, we need a semantic
1373     // check for the argument.
1374     if (SemaBuiltinRWPipe(*this, TheCall))
1375       return ExprError();
1376     break;
1377   case Builtin::BIreserve_read_pipe:
1378   case Builtin::BIreserve_write_pipe:
1379   case Builtin::BIwork_group_reserve_read_pipe:
1380   case Builtin::BIwork_group_reserve_write_pipe:
1381     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1382       return ExprError();
1383     break;
1384   case Builtin::BIsub_group_reserve_read_pipe:
1385   case Builtin::BIsub_group_reserve_write_pipe:
1386     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1387         SemaBuiltinReserveRWPipe(*this, TheCall))
1388       return ExprError();
1389     break;
1390   case Builtin::BIcommit_read_pipe:
1391   case Builtin::BIcommit_write_pipe:
1392   case Builtin::BIwork_group_commit_read_pipe:
1393   case Builtin::BIwork_group_commit_write_pipe:
1394     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1395       return ExprError();
1396     break;
1397   case Builtin::BIsub_group_commit_read_pipe:
1398   case Builtin::BIsub_group_commit_write_pipe:
1399     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1400         SemaBuiltinCommitRWPipe(*this, TheCall))
1401       return ExprError();
1402     break;
1403   case Builtin::BIget_pipe_num_packets:
1404   case Builtin::BIget_pipe_max_packets:
1405     if (SemaBuiltinPipePackets(*this, TheCall))
1406       return ExprError();
1407     break;
1408   case Builtin::BIto_global:
1409   case Builtin::BIto_local:
1410   case Builtin::BIto_private:
1411     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1412       return ExprError();
1413     break;
1414   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1415   case Builtin::BIenqueue_kernel:
1416     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1417       return ExprError();
1418     break;
1419   case Builtin::BIget_kernel_work_group_size:
1420   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1421     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1422       return ExprError();
1423     break;
1424   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1425   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1426     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1427       return ExprError();
1428     break;
1429   case Builtin::BI__builtin_os_log_format:
1430   case Builtin::BI__builtin_os_log_format_buffer_size:
1431     if (SemaBuiltinOSLogFormat(TheCall))
1432       return ExprError();
1433     break;
1434   }
1435 
1436   // Since the target specific builtins for each arch overlap, only check those
1437   // of the arch we are compiling for.
1438   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1439     switch (Context.getTargetInfo().getTriple().getArch()) {
1440       case llvm::Triple::arm:
1441       case llvm::Triple::armeb:
1442       case llvm::Triple::thumb:
1443       case llvm::Triple::thumbeb:
1444         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1445           return ExprError();
1446         break;
1447       case llvm::Triple::aarch64:
1448       case llvm::Triple::aarch64_be:
1449         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1450           return ExprError();
1451         break;
1452       case llvm::Triple::hexagon:
1453         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1454           return ExprError();
1455         break;
1456       case llvm::Triple::mips:
1457       case llvm::Triple::mipsel:
1458       case llvm::Triple::mips64:
1459       case llvm::Triple::mips64el:
1460         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1461           return ExprError();
1462         break;
1463       case llvm::Triple::systemz:
1464         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1465           return ExprError();
1466         break;
1467       case llvm::Triple::x86:
1468       case llvm::Triple::x86_64:
1469         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1470           return ExprError();
1471         break;
1472       case llvm::Triple::ppc:
1473       case llvm::Triple::ppc64:
1474       case llvm::Triple::ppc64le:
1475         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1476           return ExprError();
1477         break;
1478       default:
1479         break;
1480     }
1481   }
1482 
1483   return TheCallResult;
1484 }
1485 
1486 // Get the valid immediate range for the specified NEON type code.
1487 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1488   NeonTypeFlags Type(t);
1489   int IsQuad = ForceQuad ? true : Type.isQuad();
1490   switch (Type.getEltType()) {
1491   case NeonTypeFlags::Int8:
1492   case NeonTypeFlags::Poly8:
1493     return shift ? 7 : (8 << IsQuad) - 1;
1494   case NeonTypeFlags::Int16:
1495   case NeonTypeFlags::Poly16:
1496     return shift ? 15 : (4 << IsQuad) - 1;
1497   case NeonTypeFlags::Int32:
1498     return shift ? 31 : (2 << IsQuad) - 1;
1499   case NeonTypeFlags::Int64:
1500   case NeonTypeFlags::Poly64:
1501     return shift ? 63 : (1 << IsQuad) - 1;
1502   case NeonTypeFlags::Poly128:
1503     return shift ? 127 : (1 << IsQuad) - 1;
1504   case NeonTypeFlags::Float16:
1505     assert(!shift && "cannot shift float types!");
1506     return (4 << IsQuad) - 1;
1507   case NeonTypeFlags::Float32:
1508     assert(!shift && "cannot shift float types!");
1509     return (2 << IsQuad) - 1;
1510   case NeonTypeFlags::Float64:
1511     assert(!shift && "cannot shift float types!");
1512     return (1 << IsQuad) - 1;
1513   }
1514   llvm_unreachable("Invalid NeonTypeFlag!");
1515 }
1516 
1517 /// getNeonEltType - Return the QualType corresponding to the elements of
1518 /// the vector type specified by the NeonTypeFlags.  This is used to check
1519 /// the pointer arguments for Neon load/store intrinsics.
1520 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1521                                bool IsPolyUnsigned, bool IsInt64Long) {
1522   switch (Flags.getEltType()) {
1523   case NeonTypeFlags::Int8:
1524     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1525   case NeonTypeFlags::Int16:
1526     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1527   case NeonTypeFlags::Int32:
1528     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1529   case NeonTypeFlags::Int64:
1530     if (IsInt64Long)
1531       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1532     else
1533       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1534                                 : Context.LongLongTy;
1535   case NeonTypeFlags::Poly8:
1536     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1537   case NeonTypeFlags::Poly16:
1538     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1539   case NeonTypeFlags::Poly64:
1540     if (IsInt64Long)
1541       return Context.UnsignedLongTy;
1542     else
1543       return Context.UnsignedLongLongTy;
1544   case NeonTypeFlags::Poly128:
1545     break;
1546   case NeonTypeFlags::Float16:
1547     return Context.HalfTy;
1548   case NeonTypeFlags::Float32:
1549     return Context.FloatTy;
1550   case NeonTypeFlags::Float64:
1551     return Context.DoubleTy;
1552   }
1553   llvm_unreachable("Invalid NeonTypeFlag!");
1554 }
1555 
1556 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1557   llvm::APSInt Result;
1558   uint64_t mask = 0;
1559   unsigned TV = 0;
1560   int PtrArgNum = -1;
1561   bool HasConstPtr = false;
1562   switch (BuiltinID) {
1563 #define GET_NEON_OVERLOAD_CHECK
1564 #include "clang/Basic/arm_neon.inc"
1565 #include "clang/Basic/arm_fp16.inc"
1566 #undef GET_NEON_OVERLOAD_CHECK
1567   }
1568 
1569   // For NEON intrinsics which are overloaded on vector element type, validate
1570   // the immediate which specifies which variant to emit.
1571   unsigned ImmArg = TheCall->getNumArgs()-1;
1572   if (mask) {
1573     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1574       return true;
1575 
1576     TV = Result.getLimitedValue(64);
1577     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1578       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1579              << TheCall->getArg(ImmArg)->getSourceRange();
1580   }
1581 
1582   if (PtrArgNum >= 0) {
1583     // Check that pointer arguments have the specified type.
1584     Expr *Arg = TheCall->getArg(PtrArgNum);
1585     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1586       Arg = ICE->getSubExpr();
1587     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1588     QualType RHSTy = RHS.get()->getType();
1589 
1590     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1591     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1592                           Arch == llvm::Triple::aarch64_be;
1593     bool IsInt64Long =
1594         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1595     QualType EltTy =
1596         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1597     if (HasConstPtr)
1598       EltTy = EltTy.withConst();
1599     QualType LHSTy = Context.getPointerType(EltTy);
1600     AssignConvertType ConvTy;
1601     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1602     if (RHS.isInvalid())
1603       return true;
1604     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1605                                  RHS.get(), AA_Assigning))
1606       return true;
1607   }
1608 
1609   // For NEON intrinsics which take an immediate value as part of the
1610   // instruction, range check them here.
1611   unsigned i = 0, l = 0, u = 0;
1612   switch (BuiltinID) {
1613   default:
1614     return false;
1615   #define GET_NEON_IMMEDIATE_CHECK
1616   #include "clang/Basic/arm_neon.inc"
1617   #include "clang/Basic/arm_fp16.inc"
1618   #undef GET_NEON_IMMEDIATE_CHECK
1619   }
1620 
1621   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1622 }
1623 
1624 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1625                                         unsigned MaxWidth) {
1626   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1627           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1628           BuiltinID == ARM::BI__builtin_arm_strex ||
1629           BuiltinID == ARM::BI__builtin_arm_stlex ||
1630           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1631           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1632           BuiltinID == AArch64::BI__builtin_arm_strex ||
1633           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1634          "unexpected ARM builtin");
1635   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1636                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1637                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1638                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1639 
1640   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1641 
1642   // Ensure that we have the proper number of arguments.
1643   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1644     return true;
1645 
1646   // Inspect the pointer argument of the atomic builtin.  This should always be
1647   // a pointer type, whose element is an integral scalar or pointer type.
1648   // Because it is a pointer type, we don't have to worry about any implicit
1649   // casts here.
1650   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1651   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1652   if (PointerArgRes.isInvalid())
1653     return true;
1654   PointerArg = PointerArgRes.get();
1655 
1656   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1657   if (!pointerType) {
1658     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1659         << PointerArg->getType() << PointerArg->getSourceRange();
1660     return true;
1661   }
1662 
1663   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1664   // task is to insert the appropriate casts into the AST. First work out just
1665   // what the appropriate type is.
1666   QualType ValType = pointerType->getPointeeType();
1667   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1668   if (IsLdrex)
1669     AddrType.addConst();
1670 
1671   // Issue a warning if the cast is dodgy.
1672   CastKind CastNeeded = CK_NoOp;
1673   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1674     CastNeeded = CK_BitCast;
1675     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1676         << PointerArg->getType() << Context.getPointerType(AddrType)
1677         << AA_Passing << PointerArg->getSourceRange();
1678   }
1679 
1680   // Finally, do the cast and replace the argument with the corrected version.
1681   AddrType = Context.getPointerType(AddrType);
1682   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1683   if (PointerArgRes.isInvalid())
1684     return true;
1685   PointerArg = PointerArgRes.get();
1686 
1687   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1688 
1689   // In general, we allow ints, floats and pointers to be loaded and stored.
1690   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1691       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1692     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1693         << PointerArg->getType() << PointerArg->getSourceRange();
1694     return true;
1695   }
1696 
1697   // But ARM doesn't have instructions to deal with 128-bit versions.
1698   if (Context.getTypeSize(ValType) > MaxWidth) {
1699     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1700     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1701         << PointerArg->getType() << PointerArg->getSourceRange();
1702     return true;
1703   }
1704 
1705   switch (ValType.getObjCLifetime()) {
1706   case Qualifiers::OCL_None:
1707   case Qualifiers::OCL_ExplicitNone:
1708     // okay
1709     break;
1710 
1711   case Qualifiers::OCL_Weak:
1712   case Qualifiers::OCL_Strong:
1713   case Qualifiers::OCL_Autoreleasing:
1714     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1715         << ValType << PointerArg->getSourceRange();
1716     return true;
1717   }
1718 
1719   if (IsLdrex) {
1720     TheCall->setType(ValType);
1721     return false;
1722   }
1723 
1724   // Initialize the argument to be stored.
1725   ExprResult ValArg = TheCall->getArg(0);
1726   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1727       Context, ValType, /*consume*/ false);
1728   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1729   if (ValArg.isInvalid())
1730     return true;
1731   TheCall->setArg(0, ValArg.get());
1732 
1733   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1734   // but the custom checker bypasses all default analysis.
1735   TheCall->setType(Context.IntTy);
1736   return false;
1737 }
1738 
1739 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1740   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1741       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1742       BuiltinID == ARM::BI__builtin_arm_strex ||
1743       BuiltinID == ARM::BI__builtin_arm_stlex) {
1744     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1745   }
1746 
1747   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1748     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1749       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1750   }
1751 
1752   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1753       BuiltinID == ARM::BI__builtin_arm_wsr64)
1754     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1755 
1756   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1757       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1758       BuiltinID == ARM::BI__builtin_arm_wsr ||
1759       BuiltinID == ARM::BI__builtin_arm_wsrp)
1760     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1761 
1762   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1763     return true;
1764 
1765   // For intrinsics which take an immediate value as part of the instruction,
1766   // range check them here.
1767   // FIXME: VFP Intrinsics should error if VFP not present.
1768   switch (BuiltinID) {
1769   default: return false;
1770   case ARM::BI__builtin_arm_ssat:
1771     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1772   case ARM::BI__builtin_arm_usat:
1773     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1774   case ARM::BI__builtin_arm_ssat16:
1775     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1776   case ARM::BI__builtin_arm_usat16:
1777     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1778   case ARM::BI__builtin_arm_vcvtr_f:
1779   case ARM::BI__builtin_arm_vcvtr_d:
1780     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1781   case ARM::BI__builtin_arm_dmb:
1782   case ARM::BI__builtin_arm_dsb:
1783   case ARM::BI__builtin_arm_isb:
1784   case ARM::BI__builtin_arm_dbg:
1785     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1786   }
1787 }
1788 
1789 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1790                                          CallExpr *TheCall) {
1791   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1792       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1793       BuiltinID == AArch64::BI__builtin_arm_strex ||
1794       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1795     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1796   }
1797 
1798   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1799     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1800       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1801       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1802       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1803   }
1804 
1805   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1806       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1807     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1808 
1809   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1810       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1811       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1812       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1813     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1814 
1815   // Only check the valid encoding range. Any constant in this range would be
1816   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1817   // an exception for incorrect registers. This matches MSVC behavior.
1818   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1819       BuiltinID == AArch64::BI_WriteStatusReg)
1820     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1821 
1822   if (BuiltinID == AArch64::BI__getReg)
1823     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1824 
1825   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1826     return true;
1827 
1828   // For intrinsics which take an immediate value as part of the instruction,
1829   // range check them here.
1830   unsigned i = 0, l = 0, u = 0;
1831   switch (BuiltinID) {
1832   default: return false;
1833   case AArch64::BI__builtin_arm_dmb:
1834   case AArch64::BI__builtin_arm_dsb:
1835   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1836   }
1837 
1838   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1839 }
1840 
1841 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1842   struct BuiltinAndString {
1843     unsigned BuiltinID;
1844     const char *Str;
1845   };
1846 
1847   static BuiltinAndString ValidCPU[] = {
1848     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1849     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1850     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1851     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1852     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1853     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1854     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1855     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1856     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1857     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1858     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1859     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1860     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1861     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1862     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1863     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1864     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1865     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1866     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1867     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1868     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1869     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1870     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1871   };
1872 
1873   static BuiltinAndString ValidHVX[] = {
1874     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1875     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1876     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1877     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1878     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1879     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1880     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1881     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1882     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1883     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1884     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1885     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1886     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1887     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1888     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1889     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1890     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1891     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1892     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1893     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1894     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1895     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1896     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1897     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1898     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1899     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1900     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1901     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1902     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1903     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1904     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1905     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1906     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1907     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1908     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1909     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1910     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1911     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1912     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1913     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1914     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1915     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1916     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1917     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1918     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1919     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1920     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1921     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1922     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1923     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1924     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
1925     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
1926     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
1927     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
1928     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
1929     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
1930     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
1931     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
1932     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
1933     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
1934     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
1935     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
1936     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
1937     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
1938     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
1939     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
1940     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
1941     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
1942     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
1943     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
1944     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
1945     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
1946     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
1947     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
1948     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
1949     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
1950     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
1951     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
1952     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
1953     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
1954     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
1955     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
1958     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
1970     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2606   };
2607 
2608   // Sort the tables on first execution so we can binary search them.
2609   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2610     return LHS.BuiltinID < RHS.BuiltinID;
2611   };
2612   static const bool SortOnce =
2613       (std::sort(std::begin(ValidCPU), std::end(ValidCPU), SortCmp),
2614        std::sort(std::begin(ValidHVX), std::end(ValidHVX), SortCmp), true);
2615   (void)SortOnce;
2616   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2617     return BI.BuiltinID < BuiltinID;
2618   };
2619 
2620   const TargetInfo &TI = Context.getTargetInfo();
2621 
2622   const BuiltinAndString *FC =
2623       std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2624                        LowerBoundCmp);
2625   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2626     const TargetOptions &Opts = TI.getTargetOpts();
2627     StringRef CPU = Opts.CPU;
2628     if (!CPU.empty()) {
2629       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2630       CPU.consume_front("hexagon");
2631       SmallVector<StringRef, 3> CPUs;
2632       StringRef(FC->Str).split(CPUs, ',');
2633       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2634         return Diag(TheCall->getBeginLoc(),
2635                     diag::err_hexagon_builtin_unsupported_cpu);
2636     }
2637   }
2638 
2639   const BuiltinAndString *FH =
2640       std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2641                        LowerBoundCmp);
2642   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2643     if (!TI.hasFeature("hvx"))
2644       return Diag(TheCall->getBeginLoc(),
2645                   diag::err_hexagon_builtin_requires_hvx);
2646 
2647     SmallVector<StringRef, 3> HVXs;
2648     StringRef(FH->Str).split(HVXs, ',');
2649     bool IsValid = llvm::any_of(HVXs,
2650                                 [&TI] (StringRef V) {
2651                                   std::string F = "hvx" + V.str();
2652                                   return TI.hasFeature(F);
2653                                 });
2654     if (!IsValid)
2655       return Diag(TheCall->getBeginLoc(),
2656                   diag::err_hexagon_builtin_unsupported_hvx);
2657   }
2658 
2659   return false;
2660 }
2661 
2662 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2663   struct ArgInfo {
2664     uint8_t OpNum;
2665     bool IsSigned;
2666     uint8_t BitWidth;
2667     uint8_t Align;
2668   };
2669   struct BuiltinInfo {
2670     unsigned BuiltinID;
2671     ArgInfo Infos[2];
2672   };
2673 
2674   static BuiltinInfo Infos[] = {
2675     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2676     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2677     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2678     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2679     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2680     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2681     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2682     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2683     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2684     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2685     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2686 
2687     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2690     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2691     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2692     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2698 
2699     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2700     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2710     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2713     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2729     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2734     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2743     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2744     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2746     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2749     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2751                                                       {{ 1, false, 6,  0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2759                                                       {{ 1, false, 5,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2766                                                        { 2, false, 5,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2768                                                        { 2, false, 6,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2770                                                        { 3, false, 5,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2772                                                        { 3, false, 6,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2789                                                       {{ 2, false, 4,  0 },
2790                                                        { 3, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2792                                                       {{ 2, false, 4,  0 },
2793                                                        { 3, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2795                                                       {{ 2, false, 4,  0 },
2796                                                        { 3, false, 5,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2798                                                       {{ 2, false, 4,  0 },
2799                                                        { 3, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2811                                                        { 2, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2813                                                        { 2, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2823                                                       {{ 1, false, 4,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2826                                                       {{ 1, false, 4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2847                                                       {{ 3, false, 1,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2852                                                       {{ 3, false, 1,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2857                                                       {{ 3, false, 1,  0 }} },
2858   };
2859 
2860   // Use a dynamically initialized static to sort the table exactly once on
2861   // first run.
2862   static const bool SortOnce =
2863       (std::sort(std::begin(Infos), std::end(Infos),
2864                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2865                    return LHS.BuiltinID < RHS.BuiltinID;
2866                  }),
2867        true);
2868   (void)SortOnce;
2869 
2870   const BuiltinInfo *F =
2871       std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2872                        [](const BuiltinInfo &BI, unsigned BuiltinID) {
2873                          return BI.BuiltinID < BuiltinID;
2874                        });
2875   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2876     return false;
2877 
2878   bool Error = false;
2879 
2880   for (const ArgInfo &A : F->Infos) {
2881     // Ignore empty ArgInfo elements.
2882     if (A.BitWidth == 0)
2883       continue;
2884 
2885     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2886     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2887     if (!A.Align) {
2888       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2889     } else {
2890       unsigned M = 1 << A.Align;
2891       Min *= M;
2892       Max *= M;
2893       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2894                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2895     }
2896   }
2897   return Error;
2898 }
2899 
2900 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2901                                            CallExpr *TheCall) {
2902   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2903          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2904 }
2905 
2906 
2907 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2908 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2909 // ordering for DSP is unspecified. MSA is ordered by the data format used
2910 // by the underlying instruction i.e., df/m, df/n and then by size.
2911 //
2912 // FIXME: The size tests here should instead be tablegen'd along with the
2913 //        definitions from include/clang/Basic/BuiltinsMips.def.
2914 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2915 //        be too.
2916 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2917   unsigned i = 0, l = 0, u = 0, m = 0;
2918   switch (BuiltinID) {
2919   default: return false;
2920   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2921   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2922   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2923   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2924   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2925   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2926   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2927   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2928   // df/m field.
2929   // These intrinsics take an unsigned 3 bit immediate.
2930   case Mips::BI__builtin_msa_bclri_b:
2931   case Mips::BI__builtin_msa_bnegi_b:
2932   case Mips::BI__builtin_msa_bseti_b:
2933   case Mips::BI__builtin_msa_sat_s_b:
2934   case Mips::BI__builtin_msa_sat_u_b:
2935   case Mips::BI__builtin_msa_slli_b:
2936   case Mips::BI__builtin_msa_srai_b:
2937   case Mips::BI__builtin_msa_srari_b:
2938   case Mips::BI__builtin_msa_srli_b:
2939   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2940   case Mips::BI__builtin_msa_binsli_b:
2941   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2942   // These intrinsics take an unsigned 4 bit immediate.
2943   case Mips::BI__builtin_msa_bclri_h:
2944   case Mips::BI__builtin_msa_bnegi_h:
2945   case Mips::BI__builtin_msa_bseti_h:
2946   case Mips::BI__builtin_msa_sat_s_h:
2947   case Mips::BI__builtin_msa_sat_u_h:
2948   case Mips::BI__builtin_msa_slli_h:
2949   case Mips::BI__builtin_msa_srai_h:
2950   case Mips::BI__builtin_msa_srari_h:
2951   case Mips::BI__builtin_msa_srli_h:
2952   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2953   case Mips::BI__builtin_msa_binsli_h:
2954   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2955   // These intrinsics take an unsigned 5 bit immediate.
2956   // The first block of intrinsics actually have an unsigned 5 bit field,
2957   // not a df/n field.
2958   case Mips::BI__builtin_msa_clei_u_b:
2959   case Mips::BI__builtin_msa_clei_u_h:
2960   case Mips::BI__builtin_msa_clei_u_w:
2961   case Mips::BI__builtin_msa_clei_u_d:
2962   case Mips::BI__builtin_msa_clti_u_b:
2963   case Mips::BI__builtin_msa_clti_u_h:
2964   case Mips::BI__builtin_msa_clti_u_w:
2965   case Mips::BI__builtin_msa_clti_u_d:
2966   case Mips::BI__builtin_msa_maxi_u_b:
2967   case Mips::BI__builtin_msa_maxi_u_h:
2968   case Mips::BI__builtin_msa_maxi_u_w:
2969   case Mips::BI__builtin_msa_maxi_u_d:
2970   case Mips::BI__builtin_msa_mini_u_b:
2971   case Mips::BI__builtin_msa_mini_u_h:
2972   case Mips::BI__builtin_msa_mini_u_w:
2973   case Mips::BI__builtin_msa_mini_u_d:
2974   case Mips::BI__builtin_msa_addvi_b:
2975   case Mips::BI__builtin_msa_addvi_h:
2976   case Mips::BI__builtin_msa_addvi_w:
2977   case Mips::BI__builtin_msa_addvi_d:
2978   case Mips::BI__builtin_msa_bclri_w:
2979   case Mips::BI__builtin_msa_bnegi_w:
2980   case Mips::BI__builtin_msa_bseti_w:
2981   case Mips::BI__builtin_msa_sat_s_w:
2982   case Mips::BI__builtin_msa_sat_u_w:
2983   case Mips::BI__builtin_msa_slli_w:
2984   case Mips::BI__builtin_msa_srai_w:
2985   case Mips::BI__builtin_msa_srari_w:
2986   case Mips::BI__builtin_msa_srli_w:
2987   case Mips::BI__builtin_msa_srlri_w:
2988   case Mips::BI__builtin_msa_subvi_b:
2989   case Mips::BI__builtin_msa_subvi_h:
2990   case Mips::BI__builtin_msa_subvi_w:
2991   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2992   case Mips::BI__builtin_msa_binsli_w:
2993   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2994   // These intrinsics take an unsigned 6 bit immediate.
2995   case Mips::BI__builtin_msa_bclri_d:
2996   case Mips::BI__builtin_msa_bnegi_d:
2997   case Mips::BI__builtin_msa_bseti_d:
2998   case Mips::BI__builtin_msa_sat_s_d:
2999   case Mips::BI__builtin_msa_sat_u_d:
3000   case Mips::BI__builtin_msa_slli_d:
3001   case Mips::BI__builtin_msa_srai_d:
3002   case Mips::BI__builtin_msa_srari_d:
3003   case Mips::BI__builtin_msa_srli_d:
3004   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3005   case Mips::BI__builtin_msa_binsli_d:
3006   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3007   // These intrinsics take a signed 5 bit immediate.
3008   case Mips::BI__builtin_msa_ceqi_b:
3009   case Mips::BI__builtin_msa_ceqi_h:
3010   case Mips::BI__builtin_msa_ceqi_w:
3011   case Mips::BI__builtin_msa_ceqi_d:
3012   case Mips::BI__builtin_msa_clti_s_b:
3013   case Mips::BI__builtin_msa_clti_s_h:
3014   case Mips::BI__builtin_msa_clti_s_w:
3015   case Mips::BI__builtin_msa_clti_s_d:
3016   case Mips::BI__builtin_msa_clei_s_b:
3017   case Mips::BI__builtin_msa_clei_s_h:
3018   case Mips::BI__builtin_msa_clei_s_w:
3019   case Mips::BI__builtin_msa_clei_s_d:
3020   case Mips::BI__builtin_msa_maxi_s_b:
3021   case Mips::BI__builtin_msa_maxi_s_h:
3022   case Mips::BI__builtin_msa_maxi_s_w:
3023   case Mips::BI__builtin_msa_maxi_s_d:
3024   case Mips::BI__builtin_msa_mini_s_b:
3025   case Mips::BI__builtin_msa_mini_s_h:
3026   case Mips::BI__builtin_msa_mini_s_w:
3027   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3028   // These intrinsics take an unsigned 8 bit immediate.
3029   case Mips::BI__builtin_msa_andi_b:
3030   case Mips::BI__builtin_msa_nori_b:
3031   case Mips::BI__builtin_msa_ori_b:
3032   case Mips::BI__builtin_msa_shf_b:
3033   case Mips::BI__builtin_msa_shf_h:
3034   case Mips::BI__builtin_msa_shf_w:
3035   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3036   case Mips::BI__builtin_msa_bseli_b:
3037   case Mips::BI__builtin_msa_bmnzi_b:
3038   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3039   // df/n format
3040   // These intrinsics take an unsigned 4 bit immediate.
3041   case Mips::BI__builtin_msa_copy_s_b:
3042   case Mips::BI__builtin_msa_copy_u_b:
3043   case Mips::BI__builtin_msa_insve_b:
3044   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3045   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3046   // These intrinsics take an unsigned 3 bit immediate.
3047   case Mips::BI__builtin_msa_copy_s_h:
3048   case Mips::BI__builtin_msa_copy_u_h:
3049   case Mips::BI__builtin_msa_insve_h:
3050   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3051   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3052   // These intrinsics take an unsigned 2 bit immediate.
3053   case Mips::BI__builtin_msa_copy_s_w:
3054   case Mips::BI__builtin_msa_copy_u_w:
3055   case Mips::BI__builtin_msa_insve_w:
3056   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3057   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3058   // These intrinsics take an unsigned 1 bit immediate.
3059   case Mips::BI__builtin_msa_copy_s_d:
3060   case Mips::BI__builtin_msa_copy_u_d:
3061   case Mips::BI__builtin_msa_insve_d:
3062   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3063   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3064   // Memory offsets and immediate loads.
3065   // These intrinsics take a signed 10 bit immediate.
3066   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3067   case Mips::BI__builtin_msa_ldi_h:
3068   case Mips::BI__builtin_msa_ldi_w:
3069   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3070   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3071   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3072   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3073   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3074   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3075   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3076   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3077   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3078   }
3079 
3080   if (!m)
3081     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3082 
3083   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3084          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3085 }
3086 
3087 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3088   unsigned i = 0, l = 0, u = 0;
3089   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3090                       BuiltinID == PPC::BI__builtin_divdeu ||
3091                       BuiltinID == PPC::BI__builtin_bpermd;
3092   bool IsTarget64Bit = Context.getTargetInfo()
3093                               .getTypeWidth(Context
3094                                             .getTargetInfo()
3095                                             .getIntPtrType()) == 64;
3096   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3097                        BuiltinID == PPC::BI__builtin_divweu ||
3098                        BuiltinID == PPC::BI__builtin_divde ||
3099                        BuiltinID == PPC::BI__builtin_divdeu;
3100 
3101   if (Is64BitBltin && !IsTarget64Bit)
3102     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3103            << TheCall->getSourceRange();
3104 
3105   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3106       (BuiltinID == PPC::BI__builtin_bpermd &&
3107        !Context.getTargetInfo().hasFeature("bpermd")))
3108     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3109            << TheCall->getSourceRange();
3110 
3111   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3112     if (!Context.getTargetInfo().hasFeature("vsx"))
3113       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3114              << TheCall->getSourceRange();
3115     return false;
3116   };
3117 
3118   switch (BuiltinID) {
3119   default: return false;
3120   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3121   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3122     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3123            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3124   case PPC::BI__builtin_tbegin:
3125   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3126   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3127   case PPC::BI__builtin_tabortwc:
3128   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3129   case PPC::BI__builtin_tabortwci:
3130   case PPC::BI__builtin_tabortdci:
3131     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3132            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3133   case PPC::BI__builtin_vsx_xxpermdi:
3134   case PPC::BI__builtin_vsx_xxsldwi:
3135     return SemaBuiltinVSX(TheCall);
3136   case PPC::BI__builtin_unpack_vector_int128:
3137     return SemaVSXCheck(TheCall) ||
3138            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3139   case PPC::BI__builtin_pack_vector_int128:
3140     return SemaVSXCheck(TheCall);
3141   }
3142   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3143 }
3144 
3145 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3146                                            CallExpr *TheCall) {
3147   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3148     Expr *Arg = TheCall->getArg(0);
3149     llvm::APSInt AbortCode(32);
3150     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3151         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3152       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3153              << Arg->getSourceRange();
3154   }
3155 
3156   // For intrinsics which take an immediate value as part of the instruction,
3157   // range check them here.
3158   unsigned i = 0, l = 0, u = 0;
3159   switch (BuiltinID) {
3160   default: return false;
3161   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3162   case SystemZ::BI__builtin_s390_verimb:
3163   case SystemZ::BI__builtin_s390_verimh:
3164   case SystemZ::BI__builtin_s390_verimf:
3165   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3166   case SystemZ::BI__builtin_s390_vfaeb:
3167   case SystemZ::BI__builtin_s390_vfaeh:
3168   case SystemZ::BI__builtin_s390_vfaef:
3169   case SystemZ::BI__builtin_s390_vfaebs:
3170   case SystemZ::BI__builtin_s390_vfaehs:
3171   case SystemZ::BI__builtin_s390_vfaefs:
3172   case SystemZ::BI__builtin_s390_vfaezb:
3173   case SystemZ::BI__builtin_s390_vfaezh:
3174   case SystemZ::BI__builtin_s390_vfaezf:
3175   case SystemZ::BI__builtin_s390_vfaezbs:
3176   case SystemZ::BI__builtin_s390_vfaezhs:
3177   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3178   case SystemZ::BI__builtin_s390_vfisb:
3179   case SystemZ::BI__builtin_s390_vfidb:
3180     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3181            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3182   case SystemZ::BI__builtin_s390_vftcisb:
3183   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3184   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3185   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3186   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3187   case SystemZ::BI__builtin_s390_vstrcb:
3188   case SystemZ::BI__builtin_s390_vstrch:
3189   case SystemZ::BI__builtin_s390_vstrcf:
3190   case SystemZ::BI__builtin_s390_vstrczb:
3191   case SystemZ::BI__builtin_s390_vstrczh:
3192   case SystemZ::BI__builtin_s390_vstrczf:
3193   case SystemZ::BI__builtin_s390_vstrcbs:
3194   case SystemZ::BI__builtin_s390_vstrchs:
3195   case SystemZ::BI__builtin_s390_vstrcfs:
3196   case SystemZ::BI__builtin_s390_vstrczbs:
3197   case SystemZ::BI__builtin_s390_vstrczhs:
3198   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3199   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3200   case SystemZ::BI__builtin_s390_vfminsb:
3201   case SystemZ::BI__builtin_s390_vfmaxsb:
3202   case SystemZ::BI__builtin_s390_vfmindb:
3203   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3204   }
3205   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3206 }
3207 
3208 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3209 /// This checks that the target supports __builtin_cpu_supports and
3210 /// that the string argument is constant and valid.
3211 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3212   Expr *Arg = TheCall->getArg(0);
3213 
3214   // Check if the argument is a string literal.
3215   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3216     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3217            << Arg->getSourceRange();
3218 
3219   // Check the contents of the string.
3220   StringRef Feature =
3221       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3222   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3223     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3224            << Arg->getSourceRange();
3225   return false;
3226 }
3227 
3228 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3229 /// This checks that the target supports __builtin_cpu_is and
3230 /// that the string argument is constant and valid.
3231 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3232   Expr *Arg = TheCall->getArg(0);
3233 
3234   // Check if the argument is a string literal.
3235   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3236     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3237            << Arg->getSourceRange();
3238 
3239   // Check the contents of the string.
3240   StringRef Feature =
3241       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3242   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3243     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3244            << Arg->getSourceRange();
3245   return false;
3246 }
3247 
3248 // Check if the rounding mode is legal.
3249 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3250   // Indicates if this instruction has rounding control or just SAE.
3251   bool HasRC = false;
3252 
3253   unsigned ArgNum = 0;
3254   switch (BuiltinID) {
3255   default:
3256     return false;
3257   case X86::BI__builtin_ia32_vcvttsd2si32:
3258   case X86::BI__builtin_ia32_vcvttsd2si64:
3259   case X86::BI__builtin_ia32_vcvttsd2usi32:
3260   case X86::BI__builtin_ia32_vcvttsd2usi64:
3261   case X86::BI__builtin_ia32_vcvttss2si32:
3262   case X86::BI__builtin_ia32_vcvttss2si64:
3263   case X86::BI__builtin_ia32_vcvttss2usi32:
3264   case X86::BI__builtin_ia32_vcvttss2usi64:
3265     ArgNum = 1;
3266     break;
3267   case X86::BI__builtin_ia32_maxpd512:
3268   case X86::BI__builtin_ia32_maxps512:
3269   case X86::BI__builtin_ia32_minpd512:
3270   case X86::BI__builtin_ia32_minps512:
3271     ArgNum = 2;
3272     break;
3273   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3274   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3275   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3276   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3277   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3278   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3279   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3280   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3281   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3282   case X86::BI__builtin_ia32_exp2pd_mask:
3283   case X86::BI__builtin_ia32_exp2ps_mask:
3284   case X86::BI__builtin_ia32_getexppd512_mask:
3285   case X86::BI__builtin_ia32_getexpps512_mask:
3286   case X86::BI__builtin_ia32_rcp28pd_mask:
3287   case X86::BI__builtin_ia32_rcp28ps_mask:
3288   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3289   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3290   case X86::BI__builtin_ia32_vcomisd:
3291   case X86::BI__builtin_ia32_vcomiss:
3292   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3293     ArgNum = 3;
3294     break;
3295   case X86::BI__builtin_ia32_cmppd512_mask:
3296   case X86::BI__builtin_ia32_cmpps512_mask:
3297   case X86::BI__builtin_ia32_cmpsd_mask:
3298   case X86::BI__builtin_ia32_cmpss_mask:
3299   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3300   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3301   case X86::BI__builtin_ia32_getexpss128_round_mask:
3302   case X86::BI__builtin_ia32_maxsd_round_mask:
3303   case X86::BI__builtin_ia32_maxss_round_mask:
3304   case X86::BI__builtin_ia32_minsd_round_mask:
3305   case X86::BI__builtin_ia32_minss_round_mask:
3306   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3307   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3308   case X86::BI__builtin_ia32_reducepd512_mask:
3309   case X86::BI__builtin_ia32_reduceps512_mask:
3310   case X86::BI__builtin_ia32_rndscalepd_mask:
3311   case X86::BI__builtin_ia32_rndscaleps_mask:
3312   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3313   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3314     ArgNum = 4;
3315     break;
3316   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3317   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3318   case X86::BI__builtin_ia32_fixupimmps512_mask:
3319   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3320   case X86::BI__builtin_ia32_fixupimmsd_mask:
3321   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3322   case X86::BI__builtin_ia32_fixupimmss_mask:
3323   case X86::BI__builtin_ia32_fixupimmss_maskz:
3324   case X86::BI__builtin_ia32_rangepd512_mask:
3325   case X86::BI__builtin_ia32_rangeps512_mask:
3326   case X86::BI__builtin_ia32_rangesd128_round_mask:
3327   case X86::BI__builtin_ia32_rangess128_round_mask:
3328   case X86::BI__builtin_ia32_reducesd_mask:
3329   case X86::BI__builtin_ia32_reducess_mask:
3330   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3331   case X86::BI__builtin_ia32_rndscaless_round_mask:
3332     ArgNum = 5;
3333     break;
3334   case X86::BI__builtin_ia32_vcvtsd2si64:
3335   case X86::BI__builtin_ia32_vcvtsd2si32:
3336   case X86::BI__builtin_ia32_vcvtsd2usi32:
3337   case X86::BI__builtin_ia32_vcvtsd2usi64:
3338   case X86::BI__builtin_ia32_vcvtss2si32:
3339   case X86::BI__builtin_ia32_vcvtss2si64:
3340   case X86::BI__builtin_ia32_vcvtss2usi32:
3341   case X86::BI__builtin_ia32_vcvtss2usi64:
3342   case X86::BI__builtin_ia32_sqrtpd512:
3343   case X86::BI__builtin_ia32_sqrtps512:
3344     ArgNum = 1;
3345     HasRC = true;
3346     break;
3347   case X86::BI__builtin_ia32_addpd512:
3348   case X86::BI__builtin_ia32_addps512:
3349   case X86::BI__builtin_ia32_divpd512:
3350   case X86::BI__builtin_ia32_divps512:
3351   case X86::BI__builtin_ia32_mulpd512:
3352   case X86::BI__builtin_ia32_mulps512:
3353   case X86::BI__builtin_ia32_subpd512:
3354   case X86::BI__builtin_ia32_subps512:
3355   case X86::BI__builtin_ia32_cvtsi2sd64:
3356   case X86::BI__builtin_ia32_cvtsi2ss32:
3357   case X86::BI__builtin_ia32_cvtsi2ss64:
3358   case X86::BI__builtin_ia32_cvtusi2sd64:
3359   case X86::BI__builtin_ia32_cvtusi2ss32:
3360   case X86::BI__builtin_ia32_cvtusi2ss64:
3361     ArgNum = 2;
3362     HasRC = true;
3363     break;
3364   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3365   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3366   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3367   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3368   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3369   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3370   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3371   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3372   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3373   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3374   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3375     ArgNum = 3;
3376     HasRC = true;
3377     break;
3378   case X86::BI__builtin_ia32_addss_round_mask:
3379   case X86::BI__builtin_ia32_addsd_round_mask:
3380   case X86::BI__builtin_ia32_divss_round_mask:
3381   case X86::BI__builtin_ia32_divsd_round_mask:
3382   case X86::BI__builtin_ia32_mulss_round_mask:
3383   case X86::BI__builtin_ia32_mulsd_round_mask:
3384   case X86::BI__builtin_ia32_subss_round_mask:
3385   case X86::BI__builtin_ia32_subsd_round_mask:
3386   case X86::BI__builtin_ia32_scalefpd512_mask:
3387   case X86::BI__builtin_ia32_scalefps512_mask:
3388   case X86::BI__builtin_ia32_scalefsd_round_mask:
3389   case X86::BI__builtin_ia32_scalefss_round_mask:
3390   case X86::BI__builtin_ia32_getmantpd512_mask:
3391   case X86::BI__builtin_ia32_getmantps512_mask:
3392   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3393   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3394   case X86::BI__builtin_ia32_sqrtss_round_mask:
3395   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3396   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3397   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3398   case X86::BI__builtin_ia32_vfmaddss3_mask:
3399   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3400   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3401   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3402   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3403   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3404   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3405   case X86::BI__builtin_ia32_vfmaddps512_mask:
3406   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3407   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3408   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3409   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3410   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3411   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3412   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3413   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3414   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3415   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3416   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3417     ArgNum = 4;
3418     HasRC = true;
3419     break;
3420   case X86::BI__builtin_ia32_getmantsd_round_mask:
3421   case X86::BI__builtin_ia32_getmantss_round_mask:
3422     ArgNum = 5;
3423     HasRC = true;
3424     break;
3425   }
3426 
3427   llvm::APSInt Result;
3428 
3429   // We can't check the value of a dependent argument.
3430   Expr *Arg = TheCall->getArg(ArgNum);
3431   if (Arg->isTypeDependent() || Arg->isValueDependent())
3432     return false;
3433 
3434   // Check constant-ness first.
3435   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3436     return true;
3437 
3438   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3439   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3440   // combined with ROUND_NO_EXC.
3441   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3442       Result == 8/*ROUND_NO_EXC*/ ||
3443       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3444     return false;
3445 
3446   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3447          << Arg->getSourceRange();
3448 }
3449 
3450 // Check if the gather/scatter scale is legal.
3451 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3452                                              CallExpr *TheCall) {
3453   unsigned ArgNum = 0;
3454   switch (BuiltinID) {
3455   default:
3456     return false;
3457   case X86::BI__builtin_ia32_gatherpfdpd:
3458   case X86::BI__builtin_ia32_gatherpfdps:
3459   case X86::BI__builtin_ia32_gatherpfqpd:
3460   case X86::BI__builtin_ia32_gatherpfqps:
3461   case X86::BI__builtin_ia32_scatterpfdpd:
3462   case X86::BI__builtin_ia32_scatterpfdps:
3463   case X86::BI__builtin_ia32_scatterpfqpd:
3464   case X86::BI__builtin_ia32_scatterpfqps:
3465     ArgNum = 3;
3466     break;
3467   case X86::BI__builtin_ia32_gatherd_pd:
3468   case X86::BI__builtin_ia32_gatherd_pd256:
3469   case X86::BI__builtin_ia32_gatherq_pd:
3470   case X86::BI__builtin_ia32_gatherq_pd256:
3471   case X86::BI__builtin_ia32_gatherd_ps:
3472   case X86::BI__builtin_ia32_gatherd_ps256:
3473   case X86::BI__builtin_ia32_gatherq_ps:
3474   case X86::BI__builtin_ia32_gatherq_ps256:
3475   case X86::BI__builtin_ia32_gatherd_q:
3476   case X86::BI__builtin_ia32_gatherd_q256:
3477   case X86::BI__builtin_ia32_gatherq_q:
3478   case X86::BI__builtin_ia32_gatherq_q256:
3479   case X86::BI__builtin_ia32_gatherd_d:
3480   case X86::BI__builtin_ia32_gatherd_d256:
3481   case X86::BI__builtin_ia32_gatherq_d:
3482   case X86::BI__builtin_ia32_gatherq_d256:
3483   case X86::BI__builtin_ia32_gather3div2df:
3484   case X86::BI__builtin_ia32_gather3div2di:
3485   case X86::BI__builtin_ia32_gather3div4df:
3486   case X86::BI__builtin_ia32_gather3div4di:
3487   case X86::BI__builtin_ia32_gather3div4sf:
3488   case X86::BI__builtin_ia32_gather3div4si:
3489   case X86::BI__builtin_ia32_gather3div8sf:
3490   case X86::BI__builtin_ia32_gather3div8si:
3491   case X86::BI__builtin_ia32_gather3siv2df:
3492   case X86::BI__builtin_ia32_gather3siv2di:
3493   case X86::BI__builtin_ia32_gather3siv4df:
3494   case X86::BI__builtin_ia32_gather3siv4di:
3495   case X86::BI__builtin_ia32_gather3siv4sf:
3496   case X86::BI__builtin_ia32_gather3siv4si:
3497   case X86::BI__builtin_ia32_gather3siv8sf:
3498   case X86::BI__builtin_ia32_gather3siv8si:
3499   case X86::BI__builtin_ia32_gathersiv8df:
3500   case X86::BI__builtin_ia32_gathersiv16sf:
3501   case X86::BI__builtin_ia32_gatherdiv8df:
3502   case X86::BI__builtin_ia32_gatherdiv16sf:
3503   case X86::BI__builtin_ia32_gathersiv8di:
3504   case X86::BI__builtin_ia32_gathersiv16si:
3505   case X86::BI__builtin_ia32_gatherdiv8di:
3506   case X86::BI__builtin_ia32_gatherdiv16si:
3507   case X86::BI__builtin_ia32_scatterdiv2df:
3508   case X86::BI__builtin_ia32_scatterdiv2di:
3509   case X86::BI__builtin_ia32_scatterdiv4df:
3510   case X86::BI__builtin_ia32_scatterdiv4di:
3511   case X86::BI__builtin_ia32_scatterdiv4sf:
3512   case X86::BI__builtin_ia32_scatterdiv4si:
3513   case X86::BI__builtin_ia32_scatterdiv8sf:
3514   case X86::BI__builtin_ia32_scatterdiv8si:
3515   case X86::BI__builtin_ia32_scattersiv2df:
3516   case X86::BI__builtin_ia32_scattersiv2di:
3517   case X86::BI__builtin_ia32_scattersiv4df:
3518   case X86::BI__builtin_ia32_scattersiv4di:
3519   case X86::BI__builtin_ia32_scattersiv4sf:
3520   case X86::BI__builtin_ia32_scattersiv4si:
3521   case X86::BI__builtin_ia32_scattersiv8sf:
3522   case X86::BI__builtin_ia32_scattersiv8si:
3523   case X86::BI__builtin_ia32_scattersiv8df:
3524   case X86::BI__builtin_ia32_scattersiv16sf:
3525   case X86::BI__builtin_ia32_scatterdiv8df:
3526   case X86::BI__builtin_ia32_scatterdiv16sf:
3527   case X86::BI__builtin_ia32_scattersiv8di:
3528   case X86::BI__builtin_ia32_scattersiv16si:
3529   case X86::BI__builtin_ia32_scatterdiv8di:
3530   case X86::BI__builtin_ia32_scatterdiv16si:
3531     ArgNum = 4;
3532     break;
3533   }
3534 
3535   llvm::APSInt Result;
3536 
3537   // We can't check the value of a dependent argument.
3538   Expr *Arg = TheCall->getArg(ArgNum);
3539   if (Arg->isTypeDependent() || Arg->isValueDependent())
3540     return false;
3541 
3542   // Check constant-ness first.
3543   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3544     return true;
3545 
3546   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3547     return false;
3548 
3549   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3550          << Arg->getSourceRange();
3551 }
3552 
3553 static bool isX86_32Builtin(unsigned BuiltinID) {
3554   // These builtins only work on x86-32 targets.
3555   switch (BuiltinID) {
3556   case X86::BI__builtin_ia32_readeflags_u32:
3557   case X86::BI__builtin_ia32_writeeflags_u32:
3558     return true;
3559   }
3560 
3561   return false;
3562 }
3563 
3564 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3565   if (BuiltinID == X86::BI__builtin_cpu_supports)
3566     return SemaBuiltinCpuSupports(*this, TheCall);
3567 
3568   if (BuiltinID == X86::BI__builtin_cpu_is)
3569     return SemaBuiltinCpuIs(*this, TheCall);
3570 
3571   // Check for 32-bit only builtins on a 64-bit target.
3572   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3573   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3574     return Diag(TheCall->getCallee()->getBeginLoc(),
3575                 diag::err_32_bit_builtin_64_bit_tgt);
3576 
3577   // If the intrinsic has rounding or SAE make sure its valid.
3578   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3579     return true;
3580 
3581   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3582   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3583     return true;
3584 
3585   // For intrinsics which take an immediate value as part of the instruction,
3586   // range check them here.
3587   int i = 0, l = 0, u = 0;
3588   switch (BuiltinID) {
3589   default:
3590     return false;
3591   case X86::BI__builtin_ia32_vec_ext_v2si:
3592   case X86::BI__builtin_ia32_vec_ext_v2di:
3593   case X86::BI__builtin_ia32_vextractf128_pd256:
3594   case X86::BI__builtin_ia32_vextractf128_ps256:
3595   case X86::BI__builtin_ia32_vextractf128_si256:
3596   case X86::BI__builtin_ia32_extract128i256:
3597   case X86::BI__builtin_ia32_extractf64x4_mask:
3598   case X86::BI__builtin_ia32_extracti64x4_mask:
3599   case X86::BI__builtin_ia32_extractf32x8_mask:
3600   case X86::BI__builtin_ia32_extracti32x8_mask:
3601   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3602   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3603   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3604   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3605     i = 1; l = 0; u = 1;
3606     break;
3607   case X86::BI__builtin_ia32_vec_set_v2di:
3608   case X86::BI__builtin_ia32_vinsertf128_pd256:
3609   case X86::BI__builtin_ia32_vinsertf128_ps256:
3610   case X86::BI__builtin_ia32_vinsertf128_si256:
3611   case X86::BI__builtin_ia32_insert128i256:
3612   case X86::BI__builtin_ia32_insertf32x8:
3613   case X86::BI__builtin_ia32_inserti32x8:
3614   case X86::BI__builtin_ia32_insertf64x4:
3615   case X86::BI__builtin_ia32_inserti64x4:
3616   case X86::BI__builtin_ia32_insertf64x2_256:
3617   case X86::BI__builtin_ia32_inserti64x2_256:
3618   case X86::BI__builtin_ia32_insertf32x4_256:
3619   case X86::BI__builtin_ia32_inserti32x4_256:
3620     i = 2; l = 0; u = 1;
3621     break;
3622   case X86::BI__builtin_ia32_vpermilpd:
3623   case X86::BI__builtin_ia32_vec_ext_v4hi:
3624   case X86::BI__builtin_ia32_vec_ext_v4si:
3625   case X86::BI__builtin_ia32_vec_ext_v4sf:
3626   case X86::BI__builtin_ia32_vec_ext_v4di:
3627   case X86::BI__builtin_ia32_extractf32x4_mask:
3628   case X86::BI__builtin_ia32_extracti32x4_mask:
3629   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3630   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3631     i = 1; l = 0; u = 3;
3632     break;
3633   case X86::BI_mm_prefetch:
3634   case X86::BI__builtin_ia32_vec_ext_v8hi:
3635   case X86::BI__builtin_ia32_vec_ext_v8si:
3636     i = 1; l = 0; u = 7;
3637     break;
3638   case X86::BI__builtin_ia32_sha1rnds4:
3639   case X86::BI__builtin_ia32_blendpd:
3640   case X86::BI__builtin_ia32_shufpd:
3641   case X86::BI__builtin_ia32_vec_set_v4hi:
3642   case X86::BI__builtin_ia32_vec_set_v4si:
3643   case X86::BI__builtin_ia32_vec_set_v4di:
3644   case X86::BI__builtin_ia32_shuf_f32x4_256:
3645   case X86::BI__builtin_ia32_shuf_f64x2_256:
3646   case X86::BI__builtin_ia32_shuf_i32x4_256:
3647   case X86::BI__builtin_ia32_shuf_i64x2_256:
3648   case X86::BI__builtin_ia32_insertf64x2_512:
3649   case X86::BI__builtin_ia32_inserti64x2_512:
3650   case X86::BI__builtin_ia32_insertf32x4:
3651   case X86::BI__builtin_ia32_inserti32x4:
3652     i = 2; l = 0; u = 3;
3653     break;
3654   case X86::BI__builtin_ia32_vpermil2pd:
3655   case X86::BI__builtin_ia32_vpermil2pd256:
3656   case X86::BI__builtin_ia32_vpermil2ps:
3657   case X86::BI__builtin_ia32_vpermil2ps256:
3658     i = 3; l = 0; u = 3;
3659     break;
3660   case X86::BI__builtin_ia32_cmpb128_mask:
3661   case X86::BI__builtin_ia32_cmpw128_mask:
3662   case X86::BI__builtin_ia32_cmpd128_mask:
3663   case X86::BI__builtin_ia32_cmpq128_mask:
3664   case X86::BI__builtin_ia32_cmpb256_mask:
3665   case X86::BI__builtin_ia32_cmpw256_mask:
3666   case X86::BI__builtin_ia32_cmpd256_mask:
3667   case X86::BI__builtin_ia32_cmpq256_mask:
3668   case X86::BI__builtin_ia32_cmpb512_mask:
3669   case X86::BI__builtin_ia32_cmpw512_mask:
3670   case X86::BI__builtin_ia32_cmpd512_mask:
3671   case X86::BI__builtin_ia32_cmpq512_mask:
3672   case X86::BI__builtin_ia32_ucmpb128_mask:
3673   case X86::BI__builtin_ia32_ucmpw128_mask:
3674   case X86::BI__builtin_ia32_ucmpd128_mask:
3675   case X86::BI__builtin_ia32_ucmpq128_mask:
3676   case X86::BI__builtin_ia32_ucmpb256_mask:
3677   case X86::BI__builtin_ia32_ucmpw256_mask:
3678   case X86::BI__builtin_ia32_ucmpd256_mask:
3679   case X86::BI__builtin_ia32_ucmpq256_mask:
3680   case X86::BI__builtin_ia32_ucmpb512_mask:
3681   case X86::BI__builtin_ia32_ucmpw512_mask:
3682   case X86::BI__builtin_ia32_ucmpd512_mask:
3683   case X86::BI__builtin_ia32_ucmpq512_mask:
3684   case X86::BI__builtin_ia32_vpcomub:
3685   case X86::BI__builtin_ia32_vpcomuw:
3686   case X86::BI__builtin_ia32_vpcomud:
3687   case X86::BI__builtin_ia32_vpcomuq:
3688   case X86::BI__builtin_ia32_vpcomb:
3689   case X86::BI__builtin_ia32_vpcomw:
3690   case X86::BI__builtin_ia32_vpcomd:
3691   case X86::BI__builtin_ia32_vpcomq:
3692   case X86::BI__builtin_ia32_vec_set_v8hi:
3693   case X86::BI__builtin_ia32_vec_set_v8si:
3694     i = 2; l = 0; u = 7;
3695     break;
3696   case X86::BI__builtin_ia32_vpermilpd256:
3697   case X86::BI__builtin_ia32_roundps:
3698   case X86::BI__builtin_ia32_roundpd:
3699   case X86::BI__builtin_ia32_roundps256:
3700   case X86::BI__builtin_ia32_roundpd256:
3701   case X86::BI__builtin_ia32_getmantpd128_mask:
3702   case X86::BI__builtin_ia32_getmantpd256_mask:
3703   case X86::BI__builtin_ia32_getmantps128_mask:
3704   case X86::BI__builtin_ia32_getmantps256_mask:
3705   case X86::BI__builtin_ia32_getmantpd512_mask:
3706   case X86::BI__builtin_ia32_getmantps512_mask:
3707   case X86::BI__builtin_ia32_vec_ext_v16qi:
3708   case X86::BI__builtin_ia32_vec_ext_v16hi:
3709     i = 1; l = 0; u = 15;
3710     break;
3711   case X86::BI__builtin_ia32_pblendd128:
3712   case X86::BI__builtin_ia32_blendps:
3713   case X86::BI__builtin_ia32_blendpd256:
3714   case X86::BI__builtin_ia32_shufpd256:
3715   case X86::BI__builtin_ia32_roundss:
3716   case X86::BI__builtin_ia32_roundsd:
3717   case X86::BI__builtin_ia32_rangepd128_mask:
3718   case X86::BI__builtin_ia32_rangepd256_mask:
3719   case X86::BI__builtin_ia32_rangepd512_mask:
3720   case X86::BI__builtin_ia32_rangeps128_mask:
3721   case X86::BI__builtin_ia32_rangeps256_mask:
3722   case X86::BI__builtin_ia32_rangeps512_mask:
3723   case X86::BI__builtin_ia32_getmantsd_round_mask:
3724   case X86::BI__builtin_ia32_getmantss_round_mask:
3725   case X86::BI__builtin_ia32_vec_set_v16qi:
3726   case X86::BI__builtin_ia32_vec_set_v16hi:
3727     i = 2; l = 0; u = 15;
3728     break;
3729   case X86::BI__builtin_ia32_vec_ext_v32qi:
3730     i = 1; l = 0; u = 31;
3731     break;
3732   case X86::BI__builtin_ia32_cmpps:
3733   case X86::BI__builtin_ia32_cmpss:
3734   case X86::BI__builtin_ia32_cmppd:
3735   case X86::BI__builtin_ia32_cmpsd:
3736   case X86::BI__builtin_ia32_cmpps256:
3737   case X86::BI__builtin_ia32_cmppd256:
3738   case X86::BI__builtin_ia32_cmpps128_mask:
3739   case X86::BI__builtin_ia32_cmppd128_mask:
3740   case X86::BI__builtin_ia32_cmpps256_mask:
3741   case X86::BI__builtin_ia32_cmppd256_mask:
3742   case X86::BI__builtin_ia32_cmpps512_mask:
3743   case X86::BI__builtin_ia32_cmppd512_mask:
3744   case X86::BI__builtin_ia32_cmpsd_mask:
3745   case X86::BI__builtin_ia32_cmpss_mask:
3746   case X86::BI__builtin_ia32_vec_set_v32qi:
3747     i = 2; l = 0; u = 31;
3748     break;
3749   case X86::BI__builtin_ia32_permdf256:
3750   case X86::BI__builtin_ia32_permdi256:
3751   case X86::BI__builtin_ia32_permdf512:
3752   case X86::BI__builtin_ia32_permdi512:
3753   case X86::BI__builtin_ia32_vpermilps:
3754   case X86::BI__builtin_ia32_vpermilps256:
3755   case X86::BI__builtin_ia32_vpermilpd512:
3756   case X86::BI__builtin_ia32_vpermilps512:
3757   case X86::BI__builtin_ia32_pshufd:
3758   case X86::BI__builtin_ia32_pshufd256:
3759   case X86::BI__builtin_ia32_pshufd512:
3760   case X86::BI__builtin_ia32_pshufhw:
3761   case X86::BI__builtin_ia32_pshufhw256:
3762   case X86::BI__builtin_ia32_pshufhw512:
3763   case X86::BI__builtin_ia32_pshuflw:
3764   case X86::BI__builtin_ia32_pshuflw256:
3765   case X86::BI__builtin_ia32_pshuflw512:
3766   case X86::BI__builtin_ia32_vcvtps2ph:
3767   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3768   case X86::BI__builtin_ia32_vcvtps2ph256:
3769   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3770   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3771   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3772   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3773   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3774   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3775   case X86::BI__builtin_ia32_rndscaleps_mask:
3776   case X86::BI__builtin_ia32_rndscalepd_mask:
3777   case X86::BI__builtin_ia32_reducepd128_mask:
3778   case X86::BI__builtin_ia32_reducepd256_mask:
3779   case X86::BI__builtin_ia32_reducepd512_mask:
3780   case X86::BI__builtin_ia32_reduceps128_mask:
3781   case X86::BI__builtin_ia32_reduceps256_mask:
3782   case X86::BI__builtin_ia32_reduceps512_mask:
3783   case X86::BI__builtin_ia32_prold512:
3784   case X86::BI__builtin_ia32_prolq512:
3785   case X86::BI__builtin_ia32_prold128:
3786   case X86::BI__builtin_ia32_prold256:
3787   case X86::BI__builtin_ia32_prolq128:
3788   case X86::BI__builtin_ia32_prolq256:
3789   case X86::BI__builtin_ia32_prord512:
3790   case X86::BI__builtin_ia32_prorq512:
3791   case X86::BI__builtin_ia32_prord128:
3792   case X86::BI__builtin_ia32_prord256:
3793   case X86::BI__builtin_ia32_prorq128:
3794   case X86::BI__builtin_ia32_prorq256:
3795   case X86::BI__builtin_ia32_fpclasspd128_mask:
3796   case X86::BI__builtin_ia32_fpclasspd256_mask:
3797   case X86::BI__builtin_ia32_fpclassps128_mask:
3798   case X86::BI__builtin_ia32_fpclassps256_mask:
3799   case X86::BI__builtin_ia32_fpclassps512_mask:
3800   case X86::BI__builtin_ia32_fpclasspd512_mask:
3801   case X86::BI__builtin_ia32_fpclasssd_mask:
3802   case X86::BI__builtin_ia32_fpclassss_mask:
3803   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3804   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3805   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3806   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3807   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3808   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3809   case X86::BI__builtin_ia32_kshiftliqi:
3810   case X86::BI__builtin_ia32_kshiftlihi:
3811   case X86::BI__builtin_ia32_kshiftlisi:
3812   case X86::BI__builtin_ia32_kshiftlidi:
3813   case X86::BI__builtin_ia32_kshiftriqi:
3814   case X86::BI__builtin_ia32_kshiftrihi:
3815   case X86::BI__builtin_ia32_kshiftrisi:
3816   case X86::BI__builtin_ia32_kshiftridi:
3817     i = 1; l = 0; u = 255;
3818     break;
3819   case X86::BI__builtin_ia32_vperm2f128_pd256:
3820   case X86::BI__builtin_ia32_vperm2f128_ps256:
3821   case X86::BI__builtin_ia32_vperm2f128_si256:
3822   case X86::BI__builtin_ia32_permti256:
3823   case X86::BI__builtin_ia32_pblendw128:
3824   case X86::BI__builtin_ia32_pblendw256:
3825   case X86::BI__builtin_ia32_blendps256:
3826   case X86::BI__builtin_ia32_pblendd256:
3827   case X86::BI__builtin_ia32_palignr128:
3828   case X86::BI__builtin_ia32_palignr256:
3829   case X86::BI__builtin_ia32_palignr512:
3830   case X86::BI__builtin_ia32_alignq512:
3831   case X86::BI__builtin_ia32_alignd512:
3832   case X86::BI__builtin_ia32_alignd128:
3833   case X86::BI__builtin_ia32_alignd256:
3834   case X86::BI__builtin_ia32_alignq128:
3835   case X86::BI__builtin_ia32_alignq256:
3836   case X86::BI__builtin_ia32_vcomisd:
3837   case X86::BI__builtin_ia32_vcomiss:
3838   case X86::BI__builtin_ia32_shuf_f32x4:
3839   case X86::BI__builtin_ia32_shuf_f64x2:
3840   case X86::BI__builtin_ia32_shuf_i32x4:
3841   case X86::BI__builtin_ia32_shuf_i64x2:
3842   case X86::BI__builtin_ia32_shufpd512:
3843   case X86::BI__builtin_ia32_shufps:
3844   case X86::BI__builtin_ia32_shufps256:
3845   case X86::BI__builtin_ia32_shufps512:
3846   case X86::BI__builtin_ia32_dbpsadbw128:
3847   case X86::BI__builtin_ia32_dbpsadbw256:
3848   case X86::BI__builtin_ia32_dbpsadbw512:
3849   case X86::BI__builtin_ia32_vpshldd128:
3850   case X86::BI__builtin_ia32_vpshldd256:
3851   case X86::BI__builtin_ia32_vpshldd512:
3852   case X86::BI__builtin_ia32_vpshldq128:
3853   case X86::BI__builtin_ia32_vpshldq256:
3854   case X86::BI__builtin_ia32_vpshldq512:
3855   case X86::BI__builtin_ia32_vpshldw128:
3856   case X86::BI__builtin_ia32_vpshldw256:
3857   case X86::BI__builtin_ia32_vpshldw512:
3858   case X86::BI__builtin_ia32_vpshrdd128:
3859   case X86::BI__builtin_ia32_vpshrdd256:
3860   case X86::BI__builtin_ia32_vpshrdd512:
3861   case X86::BI__builtin_ia32_vpshrdq128:
3862   case X86::BI__builtin_ia32_vpshrdq256:
3863   case X86::BI__builtin_ia32_vpshrdq512:
3864   case X86::BI__builtin_ia32_vpshrdw128:
3865   case X86::BI__builtin_ia32_vpshrdw256:
3866   case X86::BI__builtin_ia32_vpshrdw512:
3867     i = 2; l = 0; u = 255;
3868     break;
3869   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3870   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3871   case X86::BI__builtin_ia32_fixupimmps512_mask:
3872   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3873   case X86::BI__builtin_ia32_fixupimmsd_mask:
3874   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3875   case X86::BI__builtin_ia32_fixupimmss_mask:
3876   case X86::BI__builtin_ia32_fixupimmss_maskz:
3877   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3878   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3879   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3880   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3881   case X86::BI__builtin_ia32_fixupimmps128_mask:
3882   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3883   case X86::BI__builtin_ia32_fixupimmps256_mask:
3884   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3885   case X86::BI__builtin_ia32_pternlogd512_mask:
3886   case X86::BI__builtin_ia32_pternlogd512_maskz:
3887   case X86::BI__builtin_ia32_pternlogq512_mask:
3888   case X86::BI__builtin_ia32_pternlogq512_maskz:
3889   case X86::BI__builtin_ia32_pternlogd128_mask:
3890   case X86::BI__builtin_ia32_pternlogd128_maskz:
3891   case X86::BI__builtin_ia32_pternlogd256_mask:
3892   case X86::BI__builtin_ia32_pternlogd256_maskz:
3893   case X86::BI__builtin_ia32_pternlogq128_mask:
3894   case X86::BI__builtin_ia32_pternlogq128_maskz:
3895   case X86::BI__builtin_ia32_pternlogq256_mask:
3896   case X86::BI__builtin_ia32_pternlogq256_maskz:
3897     i = 3; l = 0; u = 255;
3898     break;
3899   case X86::BI__builtin_ia32_gatherpfdpd:
3900   case X86::BI__builtin_ia32_gatherpfdps:
3901   case X86::BI__builtin_ia32_gatherpfqpd:
3902   case X86::BI__builtin_ia32_gatherpfqps:
3903   case X86::BI__builtin_ia32_scatterpfdpd:
3904   case X86::BI__builtin_ia32_scatterpfdps:
3905   case X86::BI__builtin_ia32_scatterpfqpd:
3906   case X86::BI__builtin_ia32_scatterpfqps:
3907     i = 4; l = 2; u = 3;
3908     break;
3909   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3910   case X86::BI__builtin_ia32_rndscaless_round_mask:
3911     i = 4; l = 0; u = 255;
3912     break;
3913   }
3914 
3915   // Note that we don't force a hard error on the range check here, allowing
3916   // template-generated or macro-generated dead code to potentially have out-of-
3917   // range values. These need to code generate, but don't need to necessarily
3918   // make any sense. We use a warning that defaults to an error.
3919   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3920 }
3921 
3922 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3923 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3924 /// Returns true when the format fits the function and the FormatStringInfo has
3925 /// been populated.
3926 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3927                                FormatStringInfo *FSI) {
3928   FSI->HasVAListArg = Format->getFirstArg() == 0;
3929   FSI->FormatIdx = Format->getFormatIdx() - 1;
3930   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3931 
3932   // The way the format attribute works in GCC, the implicit this argument
3933   // of member functions is counted. However, it doesn't appear in our own
3934   // lists, so decrement format_idx in that case.
3935   if (IsCXXMember) {
3936     if(FSI->FormatIdx == 0)
3937       return false;
3938     --FSI->FormatIdx;
3939     if (FSI->FirstDataArg != 0)
3940       --FSI->FirstDataArg;
3941   }
3942   return true;
3943 }
3944 
3945 /// Checks if a the given expression evaluates to null.
3946 ///
3947 /// Returns true if the value evaluates to null.
3948 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3949   // If the expression has non-null type, it doesn't evaluate to null.
3950   if (auto nullability
3951         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3952     if (*nullability == NullabilityKind::NonNull)
3953       return false;
3954   }
3955 
3956   // As a special case, transparent unions initialized with zero are
3957   // considered null for the purposes of the nonnull attribute.
3958   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3959     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3960       if (const CompoundLiteralExpr *CLE =
3961           dyn_cast<CompoundLiteralExpr>(Expr))
3962         if (const InitListExpr *ILE =
3963             dyn_cast<InitListExpr>(CLE->getInitializer()))
3964           Expr = ILE->getInit(0);
3965   }
3966 
3967   bool Result;
3968   return (!Expr->isValueDependent() &&
3969           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3970           !Result);
3971 }
3972 
3973 static void CheckNonNullArgument(Sema &S,
3974                                  const Expr *ArgExpr,
3975                                  SourceLocation CallSiteLoc) {
3976   if (CheckNonNullExpr(S, ArgExpr))
3977     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3978            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
3979 }
3980 
3981 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3982   FormatStringInfo FSI;
3983   if ((GetFormatStringType(Format) == FST_NSString) &&
3984       getFormatStringInfo(Format, false, &FSI)) {
3985     Idx = FSI.FormatIdx;
3986     return true;
3987   }
3988   return false;
3989 }
3990 
3991 /// Diagnose use of %s directive in an NSString which is being passed
3992 /// as formatting string to formatting method.
3993 static void
3994 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3995                                         const NamedDecl *FDecl,
3996                                         Expr **Args,
3997                                         unsigned NumArgs) {
3998   unsigned Idx = 0;
3999   bool Format = false;
4000   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4001   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4002     Idx = 2;
4003     Format = true;
4004   }
4005   else
4006     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4007       if (S.GetFormatNSStringIdx(I, Idx)) {
4008         Format = true;
4009         break;
4010       }
4011     }
4012   if (!Format || NumArgs <= Idx)
4013     return;
4014   const Expr *FormatExpr = Args[Idx];
4015   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4016     FormatExpr = CSCE->getSubExpr();
4017   const StringLiteral *FormatString;
4018   if (const ObjCStringLiteral *OSL =
4019       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4020     FormatString = OSL->getString();
4021   else
4022     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4023   if (!FormatString)
4024     return;
4025   if (S.FormatStringHasSArg(FormatString)) {
4026     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4027       << "%s" << 1 << 1;
4028     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4029       << FDecl->getDeclName();
4030   }
4031 }
4032 
4033 /// Determine whether the given type has a non-null nullability annotation.
4034 static bool isNonNullType(ASTContext &ctx, QualType type) {
4035   if (auto nullability = type->getNullability(ctx))
4036     return *nullability == NullabilityKind::NonNull;
4037 
4038   return false;
4039 }
4040 
4041 static void CheckNonNullArguments(Sema &S,
4042                                   const NamedDecl *FDecl,
4043                                   const FunctionProtoType *Proto,
4044                                   ArrayRef<const Expr *> Args,
4045                                   SourceLocation CallSiteLoc) {
4046   assert((FDecl || Proto) && "Need a function declaration or prototype");
4047 
4048   // Check the attributes attached to the method/function itself.
4049   llvm::SmallBitVector NonNullArgs;
4050   if (FDecl) {
4051     // Handle the nonnull attribute on the function/method declaration itself.
4052     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4053       if (!NonNull->args_size()) {
4054         // Easy case: all pointer arguments are nonnull.
4055         for (const auto *Arg : Args)
4056           if (S.isValidPointerAttrType(Arg->getType()))
4057             CheckNonNullArgument(S, Arg, CallSiteLoc);
4058         return;
4059       }
4060 
4061       for (const ParamIdx &Idx : NonNull->args()) {
4062         unsigned IdxAST = Idx.getASTIndex();
4063         if (IdxAST >= Args.size())
4064           continue;
4065         if (NonNullArgs.empty())
4066           NonNullArgs.resize(Args.size());
4067         NonNullArgs.set(IdxAST);
4068       }
4069     }
4070   }
4071 
4072   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4073     // Handle the nonnull attribute on the parameters of the
4074     // function/method.
4075     ArrayRef<ParmVarDecl*> parms;
4076     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4077       parms = FD->parameters();
4078     else
4079       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4080 
4081     unsigned ParamIndex = 0;
4082     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4083          I != E; ++I, ++ParamIndex) {
4084       const ParmVarDecl *PVD = *I;
4085       if (PVD->hasAttr<NonNullAttr>() ||
4086           isNonNullType(S.Context, PVD->getType())) {
4087         if (NonNullArgs.empty())
4088           NonNullArgs.resize(Args.size());
4089 
4090         NonNullArgs.set(ParamIndex);
4091       }
4092     }
4093   } else {
4094     // If we have a non-function, non-method declaration but no
4095     // function prototype, try to dig out the function prototype.
4096     if (!Proto) {
4097       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4098         QualType type = VD->getType().getNonReferenceType();
4099         if (auto pointerType = type->getAs<PointerType>())
4100           type = pointerType->getPointeeType();
4101         else if (auto blockType = type->getAs<BlockPointerType>())
4102           type = blockType->getPointeeType();
4103         // FIXME: data member pointers?
4104 
4105         // Dig out the function prototype, if there is one.
4106         Proto = type->getAs<FunctionProtoType>();
4107       }
4108     }
4109 
4110     // Fill in non-null argument information from the nullability
4111     // information on the parameter types (if we have them).
4112     if (Proto) {
4113       unsigned Index = 0;
4114       for (auto paramType : Proto->getParamTypes()) {
4115         if (isNonNullType(S.Context, paramType)) {
4116           if (NonNullArgs.empty())
4117             NonNullArgs.resize(Args.size());
4118 
4119           NonNullArgs.set(Index);
4120         }
4121 
4122         ++Index;
4123       }
4124     }
4125   }
4126 
4127   // Check for non-null arguments.
4128   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4129        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4130     if (NonNullArgs[ArgIndex])
4131       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4132   }
4133 }
4134 
4135 /// Handles the checks for format strings, non-POD arguments to vararg
4136 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4137 /// attributes.
4138 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4139                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4140                      bool IsMemberFunction, SourceLocation Loc,
4141                      SourceRange Range, VariadicCallType CallType) {
4142   // FIXME: We should check as much as we can in the template definition.
4143   if (CurContext->isDependentContext())
4144     return;
4145 
4146   // Printf and scanf checking.
4147   llvm::SmallBitVector CheckedVarArgs;
4148   if (FDecl) {
4149     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4150       // Only create vector if there are format attributes.
4151       CheckedVarArgs.resize(Args.size());
4152 
4153       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4154                            CheckedVarArgs);
4155     }
4156   }
4157 
4158   // Refuse POD arguments that weren't caught by the format string
4159   // checks above.
4160   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4161   if (CallType != VariadicDoesNotApply &&
4162       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4163     unsigned NumParams = Proto ? Proto->getNumParams()
4164                        : FDecl && isa<FunctionDecl>(FDecl)
4165                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4166                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4167                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4168                        : 0;
4169 
4170     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4171       // Args[ArgIdx] can be null in malformed code.
4172       if (const Expr *Arg = Args[ArgIdx]) {
4173         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4174           checkVariadicArgument(Arg, CallType);
4175       }
4176     }
4177   }
4178 
4179   if (FDecl || Proto) {
4180     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4181 
4182     // Type safety checking.
4183     if (FDecl) {
4184       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4185         CheckArgumentWithTypeTag(I, Args, Loc);
4186     }
4187   }
4188 
4189   if (FD)
4190     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4191 }
4192 
4193 /// CheckConstructorCall - Check a constructor call for correctness and safety
4194 /// properties not enforced by the C type system.
4195 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4196                                 ArrayRef<const Expr *> Args,
4197                                 const FunctionProtoType *Proto,
4198                                 SourceLocation Loc) {
4199   VariadicCallType CallType =
4200     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4201   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4202             Loc, SourceRange(), CallType);
4203 }
4204 
4205 /// CheckFunctionCall - Check a direct function call for various correctness
4206 /// and safety properties not strictly enforced by the C type system.
4207 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4208                              const FunctionProtoType *Proto) {
4209   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4210                               isa<CXXMethodDecl>(FDecl);
4211   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4212                           IsMemberOperatorCall;
4213   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4214                                                   TheCall->getCallee());
4215   Expr** Args = TheCall->getArgs();
4216   unsigned NumArgs = TheCall->getNumArgs();
4217 
4218   Expr *ImplicitThis = nullptr;
4219   if (IsMemberOperatorCall) {
4220     // If this is a call to a member operator, hide the first argument
4221     // from checkCall.
4222     // FIXME: Our choice of AST representation here is less than ideal.
4223     ImplicitThis = Args[0];
4224     ++Args;
4225     --NumArgs;
4226   } else if (IsMemberFunction)
4227     ImplicitThis =
4228         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4229 
4230   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4231             IsMemberFunction, TheCall->getRParenLoc(),
4232             TheCall->getCallee()->getSourceRange(), CallType);
4233 
4234   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4235   // None of the checks below are needed for functions that don't have
4236   // simple names (e.g., C++ conversion functions).
4237   if (!FnInfo)
4238     return false;
4239 
4240   CheckAbsoluteValueFunction(TheCall, FDecl);
4241   CheckMaxUnsignedZero(TheCall, FDecl);
4242 
4243   if (getLangOpts().ObjC)
4244     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4245 
4246   unsigned CMId = FDecl->getMemoryFunctionKind();
4247   if (CMId == 0)
4248     return false;
4249 
4250   // Handle memory setting and copying functions.
4251   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4252     CheckStrlcpycatArguments(TheCall, FnInfo);
4253   else if (CMId == Builtin::BIstrncat)
4254     CheckStrncatArguments(TheCall, FnInfo);
4255   else
4256     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4257 
4258   return false;
4259 }
4260 
4261 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4262                                ArrayRef<const Expr *> Args) {
4263   VariadicCallType CallType =
4264       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4265 
4266   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4267             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4268             CallType);
4269 
4270   return false;
4271 }
4272 
4273 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4274                             const FunctionProtoType *Proto) {
4275   QualType Ty;
4276   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4277     Ty = V->getType().getNonReferenceType();
4278   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4279     Ty = F->getType().getNonReferenceType();
4280   else
4281     return false;
4282 
4283   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4284       !Ty->isFunctionProtoType())
4285     return false;
4286 
4287   VariadicCallType CallType;
4288   if (!Proto || !Proto->isVariadic()) {
4289     CallType = VariadicDoesNotApply;
4290   } else if (Ty->isBlockPointerType()) {
4291     CallType = VariadicBlock;
4292   } else { // Ty->isFunctionPointerType()
4293     CallType = VariadicFunction;
4294   }
4295 
4296   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4297             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4298             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4299             TheCall->getCallee()->getSourceRange(), CallType);
4300 
4301   return false;
4302 }
4303 
4304 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4305 /// such as function pointers returned from functions.
4306 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4307   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4308                                                   TheCall->getCallee());
4309   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4310             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4311             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4312             TheCall->getCallee()->getSourceRange(), CallType);
4313 
4314   return false;
4315 }
4316 
4317 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4318   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4319     return false;
4320 
4321   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4322   switch (Op) {
4323   case AtomicExpr::AO__c11_atomic_init:
4324   case AtomicExpr::AO__opencl_atomic_init:
4325     llvm_unreachable("There is no ordering argument for an init");
4326 
4327   case AtomicExpr::AO__c11_atomic_load:
4328   case AtomicExpr::AO__opencl_atomic_load:
4329   case AtomicExpr::AO__atomic_load_n:
4330   case AtomicExpr::AO__atomic_load:
4331     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4332            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4333 
4334   case AtomicExpr::AO__c11_atomic_store:
4335   case AtomicExpr::AO__opencl_atomic_store:
4336   case AtomicExpr::AO__atomic_store:
4337   case AtomicExpr::AO__atomic_store_n:
4338     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4339            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4340            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4341 
4342   default:
4343     return true;
4344   }
4345 }
4346 
4347 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4348                                          AtomicExpr::AtomicOp Op) {
4349   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4350   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4351 
4352   // All the non-OpenCL operations take one of the following forms.
4353   // The OpenCL operations take the __c11 forms with one extra argument for
4354   // synchronization scope.
4355   enum {
4356     // C    __c11_atomic_init(A *, C)
4357     Init,
4358 
4359     // C    __c11_atomic_load(A *, int)
4360     Load,
4361 
4362     // void __atomic_load(A *, CP, int)
4363     LoadCopy,
4364 
4365     // void __atomic_store(A *, CP, int)
4366     Copy,
4367 
4368     // C    __c11_atomic_add(A *, M, int)
4369     Arithmetic,
4370 
4371     // C    __atomic_exchange_n(A *, CP, int)
4372     Xchg,
4373 
4374     // void __atomic_exchange(A *, C *, CP, int)
4375     GNUXchg,
4376 
4377     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4378     C11CmpXchg,
4379 
4380     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4381     GNUCmpXchg
4382   } Form = Init;
4383 
4384   const unsigned NumForm = GNUCmpXchg + 1;
4385   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4386   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4387   // where:
4388   //   C is an appropriate type,
4389   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4390   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4391   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4392   //   the int parameters are for orderings.
4393 
4394   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4395       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4396       "need to update code for modified forms");
4397   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4398                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4399                         AtomicExpr::AO__atomic_load,
4400                 "need to update code for modified C11 atomics");
4401   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4402                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4403   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4404                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4405                IsOpenCL;
4406   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4407              Op == AtomicExpr::AO__atomic_store_n ||
4408              Op == AtomicExpr::AO__atomic_exchange_n ||
4409              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4410   bool IsAddSub = false;
4411   bool IsMinMax = false;
4412 
4413   switch (Op) {
4414   case AtomicExpr::AO__c11_atomic_init:
4415   case AtomicExpr::AO__opencl_atomic_init:
4416     Form = Init;
4417     break;
4418 
4419   case AtomicExpr::AO__c11_atomic_load:
4420   case AtomicExpr::AO__opencl_atomic_load:
4421   case AtomicExpr::AO__atomic_load_n:
4422     Form = Load;
4423     break;
4424 
4425   case AtomicExpr::AO__atomic_load:
4426     Form = LoadCopy;
4427     break;
4428 
4429   case AtomicExpr::AO__c11_atomic_store:
4430   case AtomicExpr::AO__opencl_atomic_store:
4431   case AtomicExpr::AO__atomic_store:
4432   case AtomicExpr::AO__atomic_store_n:
4433     Form = Copy;
4434     break;
4435 
4436   case AtomicExpr::AO__c11_atomic_fetch_add:
4437   case AtomicExpr::AO__c11_atomic_fetch_sub:
4438   case AtomicExpr::AO__opencl_atomic_fetch_add:
4439   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4440   case AtomicExpr::AO__opencl_atomic_fetch_min:
4441   case AtomicExpr::AO__opencl_atomic_fetch_max:
4442   case AtomicExpr::AO__atomic_fetch_add:
4443   case AtomicExpr::AO__atomic_fetch_sub:
4444   case AtomicExpr::AO__atomic_add_fetch:
4445   case AtomicExpr::AO__atomic_sub_fetch:
4446     IsAddSub = true;
4447     LLVM_FALLTHROUGH;
4448   case AtomicExpr::AO__c11_atomic_fetch_and:
4449   case AtomicExpr::AO__c11_atomic_fetch_or:
4450   case AtomicExpr::AO__c11_atomic_fetch_xor:
4451   case AtomicExpr::AO__opencl_atomic_fetch_and:
4452   case AtomicExpr::AO__opencl_atomic_fetch_or:
4453   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4454   case AtomicExpr::AO__atomic_fetch_and:
4455   case AtomicExpr::AO__atomic_fetch_or:
4456   case AtomicExpr::AO__atomic_fetch_xor:
4457   case AtomicExpr::AO__atomic_fetch_nand:
4458   case AtomicExpr::AO__atomic_and_fetch:
4459   case AtomicExpr::AO__atomic_or_fetch:
4460   case AtomicExpr::AO__atomic_xor_fetch:
4461   case AtomicExpr::AO__atomic_nand_fetch:
4462     Form = Arithmetic;
4463     break;
4464 
4465   case AtomicExpr::AO__atomic_fetch_min:
4466   case AtomicExpr::AO__atomic_fetch_max:
4467     IsMinMax = true;
4468     Form = Arithmetic;
4469     break;
4470 
4471   case AtomicExpr::AO__c11_atomic_exchange:
4472   case AtomicExpr::AO__opencl_atomic_exchange:
4473   case AtomicExpr::AO__atomic_exchange_n:
4474     Form = Xchg;
4475     break;
4476 
4477   case AtomicExpr::AO__atomic_exchange:
4478     Form = GNUXchg;
4479     break;
4480 
4481   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4482   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4483   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4484   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4485     Form = C11CmpXchg;
4486     break;
4487 
4488   case AtomicExpr::AO__atomic_compare_exchange:
4489   case AtomicExpr::AO__atomic_compare_exchange_n:
4490     Form = GNUCmpXchg;
4491     break;
4492   }
4493 
4494   unsigned AdjustedNumArgs = NumArgs[Form];
4495   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4496     ++AdjustedNumArgs;
4497   // Check we have the right number of arguments.
4498   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4499     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4500         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4501         << TheCall->getCallee()->getSourceRange();
4502     return ExprError();
4503   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4504     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4505          diag::err_typecheck_call_too_many_args)
4506         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4507         << TheCall->getCallee()->getSourceRange();
4508     return ExprError();
4509   }
4510 
4511   // Inspect the first argument of the atomic operation.
4512   Expr *Ptr = TheCall->getArg(0);
4513   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4514   if (ConvertedPtr.isInvalid())
4515     return ExprError();
4516 
4517   Ptr = ConvertedPtr.get();
4518   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4519   if (!pointerType) {
4520     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4521         << Ptr->getType() << Ptr->getSourceRange();
4522     return ExprError();
4523   }
4524 
4525   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4526   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4527   QualType ValType = AtomTy; // 'C'
4528   if (IsC11) {
4529     if (!AtomTy->isAtomicType()) {
4530       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4531           << Ptr->getType() << Ptr->getSourceRange();
4532       return ExprError();
4533     }
4534     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4535         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4536       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4537           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4538           << Ptr->getSourceRange();
4539       return ExprError();
4540     }
4541     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4542   } else if (Form != Load && Form != LoadCopy) {
4543     if (ValType.isConstQualified()) {
4544       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4545           << Ptr->getType() << Ptr->getSourceRange();
4546       return ExprError();
4547     }
4548   }
4549 
4550   // For an arithmetic operation, the implied arithmetic must be well-formed.
4551   if (Form == Arithmetic) {
4552     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4553     if (IsAddSub && !ValType->isIntegerType()
4554         && !ValType->isPointerType()) {
4555       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4556           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4557       return ExprError();
4558     }
4559     if (IsMinMax) {
4560       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4561       if (!BT || (BT->getKind() != BuiltinType::Int &&
4562                   BT->getKind() != BuiltinType::UInt)) {
4563         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4564         return ExprError();
4565       }
4566     }
4567     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4568       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4569           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4570       return ExprError();
4571     }
4572     if (IsC11 && ValType->isPointerType() &&
4573         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4574                             diag::err_incomplete_type)) {
4575       return ExprError();
4576     }
4577   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4578     // For __atomic_*_n operations, the value type must be a scalar integral or
4579     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4580     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4581         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4582     return ExprError();
4583   }
4584 
4585   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4586       !AtomTy->isScalarType()) {
4587     // For GNU atomics, require a trivially-copyable type. This is not part of
4588     // the GNU atomics specification, but we enforce it for sanity.
4589     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4590         << Ptr->getType() << Ptr->getSourceRange();
4591     return ExprError();
4592   }
4593 
4594   switch (ValType.getObjCLifetime()) {
4595   case Qualifiers::OCL_None:
4596   case Qualifiers::OCL_ExplicitNone:
4597     // okay
4598     break;
4599 
4600   case Qualifiers::OCL_Weak:
4601   case Qualifiers::OCL_Strong:
4602   case Qualifiers::OCL_Autoreleasing:
4603     // FIXME: Can this happen? By this point, ValType should be known
4604     // to be trivially copyable.
4605     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4606         << ValType << Ptr->getSourceRange();
4607     return ExprError();
4608   }
4609 
4610   // All atomic operations have an overload which takes a pointer to a volatile
4611   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4612   // into the result or the other operands. Similarly atomic_load takes a
4613   // pointer to a const 'A'.
4614   ValType.removeLocalVolatile();
4615   ValType.removeLocalConst();
4616   QualType ResultType = ValType;
4617   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4618       Form == Init)
4619     ResultType = Context.VoidTy;
4620   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4621     ResultType = Context.BoolTy;
4622 
4623   // The type of a parameter passed 'by value'. In the GNU atomics, such
4624   // arguments are actually passed as pointers.
4625   QualType ByValType = ValType; // 'CP'
4626   bool IsPassedByAddress = false;
4627   if (!IsC11 && !IsN) {
4628     ByValType = Ptr->getType();
4629     IsPassedByAddress = true;
4630   }
4631 
4632   // The first argument's non-CV pointer type is used to deduce the type of
4633   // subsequent arguments, except for:
4634   //  - weak flag (always converted to bool)
4635   //  - memory order (always converted to int)
4636   //  - scope  (always converted to int)
4637   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4638     QualType Ty;
4639     if (i < NumVals[Form] + 1) {
4640       switch (i) {
4641       case 0:
4642         // The first argument is always a pointer. It has a fixed type.
4643         // It is always dereferenced, a nullptr is undefined.
4644         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4645         // Nothing else to do: we already know all we want about this pointer.
4646         continue;
4647       case 1:
4648         // The second argument is the non-atomic operand. For arithmetic, this
4649         // is always passed by value, and for a compare_exchange it is always
4650         // passed by address. For the rest, GNU uses by-address and C11 uses
4651         // by-value.
4652         assert(Form != Load);
4653         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4654           Ty = ValType;
4655         else if (Form == Copy || Form == Xchg) {
4656           if (IsPassedByAddress)
4657             // The value pointer is always dereferenced, a nullptr is undefined.
4658             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4659           Ty = ByValType;
4660         } else if (Form == Arithmetic)
4661           Ty = Context.getPointerDiffType();
4662         else {
4663           Expr *ValArg = TheCall->getArg(i);
4664           // The value pointer is always dereferenced, a nullptr is undefined.
4665           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4666           LangAS AS = LangAS::Default;
4667           // Keep address space of non-atomic pointer type.
4668           if (const PointerType *PtrTy =
4669                   ValArg->getType()->getAs<PointerType>()) {
4670             AS = PtrTy->getPointeeType().getAddressSpace();
4671           }
4672           Ty = Context.getPointerType(
4673               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4674         }
4675         break;
4676       case 2:
4677         // The third argument to compare_exchange / GNU exchange is the desired
4678         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4679         if (IsPassedByAddress)
4680           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4681         Ty = ByValType;
4682         break;
4683       case 3:
4684         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4685         Ty = Context.BoolTy;
4686         break;
4687       }
4688     } else {
4689       // The order(s) and scope are always converted to int.
4690       Ty = Context.IntTy;
4691     }
4692 
4693     InitializedEntity Entity =
4694         InitializedEntity::InitializeParameter(Context, Ty, false);
4695     ExprResult Arg = TheCall->getArg(i);
4696     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4697     if (Arg.isInvalid())
4698       return true;
4699     TheCall->setArg(i, Arg.get());
4700   }
4701 
4702   // Permute the arguments into a 'consistent' order.
4703   SmallVector<Expr*, 5> SubExprs;
4704   SubExprs.push_back(Ptr);
4705   switch (Form) {
4706   case Init:
4707     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4708     SubExprs.push_back(TheCall->getArg(1)); // Val1
4709     break;
4710   case Load:
4711     SubExprs.push_back(TheCall->getArg(1)); // Order
4712     break;
4713   case LoadCopy:
4714   case Copy:
4715   case Arithmetic:
4716   case Xchg:
4717     SubExprs.push_back(TheCall->getArg(2)); // Order
4718     SubExprs.push_back(TheCall->getArg(1)); // Val1
4719     break;
4720   case GNUXchg:
4721     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4722     SubExprs.push_back(TheCall->getArg(3)); // Order
4723     SubExprs.push_back(TheCall->getArg(1)); // Val1
4724     SubExprs.push_back(TheCall->getArg(2)); // Val2
4725     break;
4726   case C11CmpXchg:
4727     SubExprs.push_back(TheCall->getArg(3)); // Order
4728     SubExprs.push_back(TheCall->getArg(1)); // Val1
4729     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4730     SubExprs.push_back(TheCall->getArg(2)); // Val2
4731     break;
4732   case GNUCmpXchg:
4733     SubExprs.push_back(TheCall->getArg(4)); // Order
4734     SubExprs.push_back(TheCall->getArg(1)); // Val1
4735     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4736     SubExprs.push_back(TheCall->getArg(2)); // Val2
4737     SubExprs.push_back(TheCall->getArg(3)); // Weak
4738     break;
4739   }
4740 
4741   if (SubExprs.size() >= 2 && Form != Init) {
4742     llvm::APSInt Result(32);
4743     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4744         !isValidOrderingForOp(Result.getSExtValue(), Op))
4745       Diag(SubExprs[1]->getBeginLoc(),
4746            diag::warn_atomic_op_has_invalid_memory_order)
4747           << SubExprs[1]->getSourceRange();
4748   }
4749 
4750   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4751     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4752     llvm::APSInt Result(32);
4753     if (Scope->isIntegerConstantExpr(Result, Context) &&
4754         !ScopeModel->isValid(Result.getZExtValue())) {
4755       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4756           << Scope->getSourceRange();
4757     }
4758     SubExprs.push_back(Scope);
4759   }
4760 
4761   AtomicExpr *AE =
4762       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4763                                ResultType, Op, TheCall->getRParenLoc());
4764 
4765   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4766        Op == AtomicExpr::AO__c11_atomic_store ||
4767        Op == AtomicExpr::AO__opencl_atomic_load ||
4768        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4769       Context.AtomicUsesUnsupportedLibcall(AE))
4770     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4771         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4772              Op == AtomicExpr::AO__opencl_atomic_load)
4773                 ? 0
4774                 : 1);
4775 
4776   return AE;
4777 }
4778 
4779 /// checkBuiltinArgument - Given a call to a builtin function, perform
4780 /// normal type-checking on the given argument, updating the call in
4781 /// place.  This is useful when a builtin function requires custom
4782 /// type-checking for some of its arguments but not necessarily all of
4783 /// them.
4784 ///
4785 /// Returns true on error.
4786 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4787   FunctionDecl *Fn = E->getDirectCallee();
4788   assert(Fn && "builtin call without direct callee!");
4789 
4790   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4791   InitializedEntity Entity =
4792     InitializedEntity::InitializeParameter(S.Context, Param);
4793 
4794   ExprResult Arg = E->getArg(0);
4795   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4796   if (Arg.isInvalid())
4797     return true;
4798 
4799   E->setArg(ArgIndex, Arg.get());
4800   return false;
4801 }
4802 
4803 /// We have a call to a function like __sync_fetch_and_add, which is an
4804 /// overloaded function based on the pointer type of its first argument.
4805 /// The main ActOnCallExpr routines have already promoted the types of
4806 /// arguments because all of these calls are prototyped as void(...).
4807 ///
4808 /// This function goes through and does final semantic checking for these
4809 /// builtins, as well as generating any warnings.
4810 ExprResult
4811 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4812   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4813   Expr *Callee = TheCall->getCallee();
4814   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4815   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4816 
4817   // Ensure that we have at least one argument to do type inference from.
4818   if (TheCall->getNumArgs() < 1) {
4819     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4820         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4821     return ExprError();
4822   }
4823 
4824   // Inspect the first argument of the atomic builtin.  This should always be
4825   // a pointer type, whose element is an integral scalar or pointer type.
4826   // Because it is a pointer type, we don't have to worry about any implicit
4827   // casts here.
4828   // FIXME: We don't allow floating point scalars as input.
4829   Expr *FirstArg = TheCall->getArg(0);
4830   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4831   if (FirstArgResult.isInvalid())
4832     return ExprError();
4833   FirstArg = FirstArgResult.get();
4834   TheCall->setArg(0, FirstArg);
4835 
4836   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4837   if (!pointerType) {
4838     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4839         << FirstArg->getType() << FirstArg->getSourceRange();
4840     return ExprError();
4841   }
4842 
4843   QualType ValType = pointerType->getPointeeType();
4844   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4845       !ValType->isBlockPointerType()) {
4846     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4847         << FirstArg->getType() << FirstArg->getSourceRange();
4848     return ExprError();
4849   }
4850 
4851   if (ValType.isConstQualified()) {
4852     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4853         << FirstArg->getType() << FirstArg->getSourceRange();
4854     return ExprError();
4855   }
4856 
4857   switch (ValType.getObjCLifetime()) {
4858   case Qualifiers::OCL_None:
4859   case Qualifiers::OCL_ExplicitNone:
4860     // okay
4861     break;
4862 
4863   case Qualifiers::OCL_Weak:
4864   case Qualifiers::OCL_Strong:
4865   case Qualifiers::OCL_Autoreleasing:
4866     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4867         << ValType << FirstArg->getSourceRange();
4868     return ExprError();
4869   }
4870 
4871   // Strip any qualifiers off ValType.
4872   ValType = ValType.getUnqualifiedType();
4873 
4874   // The majority of builtins return a value, but a few have special return
4875   // types, so allow them to override appropriately below.
4876   QualType ResultType = ValType;
4877 
4878   // We need to figure out which concrete builtin this maps onto.  For example,
4879   // __sync_fetch_and_add with a 2 byte object turns into
4880   // __sync_fetch_and_add_2.
4881 #define BUILTIN_ROW(x) \
4882   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4883     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4884 
4885   static const unsigned BuiltinIndices[][5] = {
4886     BUILTIN_ROW(__sync_fetch_and_add),
4887     BUILTIN_ROW(__sync_fetch_and_sub),
4888     BUILTIN_ROW(__sync_fetch_and_or),
4889     BUILTIN_ROW(__sync_fetch_and_and),
4890     BUILTIN_ROW(__sync_fetch_and_xor),
4891     BUILTIN_ROW(__sync_fetch_and_nand),
4892 
4893     BUILTIN_ROW(__sync_add_and_fetch),
4894     BUILTIN_ROW(__sync_sub_and_fetch),
4895     BUILTIN_ROW(__sync_and_and_fetch),
4896     BUILTIN_ROW(__sync_or_and_fetch),
4897     BUILTIN_ROW(__sync_xor_and_fetch),
4898     BUILTIN_ROW(__sync_nand_and_fetch),
4899 
4900     BUILTIN_ROW(__sync_val_compare_and_swap),
4901     BUILTIN_ROW(__sync_bool_compare_and_swap),
4902     BUILTIN_ROW(__sync_lock_test_and_set),
4903     BUILTIN_ROW(__sync_lock_release),
4904     BUILTIN_ROW(__sync_swap)
4905   };
4906 #undef BUILTIN_ROW
4907 
4908   // Determine the index of the size.
4909   unsigned SizeIndex;
4910   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4911   case 1: SizeIndex = 0; break;
4912   case 2: SizeIndex = 1; break;
4913   case 4: SizeIndex = 2; break;
4914   case 8: SizeIndex = 3; break;
4915   case 16: SizeIndex = 4; break;
4916   default:
4917     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4918         << FirstArg->getType() << FirstArg->getSourceRange();
4919     return ExprError();
4920   }
4921 
4922   // Each of these builtins has one pointer argument, followed by some number of
4923   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4924   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4925   // as the number of fixed args.
4926   unsigned BuiltinID = FDecl->getBuiltinID();
4927   unsigned BuiltinIndex, NumFixed = 1;
4928   bool WarnAboutSemanticsChange = false;
4929   switch (BuiltinID) {
4930   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4931   case Builtin::BI__sync_fetch_and_add:
4932   case Builtin::BI__sync_fetch_and_add_1:
4933   case Builtin::BI__sync_fetch_and_add_2:
4934   case Builtin::BI__sync_fetch_and_add_4:
4935   case Builtin::BI__sync_fetch_and_add_8:
4936   case Builtin::BI__sync_fetch_and_add_16:
4937     BuiltinIndex = 0;
4938     break;
4939 
4940   case Builtin::BI__sync_fetch_and_sub:
4941   case Builtin::BI__sync_fetch_and_sub_1:
4942   case Builtin::BI__sync_fetch_and_sub_2:
4943   case Builtin::BI__sync_fetch_and_sub_4:
4944   case Builtin::BI__sync_fetch_and_sub_8:
4945   case Builtin::BI__sync_fetch_and_sub_16:
4946     BuiltinIndex = 1;
4947     break;
4948 
4949   case Builtin::BI__sync_fetch_and_or:
4950   case Builtin::BI__sync_fetch_and_or_1:
4951   case Builtin::BI__sync_fetch_and_or_2:
4952   case Builtin::BI__sync_fetch_and_or_4:
4953   case Builtin::BI__sync_fetch_and_or_8:
4954   case Builtin::BI__sync_fetch_and_or_16:
4955     BuiltinIndex = 2;
4956     break;
4957 
4958   case Builtin::BI__sync_fetch_and_and:
4959   case Builtin::BI__sync_fetch_and_and_1:
4960   case Builtin::BI__sync_fetch_and_and_2:
4961   case Builtin::BI__sync_fetch_and_and_4:
4962   case Builtin::BI__sync_fetch_and_and_8:
4963   case Builtin::BI__sync_fetch_and_and_16:
4964     BuiltinIndex = 3;
4965     break;
4966 
4967   case Builtin::BI__sync_fetch_and_xor:
4968   case Builtin::BI__sync_fetch_and_xor_1:
4969   case Builtin::BI__sync_fetch_and_xor_2:
4970   case Builtin::BI__sync_fetch_and_xor_4:
4971   case Builtin::BI__sync_fetch_and_xor_8:
4972   case Builtin::BI__sync_fetch_and_xor_16:
4973     BuiltinIndex = 4;
4974     break;
4975 
4976   case Builtin::BI__sync_fetch_and_nand:
4977   case Builtin::BI__sync_fetch_and_nand_1:
4978   case Builtin::BI__sync_fetch_and_nand_2:
4979   case Builtin::BI__sync_fetch_and_nand_4:
4980   case Builtin::BI__sync_fetch_and_nand_8:
4981   case Builtin::BI__sync_fetch_and_nand_16:
4982     BuiltinIndex = 5;
4983     WarnAboutSemanticsChange = true;
4984     break;
4985 
4986   case Builtin::BI__sync_add_and_fetch:
4987   case Builtin::BI__sync_add_and_fetch_1:
4988   case Builtin::BI__sync_add_and_fetch_2:
4989   case Builtin::BI__sync_add_and_fetch_4:
4990   case Builtin::BI__sync_add_and_fetch_8:
4991   case Builtin::BI__sync_add_and_fetch_16:
4992     BuiltinIndex = 6;
4993     break;
4994 
4995   case Builtin::BI__sync_sub_and_fetch:
4996   case Builtin::BI__sync_sub_and_fetch_1:
4997   case Builtin::BI__sync_sub_and_fetch_2:
4998   case Builtin::BI__sync_sub_and_fetch_4:
4999   case Builtin::BI__sync_sub_and_fetch_8:
5000   case Builtin::BI__sync_sub_and_fetch_16:
5001     BuiltinIndex = 7;
5002     break;
5003 
5004   case Builtin::BI__sync_and_and_fetch:
5005   case Builtin::BI__sync_and_and_fetch_1:
5006   case Builtin::BI__sync_and_and_fetch_2:
5007   case Builtin::BI__sync_and_and_fetch_4:
5008   case Builtin::BI__sync_and_and_fetch_8:
5009   case Builtin::BI__sync_and_and_fetch_16:
5010     BuiltinIndex = 8;
5011     break;
5012 
5013   case Builtin::BI__sync_or_and_fetch:
5014   case Builtin::BI__sync_or_and_fetch_1:
5015   case Builtin::BI__sync_or_and_fetch_2:
5016   case Builtin::BI__sync_or_and_fetch_4:
5017   case Builtin::BI__sync_or_and_fetch_8:
5018   case Builtin::BI__sync_or_and_fetch_16:
5019     BuiltinIndex = 9;
5020     break;
5021 
5022   case Builtin::BI__sync_xor_and_fetch:
5023   case Builtin::BI__sync_xor_and_fetch_1:
5024   case Builtin::BI__sync_xor_and_fetch_2:
5025   case Builtin::BI__sync_xor_and_fetch_4:
5026   case Builtin::BI__sync_xor_and_fetch_8:
5027   case Builtin::BI__sync_xor_and_fetch_16:
5028     BuiltinIndex = 10;
5029     break;
5030 
5031   case Builtin::BI__sync_nand_and_fetch:
5032   case Builtin::BI__sync_nand_and_fetch_1:
5033   case Builtin::BI__sync_nand_and_fetch_2:
5034   case Builtin::BI__sync_nand_and_fetch_4:
5035   case Builtin::BI__sync_nand_and_fetch_8:
5036   case Builtin::BI__sync_nand_and_fetch_16:
5037     BuiltinIndex = 11;
5038     WarnAboutSemanticsChange = true;
5039     break;
5040 
5041   case Builtin::BI__sync_val_compare_and_swap:
5042   case Builtin::BI__sync_val_compare_and_swap_1:
5043   case Builtin::BI__sync_val_compare_and_swap_2:
5044   case Builtin::BI__sync_val_compare_and_swap_4:
5045   case Builtin::BI__sync_val_compare_and_swap_8:
5046   case Builtin::BI__sync_val_compare_and_swap_16:
5047     BuiltinIndex = 12;
5048     NumFixed = 2;
5049     break;
5050 
5051   case Builtin::BI__sync_bool_compare_and_swap:
5052   case Builtin::BI__sync_bool_compare_and_swap_1:
5053   case Builtin::BI__sync_bool_compare_and_swap_2:
5054   case Builtin::BI__sync_bool_compare_and_swap_4:
5055   case Builtin::BI__sync_bool_compare_and_swap_8:
5056   case Builtin::BI__sync_bool_compare_and_swap_16:
5057     BuiltinIndex = 13;
5058     NumFixed = 2;
5059     ResultType = Context.BoolTy;
5060     break;
5061 
5062   case Builtin::BI__sync_lock_test_and_set:
5063   case Builtin::BI__sync_lock_test_and_set_1:
5064   case Builtin::BI__sync_lock_test_and_set_2:
5065   case Builtin::BI__sync_lock_test_and_set_4:
5066   case Builtin::BI__sync_lock_test_and_set_8:
5067   case Builtin::BI__sync_lock_test_and_set_16:
5068     BuiltinIndex = 14;
5069     break;
5070 
5071   case Builtin::BI__sync_lock_release:
5072   case Builtin::BI__sync_lock_release_1:
5073   case Builtin::BI__sync_lock_release_2:
5074   case Builtin::BI__sync_lock_release_4:
5075   case Builtin::BI__sync_lock_release_8:
5076   case Builtin::BI__sync_lock_release_16:
5077     BuiltinIndex = 15;
5078     NumFixed = 0;
5079     ResultType = Context.VoidTy;
5080     break;
5081 
5082   case Builtin::BI__sync_swap:
5083   case Builtin::BI__sync_swap_1:
5084   case Builtin::BI__sync_swap_2:
5085   case Builtin::BI__sync_swap_4:
5086   case Builtin::BI__sync_swap_8:
5087   case Builtin::BI__sync_swap_16:
5088     BuiltinIndex = 16;
5089     break;
5090   }
5091 
5092   // Now that we know how many fixed arguments we expect, first check that we
5093   // have at least that many.
5094   if (TheCall->getNumArgs() < 1+NumFixed) {
5095     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5096         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5097         << Callee->getSourceRange();
5098     return ExprError();
5099   }
5100 
5101   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5102       << Callee->getSourceRange();
5103 
5104   if (WarnAboutSemanticsChange) {
5105     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5106         << Callee->getSourceRange();
5107   }
5108 
5109   // Get the decl for the concrete builtin from this, we can tell what the
5110   // concrete integer type we should convert to is.
5111   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5112   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5113   FunctionDecl *NewBuiltinDecl;
5114   if (NewBuiltinID == BuiltinID)
5115     NewBuiltinDecl = FDecl;
5116   else {
5117     // Perform builtin lookup to avoid redeclaring it.
5118     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5119     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5120     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5121     assert(Res.getFoundDecl());
5122     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5123     if (!NewBuiltinDecl)
5124       return ExprError();
5125   }
5126 
5127   // The first argument --- the pointer --- has a fixed type; we
5128   // deduce the types of the rest of the arguments accordingly.  Walk
5129   // the remaining arguments, converting them to the deduced value type.
5130   for (unsigned i = 0; i != NumFixed; ++i) {
5131     ExprResult Arg = TheCall->getArg(i+1);
5132 
5133     // GCC does an implicit conversion to the pointer or integer ValType.  This
5134     // can fail in some cases (1i -> int**), check for this error case now.
5135     // Initialize the argument.
5136     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5137                                                    ValType, /*consume*/ false);
5138     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5139     if (Arg.isInvalid())
5140       return ExprError();
5141 
5142     // Okay, we have something that *can* be converted to the right type.  Check
5143     // to see if there is a potentially weird extension going on here.  This can
5144     // happen when you do an atomic operation on something like an char* and
5145     // pass in 42.  The 42 gets converted to char.  This is even more strange
5146     // for things like 45.123 -> char, etc.
5147     // FIXME: Do this check.
5148     TheCall->setArg(i+1, Arg.get());
5149   }
5150 
5151   ASTContext& Context = this->getASTContext();
5152 
5153   // Create a new DeclRefExpr to refer to the new decl.
5154   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5155       Context,
5156       DRE->getQualifierLoc(),
5157       SourceLocation(),
5158       NewBuiltinDecl,
5159       /*enclosing*/ false,
5160       DRE->getLocation(),
5161       Context.BuiltinFnTy,
5162       DRE->getValueKind());
5163 
5164   // Set the callee in the CallExpr.
5165   // FIXME: This loses syntactic information.
5166   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5167   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5168                                               CK_BuiltinFnToFnPtr);
5169   TheCall->setCallee(PromotedCall.get());
5170 
5171   // Change the result type of the call to match the original value type. This
5172   // is arbitrary, but the codegen for these builtins ins design to handle it
5173   // gracefully.
5174   TheCall->setType(ResultType);
5175 
5176   return TheCallResult;
5177 }
5178 
5179 /// SemaBuiltinNontemporalOverloaded - We have a call to
5180 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5181 /// overloaded function based on the pointer type of its last argument.
5182 ///
5183 /// This function goes through and does final semantic checking for these
5184 /// builtins.
5185 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5186   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5187   DeclRefExpr *DRE =
5188       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5189   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5190   unsigned BuiltinID = FDecl->getBuiltinID();
5191   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5192           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5193          "Unexpected nontemporal load/store builtin!");
5194   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5195   unsigned numArgs = isStore ? 2 : 1;
5196 
5197   // Ensure that we have the proper number of arguments.
5198   if (checkArgCount(*this, TheCall, numArgs))
5199     return ExprError();
5200 
5201   // Inspect the last argument of the nontemporal builtin.  This should always
5202   // be a pointer type, from which we imply the type of the memory access.
5203   // Because it is a pointer type, we don't have to worry about any implicit
5204   // casts here.
5205   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5206   ExprResult PointerArgResult =
5207       DefaultFunctionArrayLvalueConversion(PointerArg);
5208 
5209   if (PointerArgResult.isInvalid())
5210     return ExprError();
5211   PointerArg = PointerArgResult.get();
5212   TheCall->setArg(numArgs - 1, PointerArg);
5213 
5214   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5215   if (!pointerType) {
5216     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5217         << PointerArg->getType() << PointerArg->getSourceRange();
5218     return ExprError();
5219   }
5220 
5221   QualType ValType = pointerType->getPointeeType();
5222 
5223   // Strip any qualifiers off ValType.
5224   ValType = ValType.getUnqualifiedType();
5225   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5226       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5227       !ValType->isVectorType()) {
5228     Diag(DRE->getBeginLoc(),
5229          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5230         << PointerArg->getType() << PointerArg->getSourceRange();
5231     return ExprError();
5232   }
5233 
5234   if (!isStore) {
5235     TheCall->setType(ValType);
5236     return TheCallResult;
5237   }
5238 
5239   ExprResult ValArg = TheCall->getArg(0);
5240   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5241       Context, ValType, /*consume*/ false);
5242   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5243   if (ValArg.isInvalid())
5244     return ExprError();
5245 
5246   TheCall->setArg(0, ValArg.get());
5247   TheCall->setType(Context.VoidTy);
5248   return TheCallResult;
5249 }
5250 
5251 /// CheckObjCString - Checks that the argument to the builtin
5252 /// CFString constructor is correct
5253 /// Note: It might also make sense to do the UTF-16 conversion here (would
5254 /// simplify the backend).
5255 bool Sema::CheckObjCString(Expr *Arg) {
5256   Arg = Arg->IgnoreParenCasts();
5257   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5258 
5259   if (!Literal || !Literal->isAscii()) {
5260     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5261         << Arg->getSourceRange();
5262     return true;
5263   }
5264 
5265   if (Literal->containsNonAsciiOrNull()) {
5266     StringRef String = Literal->getString();
5267     unsigned NumBytes = String.size();
5268     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5269     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5270     llvm::UTF16 *ToPtr = &ToBuf[0];
5271 
5272     llvm::ConversionResult Result =
5273         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5274                                  ToPtr + NumBytes, llvm::strictConversion);
5275     // Check for conversion failure.
5276     if (Result != llvm::conversionOK)
5277       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5278           << Arg->getSourceRange();
5279   }
5280   return false;
5281 }
5282 
5283 /// CheckObjCString - Checks that the format string argument to the os_log()
5284 /// and os_trace() functions is correct, and converts it to const char *.
5285 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5286   Arg = Arg->IgnoreParenCasts();
5287   auto *Literal = dyn_cast<StringLiteral>(Arg);
5288   if (!Literal) {
5289     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5290       Literal = ObjcLiteral->getString();
5291     }
5292   }
5293 
5294   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5295     return ExprError(
5296         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5297         << Arg->getSourceRange());
5298   }
5299 
5300   ExprResult Result(Literal);
5301   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5302   InitializedEntity Entity =
5303       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5304   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5305   return Result;
5306 }
5307 
5308 /// Check that the user is calling the appropriate va_start builtin for the
5309 /// target and calling convention.
5310 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5311   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5312   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5313   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5314   bool IsWindows = TT.isOSWindows();
5315   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5316   if (IsX64 || IsAArch64) {
5317     CallingConv CC = CC_C;
5318     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5319       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5320     if (IsMSVAStart) {
5321       // Don't allow this in System V ABI functions.
5322       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5323         return S.Diag(Fn->getBeginLoc(),
5324                       diag::err_ms_va_start_used_in_sysv_function);
5325     } else {
5326       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5327       // On x64 Windows, don't allow this in System V ABI functions.
5328       // (Yes, that means there's no corresponding way to support variadic
5329       // System V ABI functions on Windows.)
5330       if ((IsWindows && CC == CC_X86_64SysV) ||
5331           (!IsWindows && CC == CC_Win64))
5332         return S.Diag(Fn->getBeginLoc(),
5333                       diag::err_va_start_used_in_wrong_abi_function)
5334                << !IsWindows;
5335     }
5336     return false;
5337   }
5338 
5339   if (IsMSVAStart)
5340     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5341   return false;
5342 }
5343 
5344 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5345                                              ParmVarDecl **LastParam = nullptr) {
5346   // Determine whether the current function, block, or obj-c method is variadic
5347   // and get its parameter list.
5348   bool IsVariadic = false;
5349   ArrayRef<ParmVarDecl *> Params;
5350   DeclContext *Caller = S.CurContext;
5351   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5352     IsVariadic = Block->isVariadic();
5353     Params = Block->parameters();
5354   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5355     IsVariadic = FD->isVariadic();
5356     Params = FD->parameters();
5357   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5358     IsVariadic = MD->isVariadic();
5359     // FIXME: This isn't correct for methods (results in bogus warning).
5360     Params = MD->parameters();
5361   } else if (isa<CapturedDecl>(Caller)) {
5362     // We don't support va_start in a CapturedDecl.
5363     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5364     return true;
5365   } else {
5366     // This must be some other declcontext that parses exprs.
5367     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5368     return true;
5369   }
5370 
5371   if (!IsVariadic) {
5372     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5373     return true;
5374   }
5375 
5376   if (LastParam)
5377     *LastParam = Params.empty() ? nullptr : Params.back();
5378 
5379   return false;
5380 }
5381 
5382 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5383 /// for validity.  Emit an error and return true on failure; return false
5384 /// on success.
5385 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5386   Expr *Fn = TheCall->getCallee();
5387 
5388   if (checkVAStartABI(*this, BuiltinID, Fn))
5389     return true;
5390 
5391   if (TheCall->getNumArgs() > 2) {
5392     Diag(TheCall->getArg(2)->getBeginLoc(),
5393          diag::err_typecheck_call_too_many_args)
5394         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5395         << Fn->getSourceRange()
5396         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5397                        (*(TheCall->arg_end() - 1))->getEndLoc());
5398     return true;
5399   }
5400 
5401   if (TheCall->getNumArgs() < 2) {
5402     return Diag(TheCall->getEndLoc(),
5403                 diag::err_typecheck_call_too_few_args_at_least)
5404            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5405   }
5406 
5407   // Type-check the first argument normally.
5408   if (checkBuiltinArgument(*this, TheCall, 0))
5409     return true;
5410 
5411   // Check that the current function is variadic, and get its last parameter.
5412   ParmVarDecl *LastParam;
5413   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5414     return true;
5415 
5416   // Verify that the second argument to the builtin is the last argument of the
5417   // current function or method.
5418   bool SecondArgIsLastNamedArgument = false;
5419   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5420 
5421   // These are valid if SecondArgIsLastNamedArgument is false after the next
5422   // block.
5423   QualType Type;
5424   SourceLocation ParamLoc;
5425   bool IsCRegister = false;
5426 
5427   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5428     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5429       SecondArgIsLastNamedArgument = PV == LastParam;
5430 
5431       Type = PV->getType();
5432       ParamLoc = PV->getLocation();
5433       IsCRegister =
5434           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5435     }
5436   }
5437 
5438   if (!SecondArgIsLastNamedArgument)
5439     Diag(TheCall->getArg(1)->getBeginLoc(),
5440          diag::warn_second_arg_of_va_start_not_last_named_param);
5441   else if (IsCRegister || Type->isReferenceType() ||
5442            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5443              // Promotable integers are UB, but enumerations need a bit of
5444              // extra checking to see what their promotable type actually is.
5445              if (!Type->isPromotableIntegerType())
5446                return false;
5447              if (!Type->isEnumeralType())
5448                return true;
5449              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5450              return !(ED &&
5451                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5452            }()) {
5453     unsigned Reason = 0;
5454     if (Type->isReferenceType())  Reason = 1;
5455     else if (IsCRegister)         Reason = 2;
5456     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5457     Diag(ParamLoc, diag::note_parameter_type) << Type;
5458   }
5459 
5460   TheCall->setType(Context.VoidTy);
5461   return false;
5462 }
5463 
5464 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5465   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5466   //                 const char *named_addr);
5467 
5468   Expr *Func = Call->getCallee();
5469 
5470   if (Call->getNumArgs() < 3)
5471     return Diag(Call->getEndLoc(),
5472                 diag::err_typecheck_call_too_few_args_at_least)
5473            << 0 /*function call*/ << 3 << Call->getNumArgs();
5474 
5475   // Type-check the first argument normally.
5476   if (checkBuiltinArgument(*this, Call, 0))
5477     return true;
5478 
5479   // Check that the current function is variadic.
5480   if (checkVAStartIsInVariadicFunction(*this, Func))
5481     return true;
5482 
5483   // __va_start on Windows does not validate the parameter qualifiers
5484 
5485   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5486   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5487 
5488   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5489   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5490 
5491   const QualType &ConstCharPtrTy =
5492       Context.getPointerType(Context.CharTy.withConst());
5493   if (!Arg1Ty->isPointerType() ||
5494       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5495     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5496         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5497         << 0                                      /* qualifier difference */
5498         << 3                                      /* parameter mismatch */
5499         << 2 << Arg1->getType() << ConstCharPtrTy;
5500 
5501   const QualType SizeTy = Context.getSizeType();
5502   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5503     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5504         << Arg2->getType() << SizeTy << 1 /* different class */
5505         << 0                              /* qualifier difference */
5506         << 3                              /* parameter mismatch */
5507         << 3 << Arg2->getType() << SizeTy;
5508 
5509   return false;
5510 }
5511 
5512 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5513 /// friends.  This is declared to take (...), so we have to check everything.
5514 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5515   if (TheCall->getNumArgs() < 2)
5516     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5517            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5518   if (TheCall->getNumArgs() > 2)
5519     return Diag(TheCall->getArg(2)->getBeginLoc(),
5520                 diag::err_typecheck_call_too_many_args)
5521            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5522            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5523                           (*(TheCall->arg_end() - 1))->getEndLoc());
5524 
5525   ExprResult OrigArg0 = TheCall->getArg(0);
5526   ExprResult OrigArg1 = TheCall->getArg(1);
5527 
5528   // Do standard promotions between the two arguments, returning their common
5529   // type.
5530   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5531   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5532     return true;
5533 
5534   // Make sure any conversions are pushed back into the call; this is
5535   // type safe since unordered compare builtins are declared as "_Bool
5536   // foo(...)".
5537   TheCall->setArg(0, OrigArg0.get());
5538   TheCall->setArg(1, OrigArg1.get());
5539 
5540   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5541     return false;
5542 
5543   // If the common type isn't a real floating type, then the arguments were
5544   // invalid for this operation.
5545   if (Res.isNull() || !Res->isRealFloatingType())
5546     return Diag(OrigArg0.get()->getBeginLoc(),
5547                 diag::err_typecheck_call_invalid_ordered_compare)
5548            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5549            << SourceRange(OrigArg0.get()->getBeginLoc(),
5550                           OrigArg1.get()->getEndLoc());
5551 
5552   return false;
5553 }
5554 
5555 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5556 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5557 /// to check everything. We expect the last argument to be a floating point
5558 /// value.
5559 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5560   if (TheCall->getNumArgs() < NumArgs)
5561     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5562            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5563   if (TheCall->getNumArgs() > NumArgs)
5564     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5565                 diag::err_typecheck_call_too_many_args)
5566            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5567            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5568                           (*(TheCall->arg_end() - 1))->getEndLoc());
5569 
5570   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5571 
5572   if (OrigArg->isTypeDependent())
5573     return false;
5574 
5575   // This operation requires a non-_Complex floating-point number.
5576   if (!OrigArg->getType()->isRealFloatingType())
5577     return Diag(OrigArg->getBeginLoc(),
5578                 diag::err_typecheck_call_invalid_unary_fp)
5579            << OrigArg->getType() << OrigArg->getSourceRange();
5580 
5581   // If this is an implicit conversion from float -> float, double, or
5582   // long double, remove it.
5583   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5584     // Only remove standard FloatCasts, leaving other casts inplace
5585     if (Cast->getCastKind() == CK_FloatingCast) {
5586       Expr *CastArg = Cast->getSubExpr();
5587       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5588         assert(
5589             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5590              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5591              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5592             "promotion from float to either float, double, or long double is "
5593             "the only expected cast here");
5594         Cast->setSubExpr(nullptr);
5595         TheCall->setArg(NumArgs-1, CastArg);
5596       }
5597     }
5598   }
5599 
5600   return false;
5601 }
5602 
5603 // Customized Sema Checking for VSX builtins that have the following signature:
5604 // vector [...] builtinName(vector [...], vector [...], const int);
5605 // Which takes the same type of vectors (any legal vector type) for the first
5606 // two arguments and takes compile time constant for the third argument.
5607 // Example builtins are :
5608 // vector double vec_xxpermdi(vector double, vector double, int);
5609 // vector short vec_xxsldwi(vector short, vector short, int);
5610 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5611   unsigned ExpectedNumArgs = 3;
5612   if (TheCall->getNumArgs() < ExpectedNumArgs)
5613     return Diag(TheCall->getEndLoc(),
5614                 diag::err_typecheck_call_too_few_args_at_least)
5615            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5616            << TheCall->getSourceRange();
5617 
5618   if (TheCall->getNumArgs() > ExpectedNumArgs)
5619     return Diag(TheCall->getEndLoc(),
5620                 diag::err_typecheck_call_too_many_args_at_most)
5621            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5622            << TheCall->getSourceRange();
5623 
5624   // Check the third argument is a compile time constant
5625   llvm::APSInt Value;
5626   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5627     return Diag(TheCall->getBeginLoc(),
5628                 diag::err_vsx_builtin_nonconstant_argument)
5629            << 3 /* argument index */ << TheCall->getDirectCallee()
5630            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5631                           TheCall->getArg(2)->getEndLoc());
5632 
5633   QualType Arg1Ty = TheCall->getArg(0)->getType();
5634   QualType Arg2Ty = TheCall->getArg(1)->getType();
5635 
5636   // Check the type of argument 1 and argument 2 are vectors.
5637   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5638   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5639       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5640     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5641            << TheCall->getDirectCallee()
5642            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5643                           TheCall->getArg(1)->getEndLoc());
5644   }
5645 
5646   // Check the first two arguments are the same type.
5647   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5648     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5649            << TheCall->getDirectCallee()
5650            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5651                           TheCall->getArg(1)->getEndLoc());
5652   }
5653 
5654   // When default clang type checking is turned off and the customized type
5655   // checking is used, the returning type of the function must be explicitly
5656   // set. Otherwise it is _Bool by default.
5657   TheCall->setType(Arg1Ty);
5658 
5659   return false;
5660 }
5661 
5662 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5663 // This is declared to take (...), so we have to check everything.
5664 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5665   if (TheCall->getNumArgs() < 2)
5666     return ExprError(Diag(TheCall->getEndLoc(),
5667                           diag::err_typecheck_call_too_few_args_at_least)
5668                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5669                      << TheCall->getSourceRange());
5670 
5671   // Determine which of the following types of shufflevector we're checking:
5672   // 1) unary, vector mask: (lhs, mask)
5673   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5674   QualType resType = TheCall->getArg(0)->getType();
5675   unsigned numElements = 0;
5676 
5677   if (!TheCall->getArg(0)->isTypeDependent() &&
5678       !TheCall->getArg(1)->isTypeDependent()) {
5679     QualType LHSType = TheCall->getArg(0)->getType();
5680     QualType RHSType = TheCall->getArg(1)->getType();
5681 
5682     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5683       return ExprError(
5684           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5685           << TheCall->getDirectCallee()
5686           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5687                          TheCall->getArg(1)->getEndLoc()));
5688 
5689     numElements = LHSType->getAs<VectorType>()->getNumElements();
5690     unsigned numResElements = TheCall->getNumArgs() - 2;
5691 
5692     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5693     // with mask.  If so, verify that RHS is an integer vector type with the
5694     // same number of elts as lhs.
5695     if (TheCall->getNumArgs() == 2) {
5696       if (!RHSType->hasIntegerRepresentation() ||
5697           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5698         return ExprError(Diag(TheCall->getBeginLoc(),
5699                               diag::err_vec_builtin_incompatible_vector)
5700                          << TheCall->getDirectCallee()
5701                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5702                                         TheCall->getArg(1)->getEndLoc()));
5703     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5704       return ExprError(Diag(TheCall->getBeginLoc(),
5705                             diag::err_vec_builtin_incompatible_vector)
5706                        << TheCall->getDirectCallee()
5707                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5708                                       TheCall->getArg(1)->getEndLoc()));
5709     } else if (numElements != numResElements) {
5710       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5711       resType = Context.getVectorType(eltType, numResElements,
5712                                       VectorType::GenericVector);
5713     }
5714   }
5715 
5716   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5717     if (TheCall->getArg(i)->isTypeDependent() ||
5718         TheCall->getArg(i)->isValueDependent())
5719       continue;
5720 
5721     llvm::APSInt Result(32);
5722     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5723       return ExprError(Diag(TheCall->getBeginLoc(),
5724                             diag::err_shufflevector_nonconstant_argument)
5725                        << TheCall->getArg(i)->getSourceRange());
5726 
5727     // Allow -1 which will be translated to undef in the IR.
5728     if (Result.isSigned() && Result.isAllOnesValue())
5729       continue;
5730 
5731     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5732       return ExprError(Diag(TheCall->getBeginLoc(),
5733                             diag::err_shufflevector_argument_too_large)
5734                        << TheCall->getArg(i)->getSourceRange());
5735   }
5736 
5737   SmallVector<Expr*, 32> exprs;
5738 
5739   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5740     exprs.push_back(TheCall->getArg(i));
5741     TheCall->setArg(i, nullptr);
5742   }
5743 
5744   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5745                                          TheCall->getCallee()->getBeginLoc(),
5746                                          TheCall->getRParenLoc());
5747 }
5748 
5749 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5750 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5751                                        SourceLocation BuiltinLoc,
5752                                        SourceLocation RParenLoc) {
5753   ExprValueKind VK = VK_RValue;
5754   ExprObjectKind OK = OK_Ordinary;
5755   QualType DstTy = TInfo->getType();
5756   QualType SrcTy = E->getType();
5757 
5758   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5759     return ExprError(Diag(BuiltinLoc,
5760                           diag::err_convertvector_non_vector)
5761                      << E->getSourceRange());
5762   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5763     return ExprError(Diag(BuiltinLoc,
5764                           diag::err_convertvector_non_vector_type));
5765 
5766   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5767     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5768     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5769     if (SrcElts != DstElts)
5770       return ExprError(Diag(BuiltinLoc,
5771                             diag::err_convertvector_incompatible_vector)
5772                        << E->getSourceRange());
5773   }
5774 
5775   return new (Context)
5776       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5777 }
5778 
5779 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5780 // This is declared to take (const void*, ...) and can take two
5781 // optional constant int args.
5782 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5783   unsigned NumArgs = TheCall->getNumArgs();
5784 
5785   if (NumArgs > 3)
5786     return Diag(TheCall->getEndLoc(),
5787                 diag::err_typecheck_call_too_many_args_at_most)
5788            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5789 
5790   // Argument 0 is checked for us and the remaining arguments must be
5791   // constant integers.
5792   for (unsigned i = 1; i != NumArgs; ++i)
5793     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5794       return true;
5795 
5796   return false;
5797 }
5798 
5799 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5800 // __assume does not evaluate its arguments, and should warn if its argument
5801 // has side effects.
5802 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5803   Expr *Arg = TheCall->getArg(0);
5804   if (Arg->isInstantiationDependent()) return false;
5805 
5806   if (Arg->HasSideEffects(Context))
5807     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5808         << Arg->getSourceRange()
5809         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5810 
5811   return false;
5812 }
5813 
5814 /// Handle __builtin_alloca_with_align. This is declared
5815 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5816 /// than 8.
5817 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5818   // The alignment must be a constant integer.
5819   Expr *Arg = TheCall->getArg(1);
5820 
5821   // We can't check the value of a dependent argument.
5822   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5823     if (const auto *UE =
5824             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5825       if (UE->getKind() == UETT_AlignOf ||
5826           UE->getKind() == UETT_PreferredAlignOf)
5827         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5828             << Arg->getSourceRange();
5829 
5830     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5831 
5832     if (!Result.isPowerOf2())
5833       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5834              << Arg->getSourceRange();
5835 
5836     if (Result < Context.getCharWidth())
5837       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5838              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5839 
5840     if (Result > std::numeric_limits<int32_t>::max())
5841       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5842              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5843   }
5844 
5845   return false;
5846 }
5847 
5848 /// Handle __builtin_assume_aligned. This is declared
5849 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5850 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5851   unsigned NumArgs = TheCall->getNumArgs();
5852 
5853   if (NumArgs > 3)
5854     return Diag(TheCall->getEndLoc(),
5855                 diag::err_typecheck_call_too_many_args_at_most)
5856            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5857 
5858   // The alignment must be a constant integer.
5859   Expr *Arg = TheCall->getArg(1);
5860 
5861   // We can't check the value of a dependent argument.
5862   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5863     llvm::APSInt Result;
5864     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5865       return true;
5866 
5867     if (!Result.isPowerOf2())
5868       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5869              << Arg->getSourceRange();
5870   }
5871 
5872   if (NumArgs > 2) {
5873     ExprResult Arg(TheCall->getArg(2));
5874     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5875       Context.getSizeType(), false);
5876     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5877     if (Arg.isInvalid()) return true;
5878     TheCall->setArg(2, Arg.get());
5879   }
5880 
5881   return false;
5882 }
5883 
5884 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5885   unsigned BuiltinID =
5886       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5887   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5888 
5889   unsigned NumArgs = TheCall->getNumArgs();
5890   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5891   if (NumArgs < NumRequiredArgs) {
5892     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5893            << 0 /* function call */ << NumRequiredArgs << NumArgs
5894            << TheCall->getSourceRange();
5895   }
5896   if (NumArgs >= NumRequiredArgs + 0x100) {
5897     return Diag(TheCall->getEndLoc(),
5898                 diag::err_typecheck_call_too_many_args_at_most)
5899            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5900            << TheCall->getSourceRange();
5901   }
5902   unsigned i = 0;
5903 
5904   // For formatting call, check buffer arg.
5905   if (!IsSizeCall) {
5906     ExprResult Arg(TheCall->getArg(i));
5907     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5908         Context, Context.VoidPtrTy, false);
5909     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5910     if (Arg.isInvalid())
5911       return true;
5912     TheCall->setArg(i, Arg.get());
5913     i++;
5914   }
5915 
5916   // Check string literal arg.
5917   unsigned FormatIdx = i;
5918   {
5919     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5920     if (Arg.isInvalid())
5921       return true;
5922     TheCall->setArg(i, Arg.get());
5923     i++;
5924   }
5925 
5926   // Make sure variadic args are scalar.
5927   unsigned FirstDataArg = i;
5928   while (i < NumArgs) {
5929     ExprResult Arg = DefaultVariadicArgumentPromotion(
5930         TheCall->getArg(i), VariadicFunction, nullptr);
5931     if (Arg.isInvalid())
5932       return true;
5933     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5934     if (ArgSize.getQuantity() >= 0x100) {
5935       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5936              << i << (int)ArgSize.getQuantity() << 0xff
5937              << TheCall->getSourceRange();
5938     }
5939     TheCall->setArg(i, Arg.get());
5940     i++;
5941   }
5942 
5943   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5944   // call to avoid duplicate diagnostics.
5945   if (!IsSizeCall) {
5946     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5947     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5948     bool Success = CheckFormatArguments(
5949         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5950         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5951         CheckedVarArgs);
5952     if (!Success)
5953       return true;
5954   }
5955 
5956   if (IsSizeCall) {
5957     TheCall->setType(Context.getSizeType());
5958   } else {
5959     TheCall->setType(Context.VoidPtrTy);
5960   }
5961   return false;
5962 }
5963 
5964 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5965 /// TheCall is a constant expression.
5966 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5967                                   llvm::APSInt &Result) {
5968   Expr *Arg = TheCall->getArg(ArgNum);
5969   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5970   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5971 
5972   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5973 
5974   if (!Arg->isIntegerConstantExpr(Result, Context))
5975     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5976            << FDecl->getDeclName() << Arg->getSourceRange();
5977 
5978   return false;
5979 }
5980 
5981 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5982 /// TheCall is a constant expression in the range [Low, High].
5983 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5984                                        int Low, int High, bool RangeIsError) {
5985   llvm::APSInt Result;
5986 
5987   // We can't check the value of a dependent argument.
5988   Expr *Arg = TheCall->getArg(ArgNum);
5989   if (Arg->isTypeDependent() || Arg->isValueDependent())
5990     return false;
5991 
5992   // Check constant-ness first.
5993   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5994     return true;
5995 
5996   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5997     if (RangeIsError)
5998       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5999              << Result.toString(10) << Low << High << Arg->getSourceRange();
6000     else
6001       // Defer the warning until we know if the code will be emitted so that
6002       // dead code can ignore this.
6003       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6004                           PDiag(diag::warn_argument_invalid_range)
6005                               << Result.toString(10) << Low << High
6006                               << Arg->getSourceRange());
6007   }
6008 
6009   return false;
6010 }
6011 
6012 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6013 /// TheCall is a constant expression is a multiple of Num..
6014 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6015                                           unsigned Num) {
6016   llvm::APSInt Result;
6017 
6018   // We can't check the value of a dependent argument.
6019   Expr *Arg = TheCall->getArg(ArgNum);
6020   if (Arg->isTypeDependent() || Arg->isValueDependent())
6021     return false;
6022 
6023   // Check constant-ness first.
6024   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6025     return true;
6026 
6027   if (Result.getSExtValue() % Num != 0)
6028     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6029            << Num << Arg->getSourceRange();
6030 
6031   return false;
6032 }
6033 
6034 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6035 /// TheCall is an ARM/AArch64 special register string literal.
6036 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6037                                     int ArgNum, unsigned ExpectedFieldNum,
6038                                     bool AllowName) {
6039   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6040                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6041                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6042                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6043                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6044                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6045   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6046                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6047                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6048                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6049                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6050                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6051   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6052 
6053   // We can't check the value of a dependent argument.
6054   Expr *Arg = TheCall->getArg(ArgNum);
6055   if (Arg->isTypeDependent() || Arg->isValueDependent())
6056     return false;
6057 
6058   // Check if the argument is a string literal.
6059   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6060     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6061            << Arg->getSourceRange();
6062 
6063   // Check the type of special register given.
6064   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6065   SmallVector<StringRef, 6> Fields;
6066   Reg.split(Fields, ":");
6067 
6068   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6069     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6070            << Arg->getSourceRange();
6071 
6072   // If the string is the name of a register then we cannot check that it is
6073   // valid here but if the string is of one the forms described in ACLE then we
6074   // can check that the supplied fields are integers and within the valid
6075   // ranges.
6076   if (Fields.size() > 1) {
6077     bool FiveFields = Fields.size() == 5;
6078 
6079     bool ValidString = true;
6080     if (IsARMBuiltin) {
6081       ValidString &= Fields[0].startswith_lower("cp") ||
6082                      Fields[0].startswith_lower("p");
6083       if (ValidString)
6084         Fields[0] =
6085           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6086 
6087       ValidString &= Fields[2].startswith_lower("c");
6088       if (ValidString)
6089         Fields[2] = Fields[2].drop_front(1);
6090 
6091       if (FiveFields) {
6092         ValidString &= Fields[3].startswith_lower("c");
6093         if (ValidString)
6094           Fields[3] = Fields[3].drop_front(1);
6095       }
6096     }
6097 
6098     SmallVector<int, 5> Ranges;
6099     if (FiveFields)
6100       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6101     else
6102       Ranges.append({15, 7, 15});
6103 
6104     for (unsigned i=0; i<Fields.size(); ++i) {
6105       int IntField;
6106       ValidString &= !Fields[i].getAsInteger(10, IntField);
6107       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6108     }
6109 
6110     if (!ValidString)
6111       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6112              << Arg->getSourceRange();
6113   } else if (IsAArch64Builtin && Fields.size() == 1) {
6114     // If the register name is one of those that appear in the condition below
6115     // and the special register builtin being used is one of the write builtins,
6116     // then we require that the argument provided for writing to the register
6117     // is an integer constant expression. This is because it will be lowered to
6118     // an MSR (immediate) instruction, so we need to know the immediate at
6119     // compile time.
6120     if (TheCall->getNumArgs() != 2)
6121       return false;
6122 
6123     std::string RegLower = Reg.lower();
6124     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6125         RegLower != "pan" && RegLower != "uao")
6126       return false;
6127 
6128     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6129   }
6130 
6131   return false;
6132 }
6133 
6134 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6135 /// This checks that the target supports __builtin_longjmp and
6136 /// that val is a constant 1.
6137 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6138   if (!Context.getTargetInfo().hasSjLjLowering())
6139     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6140            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6141 
6142   Expr *Arg = TheCall->getArg(1);
6143   llvm::APSInt Result;
6144 
6145   // TODO: This is less than ideal. Overload this to take a value.
6146   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6147     return true;
6148 
6149   if (Result != 1)
6150     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6151            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6152 
6153   return false;
6154 }
6155 
6156 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6157 /// This checks that the target supports __builtin_setjmp.
6158 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6159   if (!Context.getTargetInfo().hasSjLjLowering())
6160     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6161            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6162   return false;
6163 }
6164 
6165 namespace {
6166 
6167 class UncoveredArgHandler {
6168   enum { Unknown = -1, AllCovered = -2 };
6169 
6170   signed FirstUncoveredArg = Unknown;
6171   SmallVector<const Expr *, 4> DiagnosticExprs;
6172 
6173 public:
6174   UncoveredArgHandler() = default;
6175 
6176   bool hasUncoveredArg() const {
6177     return (FirstUncoveredArg >= 0);
6178   }
6179 
6180   unsigned getUncoveredArg() const {
6181     assert(hasUncoveredArg() && "no uncovered argument");
6182     return FirstUncoveredArg;
6183   }
6184 
6185   void setAllCovered() {
6186     // A string has been found with all arguments covered, so clear out
6187     // the diagnostics.
6188     DiagnosticExprs.clear();
6189     FirstUncoveredArg = AllCovered;
6190   }
6191 
6192   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6193     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6194 
6195     // Don't update if a previous string covers all arguments.
6196     if (FirstUncoveredArg == AllCovered)
6197       return;
6198 
6199     // UncoveredArgHandler tracks the highest uncovered argument index
6200     // and with it all the strings that match this index.
6201     if (NewFirstUncoveredArg == FirstUncoveredArg)
6202       DiagnosticExprs.push_back(StrExpr);
6203     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6204       DiagnosticExprs.clear();
6205       DiagnosticExprs.push_back(StrExpr);
6206       FirstUncoveredArg = NewFirstUncoveredArg;
6207     }
6208   }
6209 
6210   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6211 };
6212 
6213 enum StringLiteralCheckType {
6214   SLCT_NotALiteral,
6215   SLCT_UncheckedLiteral,
6216   SLCT_CheckedLiteral
6217 };
6218 
6219 } // namespace
6220 
6221 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6222                                      BinaryOperatorKind BinOpKind,
6223                                      bool AddendIsRight) {
6224   unsigned BitWidth = Offset.getBitWidth();
6225   unsigned AddendBitWidth = Addend.getBitWidth();
6226   // There might be negative interim results.
6227   if (Addend.isUnsigned()) {
6228     Addend = Addend.zext(++AddendBitWidth);
6229     Addend.setIsSigned(true);
6230   }
6231   // Adjust the bit width of the APSInts.
6232   if (AddendBitWidth > BitWidth) {
6233     Offset = Offset.sext(AddendBitWidth);
6234     BitWidth = AddendBitWidth;
6235   } else if (BitWidth > AddendBitWidth) {
6236     Addend = Addend.sext(BitWidth);
6237   }
6238 
6239   bool Ov = false;
6240   llvm::APSInt ResOffset = Offset;
6241   if (BinOpKind == BO_Add)
6242     ResOffset = Offset.sadd_ov(Addend, Ov);
6243   else {
6244     assert(AddendIsRight && BinOpKind == BO_Sub &&
6245            "operator must be add or sub with addend on the right");
6246     ResOffset = Offset.ssub_ov(Addend, Ov);
6247   }
6248 
6249   // We add an offset to a pointer here so we should support an offset as big as
6250   // possible.
6251   if (Ov) {
6252     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6253            "index (intermediate) result too big");
6254     Offset = Offset.sext(2 * BitWidth);
6255     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6256     return;
6257   }
6258 
6259   Offset = ResOffset;
6260 }
6261 
6262 namespace {
6263 
6264 // This is a wrapper class around StringLiteral to support offsetted string
6265 // literals as format strings. It takes the offset into account when returning
6266 // the string and its length or the source locations to display notes correctly.
6267 class FormatStringLiteral {
6268   const StringLiteral *FExpr;
6269   int64_t Offset;
6270 
6271  public:
6272   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6273       : FExpr(fexpr), Offset(Offset) {}
6274 
6275   StringRef getString() const {
6276     return FExpr->getString().drop_front(Offset);
6277   }
6278 
6279   unsigned getByteLength() const {
6280     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6281   }
6282 
6283   unsigned getLength() const { return FExpr->getLength() - Offset; }
6284   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6285 
6286   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6287 
6288   QualType getType() const { return FExpr->getType(); }
6289 
6290   bool isAscii() const { return FExpr->isAscii(); }
6291   bool isWide() const { return FExpr->isWide(); }
6292   bool isUTF8() const { return FExpr->isUTF8(); }
6293   bool isUTF16() const { return FExpr->isUTF16(); }
6294   bool isUTF32() const { return FExpr->isUTF32(); }
6295   bool isPascal() const { return FExpr->isPascal(); }
6296 
6297   SourceLocation getLocationOfByte(
6298       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6299       const TargetInfo &Target, unsigned *StartToken = nullptr,
6300       unsigned *StartTokenByteOffset = nullptr) const {
6301     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6302                                     StartToken, StartTokenByteOffset);
6303   }
6304 
6305   SourceLocation getBeginLoc() const LLVM_READONLY {
6306     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6307   }
6308 
6309   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6310 };
6311 
6312 }  // namespace
6313 
6314 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6315                               const Expr *OrigFormatExpr,
6316                               ArrayRef<const Expr *> Args,
6317                               bool HasVAListArg, unsigned format_idx,
6318                               unsigned firstDataArg,
6319                               Sema::FormatStringType Type,
6320                               bool inFunctionCall,
6321                               Sema::VariadicCallType CallType,
6322                               llvm::SmallBitVector &CheckedVarArgs,
6323                               UncoveredArgHandler &UncoveredArg);
6324 
6325 // Determine if an expression is a string literal or constant string.
6326 // If this function returns false on the arguments to a function expecting a
6327 // format string, we will usually need to emit a warning.
6328 // True string literals are then checked by CheckFormatString.
6329 static StringLiteralCheckType
6330 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6331                       bool HasVAListArg, unsigned format_idx,
6332                       unsigned firstDataArg, Sema::FormatStringType Type,
6333                       Sema::VariadicCallType CallType, bool InFunctionCall,
6334                       llvm::SmallBitVector &CheckedVarArgs,
6335                       UncoveredArgHandler &UncoveredArg,
6336                       llvm::APSInt Offset) {
6337  tryAgain:
6338   assert(Offset.isSigned() && "invalid offset");
6339 
6340   if (E->isTypeDependent() || E->isValueDependent())
6341     return SLCT_NotALiteral;
6342 
6343   E = E->IgnoreParenCasts();
6344 
6345   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6346     // Technically -Wformat-nonliteral does not warn about this case.
6347     // The behavior of printf and friends in this case is implementation
6348     // dependent.  Ideally if the format string cannot be null then
6349     // it should have a 'nonnull' attribute in the function prototype.
6350     return SLCT_UncheckedLiteral;
6351 
6352   switch (E->getStmtClass()) {
6353   case Stmt::BinaryConditionalOperatorClass:
6354   case Stmt::ConditionalOperatorClass: {
6355     // The expression is a literal if both sub-expressions were, and it was
6356     // completely checked only if both sub-expressions were checked.
6357     const AbstractConditionalOperator *C =
6358         cast<AbstractConditionalOperator>(E);
6359 
6360     // Determine whether it is necessary to check both sub-expressions, for
6361     // example, because the condition expression is a constant that can be
6362     // evaluated at compile time.
6363     bool CheckLeft = true, CheckRight = true;
6364 
6365     bool Cond;
6366     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6367       if (Cond)
6368         CheckRight = false;
6369       else
6370         CheckLeft = false;
6371     }
6372 
6373     // We need to maintain the offsets for the right and the left hand side
6374     // separately to check if every possible indexed expression is a valid
6375     // string literal. They might have different offsets for different string
6376     // literals in the end.
6377     StringLiteralCheckType Left;
6378     if (!CheckLeft)
6379       Left = SLCT_UncheckedLiteral;
6380     else {
6381       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6382                                    HasVAListArg, format_idx, firstDataArg,
6383                                    Type, CallType, InFunctionCall,
6384                                    CheckedVarArgs, UncoveredArg, Offset);
6385       if (Left == SLCT_NotALiteral || !CheckRight) {
6386         return Left;
6387       }
6388     }
6389 
6390     StringLiteralCheckType Right =
6391         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6392                               HasVAListArg, format_idx, firstDataArg,
6393                               Type, CallType, InFunctionCall, CheckedVarArgs,
6394                               UncoveredArg, Offset);
6395 
6396     return (CheckLeft && Left < Right) ? Left : Right;
6397   }
6398 
6399   case Stmt::ImplicitCastExprClass:
6400     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6401     goto tryAgain;
6402 
6403   case Stmt::OpaqueValueExprClass:
6404     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6405       E = src;
6406       goto tryAgain;
6407     }
6408     return SLCT_NotALiteral;
6409 
6410   case Stmt::PredefinedExprClass:
6411     // While __func__, etc., are technically not string literals, they
6412     // cannot contain format specifiers and thus are not a security
6413     // liability.
6414     return SLCT_UncheckedLiteral;
6415 
6416   case Stmt::DeclRefExprClass: {
6417     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6418 
6419     // As an exception, do not flag errors for variables binding to
6420     // const string literals.
6421     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6422       bool isConstant = false;
6423       QualType T = DR->getType();
6424 
6425       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6426         isConstant = AT->getElementType().isConstant(S.Context);
6427       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6428         isConstant = T.isConstant(S.Context) &&
6429                      PT->getPointeeType().isConstant(S.Context);
6430       } else if (T->isObjCObjectPointerType()) {
6431         // In ObjC, there is usually no "const ObjectPointer" type,
6432         // so don't check if the pointee type is constant.
6433         isConstant = T.isConstant(S.Context);
6434       }
6435 
6436       if (isConstant) {
6437         if (const Expr *Init = VD->getAnyInitializer()) {
6438           // Look through initializers like const char c[] = { "foo" }
6439           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6440             if (InitList->isStringLiteralInit())
6441               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6442           }
6443           return checkFormatStringExpr(S, Init, Args,
6444                                        HasVAListArg, format_idx,
6445                                        firstDataArg, Type, CallType,
6446                                        /*InFunctionCall*/ false, CheckedVarArgs,
6447                                        UncoveredArg, Offset);
6448         }
6449       }
6450 
6451       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6452       // special check to see if the format string is a function parameter
6453       // of the function calling the printf function.  If the function
6454       // has an attribute indicating it is a printf-like function, then we
6455       // should suppress warnings concerning non-literals being used in a call
6456       // to a vprintf function.  For example:
6457       //
6458       // void
6459       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6460       //      va_list ap;
6461       //      va_start(ap, fmt);
6462       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6463       //      ...
6464       // }
6465       if (HasVAListArg) {
6466         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6467           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6468             int PVIndex = PV->getFunctionScopeIndex() + 1;
6469             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6470               // adjust for implicit parameter
6471               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6472                 if (MD->isInstance())
6473                   ++PVIndex;
6474               // We also check if the formats are compatible.
6475               // We can't pass a 'scanf' string to a 'printf' function.
6476               if (PVIndex == PVFormat->getFormatIdx() &&
6477                   Type == S.GetFormatStringType(PVFormat))
6478                 return SLCT_UncheckedLiteral;
6479             }
6480           }
6481         }
6482       }
6483     }
6484 
6485     return SLCT_NotALiteral;
6486   }
6487 
6488   case Stmt::CallExprClass:
6489   case Stmt::CXXMemberCallExprClass: {
6490     const CallExpr *CE = cast<CallExpr>(E);
6491     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6492       bool IsFirst = true;
6493       StringLiteralCheckType CommonResult;
6494       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6495         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6496         StringLiteralCheckType Result = checkFormatStringExpr(
6497             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6498             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6499         if (IsFirst) {
6500           CommonResult = Result;
6501           IsFirst = false;
6502         }
6503       }
6504       if (!IsFirst)
6505         return CommonResult;
6506 
6507       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6508         unsigned BuiltinID = FD->getBuiltinID();
6509         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6510             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6511           const Expr *Arg = CE->getArg(0);
6512           return checkFormatStringExpr(S, Arg, Args,
6513                                        HasVAListArg, format_idx,
6514                                        firstDataArg, Type, CallType,
6515                                        InFunctionCall, CheckedVarArgs,
6516                                        UncoveredArg, Offset);
6517         }
6518       }
6519     }
6520 
6521     return SLCT_NotALiteral;
6522   }
6523   case Stmt::ObjCMessageExprClass: {
6524     const auto *ME = cast<ObjCMessageExpr>(E);
6525     if (const auto *ND = ME->getMethodDecl()) {
6526       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6527         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6528         return checkFormatStringExpr(
6529             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6530             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6531       }
6532     }
6533 
6534     return SLCT_NotALiteral;
6535   }
6536   case Stmt::ObjCStringLiteralClass:
6537   case Stmt::StringLiteralClass: {
6538     const StringLiteral *StrE = nullptr;
6539 
6540     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6541       StrE = ObjCFExpr->getString();
6542     else
6543       StrE = cast<StringLiteral>(E);
6544 
6545     if (StrE) {
6546       if (Offset.isNegative() || Offset > StrE->getLength()) {
6547         // TODO: It would be better to have an explicit warning for out of
6548         // bounds literals.
6549         return SLCT_NotALiteral;
6550       }
6551       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6552       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6553                         firstDataArg, Type, InFunctionCall, CallType,
6554                         CheckedVarArgs, UncoveredArg);
6555       return SLCT_CheckedLiteral;
6556     }
6557 
6558     return SLCT_NotALiteral;
6559   }
6560   case Stmt::BinaryOperatorClass: {
6561     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6562 
6563     // A string literal + an int offset is still a string literal.
6564     if (BinOp->isAdditiveOp()) {
6565       Expr::EvalResult LResult, RResult;
6566 
6567       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6568       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6569 
6570       if (LIsInt != RIsInt) {
6571         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6572 
6573         if (LIsInt) {
6574           if (BinOpKind == BO_Add) {
6575             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6576             E = BinOp->getRHS();
6577             goto tryAgain;
6578           }
6579         } else {
6580           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6581           E = BinOp->getLHS();
6582           goto tryAgain;
6583         }
6584       }
6585     }
6586 
6587     return SLCT_NotALiteral;
6588   }
6589   case Stmt::UnaryOperatorClass: {
6590     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6591     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6592     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6593       Expr::EvalResult IndexResult;
6594       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6595         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6596                    /*RHS is int*/ true);
6597         E = ASE->getBase();
6598         goto tryAgain;
6599       }
6600     }
6601 
6602     return SLCT_NotALiteral;
6603   }
6604 
6605   default:
6606     return SLCT_NotALiteral;
6607   }
6608 }
6609 
6610 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6611   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6612       .Case("scanf", FST_Scanf)
6613       .Cases("printf", "printf0", FST_Printf)
6614       .Cases("NSString", "CFString", FST_NSString)
6615       .Case("strftime", FST_Strftime)
6616       .Case("strfmon", FST_Strfmon)
6617       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6618       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6619       .Case("os_trace", FST_OSLog)
6620       .Case("os_log", FST_OSLog)
6621       .Default(FST_Unknown);
6622 }
6623 
6624 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6625 /// functions) for correct use of format strings.
6626 /// Returns true if a format string has been fully checked.
6627 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6628                                 ArrayRef<const Expr *> Args,
6629                                 bool IsCXXMember,
6630                                 VariadicCallType CallType,
6631                                 SourceLocation Loc, SourceRange Range,
6632                                 llvm::SmallBitVector &CheckedVarArgs) {
6633   FormatStringInfo FSI;
6634   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6635     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6636                                 FSI.FirstDataArg, GetFormatStringType(Format),
6637                                 CallType, Loc, Range, CheckedVarArgs);
6638   return false;
6639 }
6640 
6641 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6642                                 bool HasVAListArg, unsigned format_idx,
6643                                 unsigned firstDataArg, FormatStringType Type,
6644                                 VariadicCallType CallType,
6645                                 SourceLocation Loc, SourceRange Range,
6646                                 llvm::SmallBitVector &CheckedVarArgs) {
6647   // CHECK: printf/scanf-like function is called with no format string.
6648   if (format_idx >= Args.size()) {
6649     Diag(Loc, diag::warn_missing_format_string) << Range;
6650     return false;
6651   }
6652 
6653   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6654 
6655   // CHECK: format string is not a string literal.
6656   //
6657   // Dynamically generated format strings are difficult to
6658   // automatically vet at compile time.  Requiring that format strings
6659   // are string literals: (1) permits the checking of format strings by
6660   // the compiler and thereby (2) can practically remove the source of
6661   // many format string exploits.
6662 
6663   // Format string can be either ObjC string (e.g. @"%d") or
6664   // C string (e.g. "%d")
6665   // ObjC string uses the same format specifiers as C string, so we can use
6666   // the same format string checking logic for both ObjC and C strings.
6667   UncoveredArgHandler UncoveredArg;
6668   StringLiteralCheckType CT =
6669       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6670                             format_idx, firstDataArg, Type, CallType,
6671                             /*IsFunctionCall*/ true, CheckedVarArgs,
6672                             UncoveredArg,
6673                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6674 
6675   // Generate a diagnostic where an uncovered argument is detected.
6676   if (UncoveredArg.hasUncoveredArg()) {
6677     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6678     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6679     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6680   }
6681 
6682   if (CT != SLCT_NotALiteral)
6683     // Literal format string found, check done!
6684     return CT == SLCT_CheckedLiteral;
6685 
6686   // Strftime is particular as it always uses a single 'time' argument,
6687   // so it is safe to pass a non-literal string.
6688   if (Type == FST_Strftime)
6689     return false;
6690 
6691   // Do not emit diag when the string param is a macro expansion and the
6692   // format is either NSString or CFString. This is a hack to prevent
6693   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6694   // which are usually used in place of NS and CF string literals.
6695   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6696   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6697     return false;
6698 
6699   // If there are no arguments specified, warn with -Wformat-security, otherwise
6700   // warn only with -Wformat-nonliteral.
6701   if (Args.size() == firstDataArg) {
6702     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6703       << OrigFormatExpr->getSourceRange();
6704     switch (Type) {
6705     default:
6706       break;
6707     case FST_Kprintf:
6708     case FST_FreeBSDKPrintf:
6709     case FST_Printf:
6710       Diag(FormatLoc, diag::note_format_security_fixit)
6711         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6712       break;
6713     case FST_NSString:
6714       Diag(FormatLoc, diag::note_format_security_fixit)
6715         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6716       break;
6717     }
6718   } else {
6719     Diag(FormatLoc, diag::warn_format_nonliteral)
6720       << OrigFormatExpr->getSourceRange();
6721   }
6722   return false;
6723 }
6724 
6725 namespace {
6726 
6727 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6728 protected:
6729   Sema &S;
6730   const FormatStringLiteral *FExpr;
6731   const Expr *OrigFormatExpr;
6732   const Sema::FormatStringType FSType;
6733   const unsigned FirstDataArg;
6734   const unsigned NumDataArgs;
6735   const char *Beg; // Start of format string.
6736   const bool HasVAListArg;
6737   ArrayRef<const Expr *> Args;
6738   unsigned FormatIdx;
6739   llvm::SmallBitVector CoveredArgs;
6740   bool usesPositionalArgs = false;
6741   bool atFirstArg = true;
6742   bool inFunctionCall;
6743   Sema::VariadicCallType CallType;
6744   llvm::SmallBitVector &CheckedVarArgs;
6745   UncoveredArgHandler &UncoveredArg;
6746 
6747 public:
6748   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6749                      const Expr *origFormatExpr,
6750                      const Sema::FormatStringType type, unsigned firstDataArg,
6751                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6752                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6753                      bool inFunctionCall, Sema::VariadicCallType callType,
6754                      llvm::SmallBitVector &CheckedVarArgs,
6755                      UncoveredArgHandler &UncoveredArg)
6756       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6757         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6758         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6759         inFunctionCall(inFunctionCall), CallType(callType),
6760         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6761     CoveredArgs.resize(numDataArgs);
6762     CoveredArgs.reset();
6763   }
6764 
6765   void DoneProcessing();
6766 
6767   void HandleIncompleteSpecifier(const char *startSpecifier,
6768                                  unsigned specifierLen) override;
6769 
6770   void HandleInvalidLengthModifier(
6771                            const analyze_format_string::FormatSpecifier &FS,
6772                            const analyze_format_string::ConversionSpecifier &CS,
6773                            const char *startSpecifier, unsigned specifierLen,
6774                            unsigned DiagID);
6775 
6776   void HandleNonStandardLengthModifier(
6777                     const analyze_format_string::FormatSpecifier &FS,
6778                     const char *startSpecifier, unsigned specifierLen);
6779 
6780   void HandleNonStandardConversionSpecifier(
6781                     const analyze_format_string::ConversionSpecifier &CS,
6782                     const char *startSpecifier, unsigned specifierLen);
6783 
6784   void HandlePosition(const char *startPos, unsigned posLen) override;
6785 
6786   void HandleInvalidPosition(const char *startSpecifier,
6787                              unsigned specifierLen,
6788                              analyze_format_string::PositionContext p) override;
6789 
6790   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6791 
6792   void HandleNullChar(const char *nullCharacter) override;
6793 
6794   template <typename Range>
6795   static void
6796   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6797                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6798                        bool IsStringLocation, Range StringRange,
6799                        ArrayRef<FixItHint> Fixit = None);
6800 
6801 protected:
6802   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6803                                         const char *startSpec,
6804                                         unsigned specifierLen,
6805                                         const char *csStart, unsigned csLen);
6806 
6807   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6808                                          const char *startSpec,
6809                                          unsigned specifierLen);
6810 
6811   SourceRange getFormatStringRange();
6812   CharSourceRange getSpecifierRange(const char *startSpecifier,
6813                                     unsigned specifierLen);
6814   SourceLocation getLocationOfByte(const char *x);
6815 
6816   const Expr *getDataArg(unsigned i) const;
6817 
6818   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6819                     const analyze_format_string::ConversionSpecifier &CS,
6820                     const char *startSpecifier, unsigned specifierLen,
6821                     unsigned argIndex);
6822 
6823   template <typename Range>
6824   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6825                             bool IsStringLocation, Range StringRange,
6826                             ArrayRef<FixItHint> Fixit = None);
6827 };
6828 
6829 } // namespace
6830 
6831 SourceRange CheckFormatHandler::getFormatStringRange() {
6832   return OrigFormatExpr->getSourceRange();
6833 }
6834 
6835 CharSourceRange CheckFormatHandler::
6836 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6837   SourceLocation Start = getLocationOfByte(startSpecifier);
6838   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6839 
6840   // Advance the end SourceLocation by one due to half-open ranges.
6841   End = End.getLocWithOffset(1);
6842 
6843   return CharSourceRange::getCharRange(Start, End);
6844 }
6845 
6846 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6847   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6848                                   S.getLangOpts(), S.Context.getTargetInfo());
6849 }
6850 
6851 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6852                                                    unsigned specifierLen){
6853   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6854                        getLocationOfByte(startSpecifier),
6855                        /*IsStringLocation*/true,
6856                        getSpecifierRange(startSpecifier, specifierLen));
6857 }
6858 
6859 void CheckFormatHandler::HandleInvalidLengthModifier(
6860     const analyze_format_string::FormatSpecifier &FS,
6861     const analyze_format_string::ConversionSpecifier &CS,
6862     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6863   using namespace analyze_format_string;
6864 
6865   const LengthModifier &LM = FS.getLengthModifier();
6866   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6867 
6868   // See if we know how to fix this length modifier.
6869   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6870   if (FixedLM) {
6871     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6872                          getLocationOfByte(LM.getStart()),
6873                          /*IsStringLocation*/true,
6874                          getSpecifierRange(startSpecifier, specifierLen));
6875 
6876     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6877       << FixedLM->toString()
6878       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6879 
6880   } else {
6881     FixItHint Hint;
6882     if (DiagID == diag::warn_format_nonsensical_length)
6883       Hint = FixItHint::CreateRemoval(LMRange);
6884 
6885     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6886                          getLocationOfByte(LM.getStart()),
6887                          /*IsStringLocation*/true,
6888                          getSpecifierRange(startSpecifier, specifierLen),
6889                          Hint);
6890   }
6891 }
6892 
6893 void CheckFormatHandler::HandleNonStandardLengthModifier(
6894     const analyze_format_string::FormatSpecifier &FS,
6895     const char *startSpecifier, unsigned specifierLen) {
6896   using namespace analyze_format_string;
6897 
6898   const LengthModifier &LM = FS.getLengthModifier();
6899   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6900 
6901   // See if we know how to fix this length modifier.
6902   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6903   if (FixedLM) {
6904     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6905                            << LM.toString() << 0,
6906                          getLocationOfByte(LM.getStart()),
6907                          /*IsStringLocation*/true,
6908                          getSpecifierRange(startSpecifier, specifierLen));
6909 
6910     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6911       << FixedLM->toString()
6912       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6913 
6914   } else {
6915     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6916                            << LM.toString() << 0,
6917                          getLocationOfByte(LM.getStart()),
6918                          /*IsStringLocation*/true,
6919                          getSpecifierRange(startSpecifier, specifierLen));
6920   }
6921 }
6922 
6923 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6924     const analyze_format_string::ConversionSpecifier &CS,
6925     const char *startSpecifier, unsigned specifierLen) {
6926   using namespace analyze_format_string;
6927 
6928   // See if we know how to fix this conversion specifier.
6929   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6930   if (FixedCS) {
6931     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6932                           << CS.toString() << /*conversion specifier*/1,
6933                          getLocationOfByte(CS.getStart()),
6934                          /*IsStringLocation*/true,
6935                          getSpecifierRange(startSpecifier, specifierLen));
6936 
6937     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6938     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6939       << FixedCS->toString()
6940       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6941   } else {
6942     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6943                           << CS.toString() << /*conversion specifier*/1,
6944                          getLocationOfByte(CS.getStart()),
6945                          /*IsStringLocation*/true,
6946                          getSpecifierRange(startSpecifier, specifierLen));
6947   }
6948 }
6949 
6950 void CheckFormatHandler::HandlePosition(const char *startPos,
6951                                         unsigned posLen) {
6952   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6953                                getLocationOfByte(startPos),
6954                                /*IsStringLocation*/true,
6955                                getSpecifierRange(startPos, posLen));
6956 }
6957 
6958 void
6959 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6960                                      analyze_format_string::PositionContext p) {
6961   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6962                          << (unsigned) p,
6963                        getLocationOfByte(startPos), /*IsStringLocation*/true,
6964                        getSpecifierRange(startPos, posLen));
6965 }
6966 
6967 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6968                                             unsigned posLen) {
6969   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6970                                getLocationOfByte(startPos),
6971                                /*IsStringLocation*/true,
6972                                getSpecifierRange(startPos, posLen));
6973 }
6974 
6975 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6976   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6977     // The presence of a null character is likely an error.
6978     EmitFormatDiagnostic(
6979       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6980       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6981       getFormatStringRange());
6982   }
6983 }
6984 
6985 // Note that this may return NULL if there was an error parsing or building
6986 // one of the argument expressions.
6987 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6988   return Args[FirstDataArg + i];
6989 }
6990 
6991 void CheckFormatHandler::DoneProcessing() {
6992   // Does the number of data arguments exceed the number of
6993   // format conversions in the format string?
6994   if (!HasVAListArg) {
6995       // Find any arguments that weren't covered.
6996     CoveredArgs.flip();
6997     signed notCoveredArg = CoveredArgs.find_first();
6998     if (notCoveredArg >= 0) {
6999       assert((unsigned)notCoveredArg < NumDataArgs);
7000       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7001     } else {
7002       UncoveredArg.setAllCovered();
7003     }
7004   }
7005 }
7006 
7007 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7008                                    const Expr *ArgExpr) {
7009   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7010          "Invalid state");
7011 
7012   if (!ArgExpr)
7013     return;
7014 
7015   SourceLocation Loc = ArgExpr->getBeginLoc();
7016 
7017   if (S.getSourceManager().isInSystemMacro(Loc))
7018     return;
7019 
7020   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7021   for (auto E : DiagnosticExprs)
7022     PDiag << E->getSourceRange();
7023 
7024   CheckFormatHandler::EmitFormatDiagnostic(
7025                                   S, IsFunctionCall, DiagnosticExprs[0],
7026                                   PDiag, Loc, /*IsStringLocation*/false,
7027                                   DiagnosticExprs[0]->getSourceRange());
7028 }
7029 
7030 bool
7031 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7032                                                      SourceLocation Loc,
7033                                                      const char *startSpec,
7034                                                      unsigned specifierLen,
7035                                                      const char *csStart,
7036                                                      unsigned csLen) {
7037   bool keepGoing = true;
7038   if (argIndex < NumDataArgs) {
7039     // Consider the argument coverered, even though the specifier doesn't
7040     // make sense.
7041     CoveredArgs.set(argIndex);
7042   }
7043   else {
7044     // If argIndex exceeds the number of data arguments we
7045     // don't issue a warning because that is just a cascade of warnings (and
7046     // they may have intended '%%' anyway). We don't want to continue processing
7047     // the format string after this point, however, as we will like just get
7048     // gibberish when trying to match arguments.
7049     keepGoing = false;
7050   }
7051 
7052   StringRef Specifier(csStart, csLen);
7053 
7054   // If the specifier in non-printable, it could be the first byte of a UTF-8
7055   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7056   // hex value.
7057   std::string CodePointStr;
7058   if (!llvm::sys::locale::isPrint(*csStart)) {
7059     llvm::UTF32 CodePoint;
7060     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7061     const llvm::UTF8 *E =
7062         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7063     llvm::ConversionResult Result =
7064         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7065 
7066     if (Result != llvm::conversionOK) {
7067       unsigned char FirstChar = *csStart;
7068       CodePoint = (llvm::UTF32)FirstChar;
7069     }
7070 
7071     llvm::raw_string_ostream OS(CodePointStr);
7072     if (CodePoint < 256)
7073       OS << "\\x" << llvm::format("%02x", CodePoint);
7074     else if (CodePoint <= 0xFFFF)
7075       OS << "\\u" << llvm::format("%04x", CodePoint);
7076     else
7077       OS << "\\U" << llvm::format("%08x", CodePoint);
7078     OS.flush();
7079     Specifier = CodePointStr;
7080   }
7081 
7082   EmitFormatDiagnostic(
7083       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7084       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7085 
7086   return keepGoing;
7087 }
7088 
7089 void
7090 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7091                                                       const char *startSpec,
7092                                                       unsigned specifierLen) {
7093   EmitFormatDiagnostic(
7094     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7095     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7096 }
7097 
7098 bool
7099 CheckFormatHandler::CheckNumArgs(
7100   const analyze_format_string::FormatSpecifier &FS,
7101   const analyze_format_string::ConversionSpecifier &CS,
7102   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7103 
7104   if (argIndex >= NumDataArgs) {
7105     PartialDiagnostic PDiag = FS.usesPositionalArg()
7106       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7107            << (argIndex+1) << NumDataArgs)
7108       : S.PDiag(diag::warn_printf_insufficient_data_args);
7109     EmitFormatDiagnostic(
7110       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7111       getSpecifierRange(startSpecifier, specifierLen));
7112 
7113     // Since more arguments than conversion tokens are given, by extension
7114     // all arguments are covered, so mark this as so.
7115     UncoveredArg.setAllCovered();
7116     return false;
7117   }
7118   return true;
7119 }
7120 
7121 template<typename Range>
7122 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7123                                               SourceLocation Loc,
7124                                               bool IsStringLocation,
7125                                               Range StringRange,
7126                                               ArrayRef<FixItHint> FixIt) {
7127   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7128                        Loc, IsStringLocation, StringRange, FixIt);
7129 }
7130 
7131 /// If the format string is not within the function call, emit a note
7132 /// so that the function call and string are in diagnostic messages.
7133 ///
7134 /// \param InFunctionCall if true, the format string is within the function
7135 /// call and only one diagnostic message will be produced.  Otherwise, an
7136 /// extra note will be emitted pointing to location of the format string.
7137 ///
7138 /// \param ArgumentExpr the expression that is passed as the format string
7139 /// argument in the function call.  Used for getting locations when two
7140 /// diagnostics are emitted.
7141 ///
7142 /// \param PDiag the callee should already have provided any strings for the
7143 /// diagnostic message.  This function only adds locations and fixits
7144 /// to diagnostics.
7145 ///
7146 /// \param Loc primary location for diagnostic.  If two diagnostics are
7147 /// required, one will be at Loc and a new SourceLocation will be created for
7148 /// the other one.
7149 ///
7150 /// \param IsStringLocation if true, Loc points to the format string should be
7151 /// used for the note.  Otherwise, Loc points to the argument list and will
7152 /// be used with PDiag.
7153 ///
7154 /// \param StringRange some or all of the string to highlight.  This is
7155 /// templated so it can accept either a CharSourceRange or a SourceRange.
7156 ///
7157 /// \param FixIt optional fix it hint for the format string.
7158 template <typename Range>
7159 void CheckFormatHandler::EmitFormatDiagnostic(
7160     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7161     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7162     Range StringRange, ArrayRef<FixItHint> FixIt) {
7163   if (InFunctionCall) {
7164     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7165     D << StringRange;
7166     D << FixIt;
7167   } else {
7168     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7169       << ArgumentExpr->getSourceRange();
7170 
7171     const Sema::SemaDiagnosticBuilder &Note =
7172       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7173              diag::note_format_string_defined);
7174 
7175     Note << StringRange;
7176     Note << FixIt;
7177   }
7178 }
7179 
7180 //===--- CHECK: Printf format string checking ------------------------------===//
7181 
7182 namespace {
7183 
7184 class CheckPrintfHandler : public CheckFormatHandler {
7185 public:
7186   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7187                      const Expr *origFormatExpr,
7188                      const Sema::FormatStringType type, unsigned firstDataArg,
7189                      unsigned numDataArgs, bool isObjC, const char *beg,
7190                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7191                      unsigned formatIdx, bool inFunctionCall,
7192                      Sema::VariadicCallType CallType,
7193                      llvm::SmallBitVector &CheckedVarArgs,
7194                      UncoveredArgHandler &UncoveredArg)
7195       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7196                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7197                            inFunctionCall, CallType, CheckedVarArgs,
7198                            UncoveredArg) {}
7199 
7200   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7201 
7202   /// Returns true if '%@' specifiers are allowed in the format string.
7203   bool allowsObjCArg() const {
7204     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7205            FSType == Sema::FST_OSTrace;
7206   }
7207 
7208   bool HandleInvalidPrintfConversionSpecifier(
7209                                       const analyze_printf::PrintfSpecifier &FS,
7210                                       const char *startSpecifier,
7211                                       unsigned specifierLen) override;
7212 
7213   void handleInvalidMaskType(StringRef MaskType) override;
7214 
7215   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7216                              const char *startSpecifier,
7217                              unsigned specifierLen) override;
7218   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7219                        const char *StartSpecifier,
7220                        unsigned SpecifierLen,
7221                        const Expr *E);
7222 
7223   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7224                     const char *startSpecifier, unsigned specifierLen);
7225   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7226                            const analyze_printf::OptionalAmount &Amt,
7227                            unsigned type,
7228                            const char *startSpecifier, unsigned specifierLen);
7229   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7230                   const analyze_printf::OptionalFlag &flag,
7231                   const char *startSpecifier, unsigned specifierLen);
7232   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7233                          const analyze_printf::OptionalFlag &ignoredFlag,
7234                          const analyze_printf::OptionalFlag &flag,
7235                          const char *startSpecifier, unsigned specifierLen);
7236   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7237                            const Expr *E);
7238 
7239   void HandleEmptyObjCModifierFlag(const char *startFlag,
7240                                    unsigned flagLen) override;
7241 
7242   void HandleInvalidObjCModifierFlag(const char *startFlag,
7243                                             unsigned flagLen) override;
7244 
7245   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7246                                            const char *flagsEnd,
7247                                            const char *conversionPosition)
7248                                              override;
7249 };
7250 
7251 } // namespace
7252 
7253 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7254                                       const analyze_printf::PrintfSpecifier &FS,
7255                                       const char *startSpecifier,
7256                                       unsigned specifierLen) {
7257   const analyze_printf::PrintfConversionSpecifier &CS =
7258     FS.getConversionSpecifier();
7259 
7260   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7261                                           getLocationOfByte(CS.getStart()),
7262                                           startSpecifier, specifierLen,
7263                                           CS.getStart(), CS.getLength());
7264 }
7265 
7266 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7267   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7268 }
7269 
7270 bool CheckPrintfHandler::HandleAmount(
7271                                const analyze_format_string::OptionalAmount &Amt,
7272                                unsigned k, const char *startSpecifier,
7273                                unsigned specifierLen) {
7274   if (Amt.hasDataArgument()) {
7275     if (!HasVAListArg) {
7276       unsigned argIndex = Amt.getArgIndex();
7277       if (argIndex >= NumDataArgs) {
7278         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7279                                << k,
7280                              getLocationOfByte(Amt.getStart()),
7281                              /*IsStringLocation*/true,
7282                              getSpecifierRange(startSpecifier, specifierLen));
7283         // Don't do any more checking.  We will just emit
7284         // spurious errors.
7285         return false;
7286       }
7287 
7288       // Type check the data argument.  It should be an 'int'.
7289       // Although not in conformance with C99, we also allow the argument to be
7290       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7291       // doesn't emit a warning for that case.
7292       CoveredArgs.set(argIndex);
7293       const Expr *Arg = getDataArg(argIndex);
7294       if (!Arg)
7295         return false;
7296 
7297       QualType T = Arg->getType();
7298 
7299       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7300       assert(AT.isValid());
7301 
7302       if (!AT.matchesType(S.Context, T)) {
7303         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7304                                << k << AT.getRepresentativeTypeName(S.Context)
7305                                << T << Arg->getSourceRange(),
7306                              getLocationOfByte(Amt.getStart()),
7307                              /*IsStringLocation*/true,
7308                              getSpecifierRange(startSpecifier, specifierLen));
7309         // Don't do any more checking.  We will just emit
7310         // spurious errors.
7311         return false;
7312       }
7313     }
7314   }
7315   return true;
7316 }
7317 
7318 void CheckPrintfHandler::HandleInvalidAmount(
7319                                       const analyze_printf::PrintfSpecifier &FS,
7320                                       const analyze_printf::OptionalAmount &Amt,
7321                                       unsigned type,
7322                                       const char *startSpecifier,
7323                                       unsigned specifierLen) {
7324   const analyze_printf::PrintfConversionSpecifier &CS =
7325     FS.getConversionSpecifier();
7326 
7327   FixItHint fixit =
7328     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7329       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7330                                  Amt.getConstantLength()))
7331       : FixItHint();
7332 
7333   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7334                          << type << CS.toString(),
7335                        getLocationOfByte(Amt.getStart()),
7336                        /*IsStringLocation*/true,
7337                        getSpecifierRange(startSpecifier, specifierLen),
7338                        fixit);
7339 }
7340 
7341 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7342                                     const analyze_printf::OptionalFlag &flag,
7343                                     const char *startSpecifier,
7344                                     unsigned specifierLen) {
7345   // Warn about pointless flag with a fixit removal.
7346   const analyze_printf::PrintfConversionSpecifier &CS =
7347     FS.getConversionSpecifier();
7348   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7349                          << flag.toString() << CS.toString(),
7350                        getLocationOfByte(flag.getPosition()),
7351                        /*IsStringLocation*/true,
7352                        getSpecifierRange(startSpecifier, specifierLen),
7353                        FixItHint::CreateRemoval(
7354                          getSpecifierRange(flag.getPosition(), 1)));
7355 }
7356 
7357 void CheckPrintfHandler::HandleIgnoredFlag(
7358                                 const analyze_printf::PrintfSpecifier &FS,
7359                                 const analyze_printf::OptionalFlag &ignoredFlag,
7360                                 const analyze_printf::OptionalFlag &flag,
7361                                 const char *startSpecifier,
7362                                 unsigned specifierLen) {
7363   // Warn about ignored flag with a fixit removal.
7364   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7365                          << ignoredFlag.toString() << flag.toString(),
7366                        getLocationOfByte(ignoredFlag.getPosition()),
7367                        /*IsStringLocation*/true,
7368                        getSpecifierRange(startSpecifier, specifierLen),
7369                        FixItHint::CreateRemoval(
7370                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7371 }
7372 
7373 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7374                                                      unsigned flagLen) {
7375   // Warn about an empty flag.
7376   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7377                        getLocationOfByte(startFlag),
7378                        /*IsStringLocation*/true,
7379                        getSpecifierRange(startFlag, flagLen));
7380 }
7381 
7382 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7383                                                        unsigned flagLen) {
7384   // Warn about an invalid flag.
7385   auto Range = getSpecifierRange(startFlag, flagLen);
7386   StringRef flag(startFlag, flagLen);
7387   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7388                       getLocationOfByte(startFlag),
7389                       /*IsStringLocation*/true,
7390                       Range, FixItHint::CreateRemoval(Range));
7391 }
7392 
7393 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7394     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7395     // Warn about using '[...]' without a '@' conversion.
7396     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7397     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7398     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7399                          getLocationOfByte(conversionPosition),
7400                          /*IsStringLocation*/true,
7401                          Range, FixItHint::CreateRemoval(Range));
7402 }
7403 
7404 // Determines if the specified is a C++ class or struct containing
7405 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7406 // "c_str()").
7407 template<typename MemberKind>
7408 static llvm::SmallPtrSet<MemberKind*, 1>
7409 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7410   const RecordType *RT = Ty->getAs<RecordType>();
7411   llvm::SmallPtrSet<MemberKind*, 1> Results;
7412 
7413   if (!RT)
7414     return Results;
7415   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7416   if (!RD || !RD->getDefinition())
7417     return Results;
7418 
7419   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7420                  Sema::LookupMemberName);
7421   R.suppressDiagnostics();
7422 
7423   // We just need to include all members of the right kind turned up by the
7424   // filter, at this point.
7425   if (S.LookupQualifiedName(R, RT->getDecl()))
7426     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7427       NamedDecl *decl = (*I)->getUnderlyingDecl();
7428       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7429         Results.insert(FK);
7430     }
7431   return Results;
7432 }
7433 
7434 /// Check if we could call '.c_str()' on an object.
7435 ///
7436 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7437 /// allow the call, or if it would be ambiguous).
7438 bool Sema::hasCStrMethod(const Expr *E) {
7439   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7440 
7441   MethodSet Results =
7442       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7443   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7444        MI != ME; ++MI)
7445     if ((*MI)->getMinRequiredArguments() == 0)
7446       return true;
7447   return false;
7448 }
7449 
7450 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7451 // better diagnostic if so. AT is assumed to be valid.
7452 // Returns true when a c_str() conversion method is found.
7453 bool CheckPrintfHandler::checkForCStrMembers(
7454     const analyze_printf::ArgType &AT, const Expr *E) {
7455   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7456 
7457   MethodSet Results =
7458       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7459 
7460   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7461        MI != ME; ++MI) {
7462     const CXXMethodDecl *Method = *MI;
7463     if (Method->getMinRequiredArguments() == 0 &&
7464         AT.matchesType(S.Context, Method->getReturnType())) {
7465       // FIXME: Suggest parens if the expression needs them.
7466       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7467       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7468           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7469       return true;
7470     }
7471   }
7472 
7473   return false;
7474 }
7475 
7476 bool
7477 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7478                                             &FS,
7479                                           const char *startSpecifier,
7480                                           unsigned specifierLen) {
7481   using namespace analyze_format_string;
7482   using namespace analyze_printf;
7483 
7484   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7485 
7486   if (FS.consumesDataArgument()) {
7487     if (atFirstArg) {
7488         atFirstArg = false;
7489         usesPositionalArgs = FS.usesPositionalArg();
7490     }
7491     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7492       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7493                                         startSpecifier, specifierLen);
7494       return false;
7495     }
7496   }
7497 
7498   // First check if the field width, precision, and conversion specifier
7499   // have matching data arguments.
7500   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7501                     startSpecifier, specifierLen)) {
7502     return false;
7503   }
7504 
7505   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7506                     startSpecifier, specifierLen)) {
7507     return false;
7508   }
7509 
7510   if (!CS.consumesDataArgument()) {
7511     // FIXME: Technically specifying a precision or field width here
7512     // makes no sense.  Worth issuing a warning at some point.
7513     return true;
7514   }
7515 
7516   // Consume the argument.
7517   unsigned argIndex = FS.getArgIndex();
7518   if (argIndex < NumDataArgs) {
7519     // The check to see if the argIndex is valid will come later.
7520     // We set the bit here because we may exit early from this
7521     // function if we encounter some other error.
7522     CoveredArgs.set(argIndex);
7523   }
7524 
7525   // FreeBSD kernel extensions.
7526   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7527       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7528     // We need at least two arguments.
7529     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7530       return false;
7531 
7532     // Claim the second argument.
7533     CoveredArgs.set(argIndex + 1);
7534 
7535     // Type check the first argument (int for %b, pointer for %D)
7536     const Expr *Ex = getDataArg(argIndex);
7537     const analyze_printf::ArgType &AT =
7538       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7539         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7540     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7541       EmitFormatDiagnostic(
7542           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7543               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7544               << false << Ex->getSourceRange(),
7545           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7546           getSpecifierRange(startSpecifier, specifierLen));
7547 
7548     // Type check the second argument (char * for both %b and %D)
7549     Ex = getDataArg(argIndex + 1);
7550     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7551     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7552       EmitFormatDiagnostic(
7553           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7554               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7555               << false << Ex->getSourceRange(),
7556           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7557           getSpecifierRange(startSpecifier, specifierLen));
7558 
7559      return true;
7560   }
7561 
7562   // Check for using an Objective-C specific conversion specifier
7563   // in a non-ObjC literal.
7564   if (!allowsObjCArg() && CS.isObjCArg()) {
7565     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7566                                                   specifierLen);
7567   }
7568 
7569   // %P can only be used with os_log.
7570   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7571     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7572                                                   specifierLen);
7573   }
7574 
7575   // %n is not allowed with os_log.
7576   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7577     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7578                          getLocationOfByte(CS.getStart()),
7579                          /*IsStringLocation*/ false,
7580                          getSpecifierRange(startSpecifier, specifierLen));
7581 
7582     return true;
7583   }
7584 
7585   // Only scalars are allowed for os_trace.
7586   if (FSType == Sema::FST_OSTrace &&
7587       (CS.getKind() == ConversionSpecifier::PArg ||
7588        CS.getKind() == ConversionSpecifier::sArg ||
7589        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7590     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7591                                                   specifierLen);
7592   }
7593 
7594   // Check for use of public/private annotation outside of os_log().
7595   if (FSType != Sema::FST_OSLog) {
7596     if (FS.isPublic().isSet()) {
7597       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7598                                << "public",
7599                            getLocationOfByte(FS.isPublic().getPosition()),
7600                            /*IsStringLocation*/ false,
7601                            getSpecifierRange(startSpecifier, specifierLen));
7602     }
7603     if (FS.isPrivate().isSet()) {
7604       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7605                                << "private",
7606                            getLocationOfByte(FS.isPrivate().getPosition()),
7607                            /*IsStringLocation*/ false,
7608                            getSpecifierRange(startSpecifier, specifierLen));
7609     }
7610   }
7611 
7612   // Check for invalid use of field width
7613   if (!FS.hasValidFieldWidth()) {
7614     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7615         startSpecifier, specifierLen);
7616   }
7617 
7618   // Check for invalid use of precision
7619   if (!FS.hasValidPrecision()) {
7620     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7621         startSpecifier, specifierLen);
7622   }
7623 
7624   // Precision is mandatory for %P specifier.
7625   if (CS.getKind() == ConversionSpecifier::PArg &&
7626       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7627     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7628                          getLocationOfByte(startSpecifier),
7629                          /*IsStringLocation*/ false,
7630                          getSpecifierRange(startSpecifier, specifierLen));
7631   }
7632 
7633   // Check each flag does not conflict with any other component.
7634   if (!FS.hasValidThousandsGroupingPrefix())
7635     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7636   if (!FS.hasValidLeadingZeros())
7637     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7638   if (!FS.hasValidPlusPrefix())
7639     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7640   if (!FS.hasValidSpacePrefix())
7641     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7642   if (!FS.hasValidAlternativeForm())
7643     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7644   if (!FS.hasValidLeftJustified())
7645     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7646 
7647   // Check that flags are not ignored by another flag
7648   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7649     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7650         startSpecifier, specifierLen);
7651   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7652     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7653             startSpecifier, specifierLen);
7654 
7655   // Check the length modifier is valid with the given conversion specifier.
7656   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7657     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7658                                 diag::warn_format_nonsensical_length);
7659   else if (!FS.hasStandardLengthModifier())
7660     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7661   else if (!FS.hasStandardLengthConversionCombination())
7662     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7663                                 diag::warn_format_non_standard_conversion_spec);
7664 
7665   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7666     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7667 
7668   // The remaining checks depend on the data arguments.
7669   if (HasVAListArg)
7670     return true;
7671 
7672   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7673     return false;
7674 
7675   const Expr *Arg = getDataArg(argIndex);
7676   if (!Arg)
7677     return true;
7678 
7679   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7680 }
7681 
7682 static bool requiresParensToAddCast(const Expr *E) {
7683   // FIXME: We should have a general way to reason about operator
7684   // precedence and whether parens are actually needed here.
7685   // Take care of a few common cases where they aren't.
7686   const Expr *Inside = E->IgnoreImpCasts();
7687   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7688     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7689 
7690   switch (Inside->getStmtClass()) {
7691   case Stmt::ArraySubscriptExprClass:
7692   case Stmt::CallExprClass:
7693   case Stmt::CharacterLiteralClass:
7694   case Stmt::CXXBoolLiteralExprClass:
7695   case Stmt::DeclRefExprClass:
7696   case Stmt::FloatingLiteralClass:
7697   case Stmt::IntegerLiteralClass:
7698   case Stmt::MemberExprClass:
7699   case Stmt::ObjCArrayLiteralClass:
7700   case Stmt::ObjCBoolLiteralExprClass:
7701   case Stmt::ObjCBoxedExprClass:
7702   case Stmt::ObjCDictionaryLiteralClass:
7703   case Stmt::ObjCEncodeExprClass:
7704   case Stmt::ObjCIvarRefExprClass:
7705   case Stmt::ObjCMessageExprClass:
7706   case Stmt::ObjCPropertyRefExprClass:
7707   case Stmt::ObjCStringLiteralClass:
7708   case Stmt::ObjCSubscriptRefExprClass:
7709   case Stmt::ParenExprClass:
7710   case Stmt::StringLiteralClass:
7711   case Stmt::UnaryOperatorClass:
7712     return false;
7713   default:
7714     return true;
7715   }
7716 }
7717 
7718 static std::pair<QualType, StringRef>
7719 shouldNotPrintDirectly(const ASTContext &Context,
7720                        QualType IntendedTy,
7721                        const Expr *E) {
7722   // Use a 'while' to peel off layers of typedefs.
7723   QualType TyTy = IntendedTy;
7724   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7725     StringRef Name = UserTy->getDecl()->getName();
7726     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7727       .Case("CFIndex", Context.getNSIntegerType())
7728       .Case("NSInteger", Context.getNSIntegerType())
7729       .Case("NSUInteger", Context.getNSUIntegerType())
7730       .Case("SInt32", Context.IntTy)
7731       .Case("UInt32", Context.UnsignedIntTy)
7732       .Default(QualType());
7733 
7734     if (!CastTy.isNull())
7735       return std::make_pair(CastTy, Name);
7736 
7737     TyTy = UserTy->desugar();
7738   }
7739 
7740   // Strip parens if necessary.
7741   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7742     return shouldNotPrintDirectly(Context,
7743                                   PE->getSubExpr()->getType(),
7744                                   PE->getSubExpr());
7745 
7746   // If this is a conditional expression, then its result type is constructed
7747   // via usual arithmetic conversions and thus there might be no necessary
7748   // typedef sugar there.  Recurse to operands to check for NSInteger &
7749   // Co. usage condition.
7750   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7751     QualType TrueTy, FalseTy;
7752     StringRef TrueName, FalseName;
7753 
7754     std::tie(TrueTy, TrueName) =
7755       shouldNotPrintDirectly(Context,
7756                              CO->getTrueExpr()->getType(),
7757                              CO->getTrueExpr());
7758     std::tie(FalseTy, FalseName) =
7759       shouldNotPrintDirectly(Context,
7760                              CO->getFalseExpr()->getType(),
7761                              CO->getFalseExpr());
7762 
7763     if (TrueTy == FalseTy)
7764       return std::make_pair(TrueTy, TrueName);
7765     else if (TrueTy.isNull())
7766       return std::make_pair(FalseTy, FalseName);
7767     else if (FalseTy.isNull())
7768       return std::make_pair(TrueTy, TrueName);
7769   }
7770 
7771   return std::make_pair(QualType(), StringRef());
7772 }
7773 
7774 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7775 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7776 /// type do not count.
7777 static bool
7778 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7779   QualType From = ICE->getSubExpr()->getType();
7780   QualType To = ICE->getType();
7781   // It's an integer promotion if the destination type is the promoted
7782   // source type.
7783   if (ICE->getCastKind() == CK_IntegralCast &&
7784       From->isPromotableIntegerType() &&
7785       S.Context.getPromotedIntegerType(From) == To)
7786     return true;
7787   // Look through vector types, since we do default argument promotion for
7788   // those in OpenCL.
7789   if (const auto *VecTy = From->getAs<ExtVectorType>())
7790     From = VecTy->getElementType();
7791   if (const auto *VecTy = To->getAs<ExtVectorType>())
7792     To = VecTy->getElementType();
7793   // It's a floating promotion if the source type is a lower rank.
7794   return ICE->getCastKind() == CK_FloatingCast &&
7795          S.Context.getFloatingTypeOrder(From, To) < 0;
7796 }
7797 
7798 bool
7799 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7800                                     const char *StartSpecifier,
7801                                     unsigned SpecifierLen,
7802                                     const Expr *E) {
7803   using namespace analyze_format_string;
7804   using namespace analyze_printf;
7805 
7806   // Now type check the data expression that matches the
7807   // format specifier.
7808   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7809   if (!AT.isValid())
7810     return true;
7811 
7812   QualType ExprTy = E->getType();
7813   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7814     ExprTy = TET->getUnderlyingExpr()->getType();
7815   }
7816 
7817   const analyze_printf::ArgType::MatchKind Match =
7818       AT.matchesType(S.Context, ExprTy);
7819   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7820   if (Match == analyze_printf::ArgType::Match)
7821     return true;
7822 
7823   // Look through argument promotions for our error message's reported type.
7824   // This includes the integral and floating promotions, but excludes array
7825   // and function pointer decay (seeing that an argument intended to be a
7826   // string has type 'char [6]' is probably more confusing than 'char *') and
7827   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7828   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7829     if (isArithmeticArgumentPromotion(S, ICE)) {
7830       E = ICE->getSubExpr();
7831       ExprTy = E->getType();
7832 
7833       // Check if we didn't match because of an implicit cast from a 'char'
7834       // or 'short' to an 'int'.  This is done because printf is a varargs
7835       // function.
7836       if (ICE->getType() == S.Context.IntTy ||
7837           ICE->getType() == S.Context.UnsignedIntTy) {
7838         // All further checking is done on the subexpression.
7839         if (AT.matchesType(S.Context, ExprTy))
7840           return true;
7841       }
7842     }
7843   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7844     // Special case for 'a', which has type 'int' in C.
7845     // Note, however, that we do /not/ want to treat multibyte constants like
7846     // 'MooV' as characters! This form is deprecated but still exists.
7847     if (ExprTy == S.Context.IntTy)
7848       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7849         ExprTy = S.Context.CharTy;
7850   }
7851 
7852   // Look through enums to their underlying type.
7853   bool IsEnum = false;
7854   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7855     ExprTy = EnumTy->getDecl()->getIntegerType();
7856     IsEnum = true;
7857   }
7858 
7859   // %C in an Objective-C context prints a unichar, not a wchar_t.
7860   // If the argument is an integer of some kind, believe the %C and suggest
7861   // a cast instead of changing the conversion specifier.
7862   QualType IntendedTy = ExprTy;
7863   if (isObjCContext() &&
7864       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7865     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7866         !ExprTy->isCharType()) {
7867       // 'unichar' is defined as a typedef of unsigned short, but we should
7868       // prefer using the typedef if it is visible.
7869       IntendedTy = S.Context.UnsignedShortTy;
7870 
7871       // While we are here, check if the value is an IntegerLiteral that happens
7872       // to be within the valid range.
7873       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7874         const llvm::APInt &V = IL->getValue();
7875         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7876           return true;
7877       }
7878 
7879       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7880                           Sema::LookupOrdinaryName);
7881       if (S.LookupName(Result, S.getCurScope())) {
7882         NamedDecl *ND = Result.getFoundDecl();
7883         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7884           if (TD->getUnderlyingType() == IntendedTy)
7885             IntendedTy = S.Context.getTypedefType(TD);
7886       }
7887     }
7888   }
7889 
7890   // Special-case some of Darwin's platform-independence types by suggesting
7891   // casts to primitive types that are known to be large enough.
7892   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7893   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7894     QualType CastTy;
7895     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7896     if (!CastTy.isNull()) {
7897       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7898       // (long in ASTContext). Only complain to pedants.
7899       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7900           (AT.isSizeT() || AT.isPtrdiffT()) &&
7901           AT.matchesType(S.Context, CastTy))
7902         Pedantic = true;
7903       IntendedTy = CastTy;
7904       ShouldNotPrintDirectly = true;
7905     }
7906   }
7907 
7908   // We may be able to offer a FixItHint if it is a supported type.
7909   PrintfSpecifier fixedFS = FS;
7910   bool Success =
7911       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7912 
7913   if (Success) {
7914     // Get the fix string from the fixed format specifier
7915     SmallString<16> buf;
7916     llvm::raw_svector_ostream os(buf);
7917     fixedFS.toString(os);
7918 
7919     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7920 
7921     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7922       unsigned Diag =
7923           Pedantic
7924               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7925               : diag::warn_format_conversion_argument_type_mismatch;
7926       // In this case, the specifier is wrong and should be changed to match
7927       // the argument.
7928       EmitFormatDiagnostic(S.PDiag(Diag)
7929                                << AT.getRepresentativeTypeName(S.Context)
7930                                << IntendedTy << IsEnum << E->getSourceRange(),
7931                            E->getBeginLoc(),
7932                            /*IsStringLocation*/ false, SpecRange,
7933                            FixItHint::CreateReplacement(SpecRange, os.str()));
7934     } else {
7935       // The canonical type for formatting this value is different from the
7936       // actual type of the expression. (This occurs, for example, with Darwin's
7937       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7938       // should be printed as 'long' for 64-bit compatibility.)
7939       // Rather than emitting a normal format/argument mismatch, we want to
7940       // add a cast to the recommended type (and correct the format string
7941       // if necessary).
7942       SmallString<16> CastBuf;
7943       llvm::raw_svector_ostream CastFix(CastBuf);
7944       CastFix << "(";
7945       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7946       CastFix << ")";
7947 
7948       SmallVector<FixItHint,4> Hints;
7949       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
7950         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7951 
7952       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7953         // If there's already a cast present, just replace it.
7954         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7955         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7956 
7957       } else if (!requiresParensToAddCast(E)) {
7958         // If the expression has high enough precedence,
7959         // just write the C-style cast.
7960         Hints.push_back(
7961             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7962       } else {
7963         // Otherwise, add parens around the expression as well as the cast.
7964         CastFix << "(";
7965         Hints.push_back(
7966             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7967 
7968         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
7969         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7970       }
7971 
7972       if (ShouldNotPrintDirectly) {
7973         // The expression has a type that should not be printed directly.
7974         // We extract the name from the typedef because we don't want to show
7975         // the underlying type in the diagnostic.
7976         StringRef Name;
7977         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7978           Name = TypedefTy->getDecl()->getName();
7979         else
7980           Name = CastTyName;
7981         unsigned Diag = Pedantic
7982                             ? diag::warn_format_argument_needs_cast_pedantic
7983                             : diag::warn_format_argument_needs_cast;
7984         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7985                                            << E->getSourceRange(),
7986                              E->getBeginLoc(), /*IsStringLocation=*/false,
7987                              SpecRange, Hints);
7988       } else {
7989         // In this case, the expression could be printed using a different
7990         // specifier, but we've decided that the specifier is probably correct
7991         // and we should cast instead. Just use the normal warning message.
7992         EmitFormatDiagnostic(
7993             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7994                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7995                 << E->getSourceRange(),
7996             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7997       }
7998     }
7999   } else {
8000     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8001                                                    SpecifierLen);
8002     // Since the warning for passing non-POD types to variadic functions
8003     // was deferred until now, we emit a warning for non-POD
8004     // arguments here.
8005     switch (S.isValidVarArgType(ExprTy)) {
8006     case Sema::VAK_Valid:
8007     case Sema::VAK_ValidInCXX11: {
8008       unsigned Diag =
8009           Pedantic
8010               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8011               : diag::warn_format_conversion_argument_type_mismatch;
8012 
8013       EmitFormatDiagnostic(
8014           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8015                         << IsEnum << CSR << E->getSourceRange(),
8016           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8017       break;
8018     }
8019     case Sema::VAK_Undefined:
8020     case Sema::VAK_MSVCUndefined:
8021       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8022                                << S.getLangOpts().CPlusPlus11 << ExprTy
8023                                << CallType
8024                                << AT.getRepresentativeTypeName(S.Context) << CSR
8025                                << E->getSourceRange(),
8026                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8027       checkForCStrMembers(AT, E);
8028       break;
8029 
8030     case Sema::VAK_Invalid:
8031       if (ExprTy->isObjCObjectType())
8032         EmitFormatDiagnostic(
8033             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8034                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8035                 << AT.getRepresentativeTypeName(S.Context) << CSR
8036                 << E->getSourceRange(),
8037             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8038       else
8039         // FIXME: If this is an initializer list, suggest removing the braces
8040         // or inserting a cast to the target type.
8041         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8042             << isa<InitListExpr>(E) << ExprTy << CallType
8043             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8044       break;
8045     }
8046 
8047     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8048            "format string specifier index out of range");
8049     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8050   }
8051 
8052   return true;
8053 }
8054 
8055 //===--- CHECK: Scanf format string checking ------------------------------===//
8056 
8057 namespace {
8058 
8059 class CheckScanfHandler : public CheckFormatHandler {
8060 public:
8061   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8062                     const Expr *origFormatExpr, Sema::FormatStringType type,
8063                     unsigned firstDataArg, unsigned numDataArgs,
8064                     const char *beg, bool hasVAListArg,
8065                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8066                     bool inFunctionCall, Sema::VariadicCallType CallType,
8067                     llvm::SmallBitVector &CheckedVarArgs,
8068                     UncoveredArgHandler &UncoveredArg)
8069       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8070                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8071                            inFunctionCall, CallType, CheckedVarArgs,
8072                            UncoveredArg) {}
8073 
8074   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8075                             const char *startSpecifier,
8076                             unsigned specifierLen) override;
8077 
8078   bool HandleInvalidScanfConversionSpecifier(
8079           const analyze_scanf::ScanfSpecifier &FS,
8080           const char *startSpecifier,
8081           unsigned specifierLen) override;
8082 
8083   void HandleIncompleteScanList(const char *start, const char *end) override;
8084 };
8085 
8086 } // namespace
8087 
8088 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8089                                                  const char *end) {
8090   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8091                        getLocationOfByte(end), /*IsStringLocation*/true,
8092                        getSpecifierRange(start, end - start));
8093 }
8094 
8095 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8096                                         const analyze_scanf::ScanfSpecifier &FS,
8097                                         const char *startSpecifier,
8098                                         unsigned specifierLen) {
8099   const analyze_scanf::ScanfConversionSpecifier &CS =
8100     FS.getConversionSpecifier();
8101 
8102   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8103                                           getLocationOfByte(CS.getStart()),
8104                                           startSpecifier, specifierLen,
8105                                           CS.getStart(), CS.getLength());
8106 }
8107 
8108 bool CheckScanfHandler::HandleScanfSpecifier(
8109                                        const analyze_scanf::ScanfSpecifier &FS,
8110                                        const char *startSpecifier,
8111                                        unsigned specifierLen) {
8112   using namespace analyze_scanf;
8113   using namespace analyze_format_string;
8114 
8115   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8116 
8117   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8118   // be used to decide if we are using positional arguments consistently.
8119   if (FS.consumesDataArgument()) {
8120     if (atFirstArg) {
8121       atFirstArg = false;
8122       usesPositionalArgs = FS.usesPositionalArg();
8123     }
8124     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8125       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8126                                         startSpecifier, specifierLen);
8127       return false;
8128     }
8129   }
8130 
8131   // Check if the field with is non-zero.
8132   const OptionalAmount &Amt = FS.getFieldWidth();
8133   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8134     if (Amt.getConstantAmount() == 0) {
8135       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8136                                                    Amt.getConstantLength());
8137       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8138                            getLocationOfByte(Amt.getStart()),
8139                            /*IsStringLocation*/true, R,
8140                            FixItHint::CreateRemoval(R));
8141     }
8142   }
8143 
8144   if (!FS.consumesDataArgument()) {
8145     // FIXME: Technically specifying a precision or field width here
8146     // makes no sense.  Worth issuing a warning at some point.
8147     return true;
8148   }
8149 
8150   // Consume the argument.
8151   unsigned argIndex = FS.getArgIndex();
8152   if (argIndex < NumDataArgs) {
8153       // The check to see if the argIndex is valid will come later.
8154       // We set the bit here because we may exit early from this
8155       // function if we encounter some other error.
8156     CoveredArgs.set(argIndex);
8157   }
8158 
8159   // Check the length modifier is valid with the given conversion specifier.
8160   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
8161     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8162                                 diag::warn_format_nonsensical_length);
8163   else if (!FS.hasStandardLengthModifier())
8164     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8165   else if (!FS.hasStandardLengthConversionCombination())
8166     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8167                                 diag::warn_format_non_standard_conversion_spec);
8168 
8169   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8170     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8171 
8172   // The remaining checks depend on the data arguments.
8173   if (HasVAListArg)
8174     return true;
8175 
8176   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8177     return false;
8178 
8179   // Check that the argument type matches the format specifier.
8180   const Expr *Ex = getDataArg(argIndex);
8181   if (!Ex)
8182     return true;
8183 
8184   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8185 
8186   if (!AT.isValid()) {
8187     return true;
8188   }
8189 
8190   analyze_format_string::ArgType::MatchKind Match =
8191       AT.matchesType(S.Context, Ex->getType());
8192   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8193   if (Match == analyze_format_string::ArgType::Match)
8194     return true;
8195 
8196   ScanfSpecifier fixedFS = FS;
8197   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8198                                  S.getLangOpts(), S.Context);
8199 
8200   unsigned Diag =
8201       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8202                : diag::warn_format_conversion_argument_type_mismatch;
8203 
8204   if (Success) {
8205     // Get the fix string from the fixed format specifier.
8206     SmallString<128> buf;
8207     llvm::raw_svector_ostream os(buf);
8208     fixedFS.toString(os);
8209 
8210     EmitFormatDiagnostic(
8211         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8212                       << Ex->getType() << false << Ex->getSourceRange(),
8213         Ex->getBeginLoc(),
8214         /*IsStringLocation*/ false,
8215         getSpecifierRange(startSpecifier, specifierLen),
8216         FixItHint::CreateReplacement(
8217             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8218   } else {
8219     EmitFormatDiagnostic(S.PDiag(Diag)
8220                              << AT.getRepresentativeTypeName(S.Context)
8221                              << Ex->getType() << false << Ex->getSourceRange(),
8222                          Ex->getBeginLoc(),
8223                          /*IsStringLocation*/ false,
8224                          getSpecifierRange(startSpecifier, specifierLen));
8225   }
8226 
8227   return true;
8228 }
8229 
8230 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8231                               const Expr *OrigFormatExpr,
8232                               ArrayRef<const Expr *> Args,
8233                               bool HasVAListArg, unsigned format_idx,
8234                               unsigned firstDataArg,
8235                               Sema::FormatStringType Type,
8236                               bool inFunctionCall,
8237                               Sema::VariadicCallType CallType,
8238                               llvm::SmallBitVector &CheckedVarArgs,
8239                               UncoveredArgHandler &UncoveredArg) {
8240   // CHECK: is the format string a wide literal?
8241   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8242     CheckFormatHandler::EmitFormatDiagnostic(
8243         S, inFunctionCall, Args[format_idx],
8244         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8245         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8246     return;
8247   }
8248 
8249   // Str - The format string.  NOTE: this is NOT null-terminated!
8250   StringRef StrRef = FExpr->getString();
8251   const char *Str = StrRef.data();
8252   // Account for cases where the string literal is truncated in a declaration.
8253   const ConstantArrayType *T =
8254     S.Context.getAsConstantArrayType(FExpr->getType());
8255   assert(T && "String literal not of constant array type!");
8256   size_t TypeSize = T->getSize().getZExtValue();
8257   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8258   const unsigned numDataArgs = Args.size() - firstDataArg;
8259 
8260   // Emit a warning if the string literal is truncated and does not contain an
8261   // embedded null character.
8262   if (TypeSize <= StrRef.size() &&
8263       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8264     CheckFormatHandler::EmitFormatDiagnostic(
8265         S, inFunctionCall, Args[format_idx],
8266         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8267         FExpr->getBeginLoc(),
8268         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8269     return;
8270   }
8271 
8272   // CHECK: empty format string?
8273   if (StrLen == 0 && numDataArgs > 0) {
8274     CheckFormatHandler::EmitFormatDiagnostic(
8275         S, inFunctionCall, Args[format_idx],
8276         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8277         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8278     return;
8279   }
8280 
8281   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8282       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8283       Type == Sema::FST_OSTrace) {
8284     CheckPrintfHandler H(
8285         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8286         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8287         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8288         CheckedVarArgs, UncoveredArg);
8289 
8290     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8291                                                   S.getLangOpts(),
8292                                                   S.Context.getTargetInfo(),
8293                                             Type == Sema::FST_FreeBSDKPrintf))
8294       H.DoneProcessing();
8295   } else if (Type == Sema::FST_Scanf) {
8296     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8297                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8298                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8299 
8300     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8301                                                  S.getLangOpts(),
8302                                                  S.Context.getTargetInfo()))
8303       H.DoneProcessing();
8304   } // TODO: handle other formats
8305 }
8306 
8307 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8308   // Str - The format string.  NOTE: this is NOT null-terminated!
8309   StringRef StrRef = FExpr->getString();
8310   const char *Str = StrRef.data();
8311   // Account for cases where the string literal is truncated in a declaration.
8312   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8313   assert(T && "String literal not of constant array type!");
8314   size_t TypeSize = T->getSize().getZExtValue();
8315   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8316   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8317                                                          getLangOpts(),
8318                                                          Context.getTargetInfo());
8319 }
8320 
8321 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8322 
8323 // Returns the related absolute value function that is larger, of 0 if one
8324 // does not exist.
8325 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8326   switch (AbsFunction) {
8327   default:
8328     return 0;
8329 
8330   case Builtin::BI__builtin_abs:
8331     return Builtin::BI__builtin_labs;
8332   case Builtin::BI__builtin_labs:
8333     return Builtin::BI__builtin_llabs;
8334   case Builtin::BI__builtin_llabs:
8335     return 0;
8336 
8337   case Builtin::BI__builtin_fabsf:
8338     return Builtin::BI__builtin_fabs;
8339   case Builtin::BI__builtin_fabs:
8340     return Builtin::BI__builtin_fabsl;
8341   case Builtin::BI__builtin_fabsl:
8342     return 0;
8343 
8344   case Builtin::BI__builtin_cabsf:
8345     return Builtin::BI__builtin_cabs;
8346   case Builtin::BI__builtin_cabs:
8347     return Builtin::BI__builtin_cabsl;
8348   case Builtin::BI__builtin_cabsl:
8349     return 0;
8350 
8351   case Builtin::BIabs:
8352     return Builtin::BIlabs;
8353   case Builtin::BIlabs:
8354     return Builtin::BIllabs;
8355   case Builtin::BIllabs:
8356     return 0;
8357 
8358   case Builtin::BIfabsf:
8359     return Builtin::BIfabs;
8360   case Builtin::BIfabs:
8361     return Builtin::BIfabsl;
8362   case Builtin::BIfabsl:
8363     return 0;
8364 
8365   case Builtin::BIcabsf:
8366    return Builtin::BIcabs;
8367   case Builtin::BIcabs:
8368     return Builtin::BIcabsl;
8369   case Builtin::BIcabsl:
8370     return 0;
8371   }
8372 }
8373 
8374 // Returns the argument type of the absolute value function.
8375 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8376                                              unsigned AbsType) {
8377   if (AbsType == 0)
8378     return QualType();
8379 
8380   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8381   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8382   if (Error != ASTContext::GE_None)
8383     return QualType();
8384 
8385   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8386   if (!FT)
8387     return QualType();
8388 
8389   if (FT->getNumParams() != 1)
8390     return QualType();
8391 
8392   return FT->getParamType(0);
8393 }
8394 
8395 // Returns the best absolute value function, or zero, based on type and
8396 // current absolute value function.
8397 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8398                                    unsigned AbsFunctionKind) {
8399   unsigned BestKind = 0;
8400   uint64_t ArgSize = Context.getTypeSize(ArgType);
8401   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8402        Kind = getLargerAbsoluteValueFunction(Kind)) {
8403     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8404     if (Context.getTypeSize(ParamType) >= ArgSize) {
8405       if (BestKind == 0)
8406         BestKind = Kind;
8407       else if (Context.hasSameType(ParamType, ArgType)) {
8408         BestKind = Kind;
8409         break;
8410       }
8411     }
8412   }
8413   return BestKind;
8414 }
8415 
8416 enum AbsoluteValueKind {
8417   AVK_Integer,
8418   AVK_Floating,
8419   AVK_Complex
8420 };
8421 
8422 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8423   if (T->isIntegralOrEnumerationType())
8424     return AVK_Integer;
8425   if (T->isRealFloatingType())
8426     return AVK_Floating;
8427   if (T->isAnyComplexType())
8428     return AVK_Complex;
8429 
8430   llvm_unreachable("Type not integer, floating, or complex");
8431 }
8432 
8433 // Changes the absolute value function to a different type.  Preserves whether
8434 // the function is a builtin.
8435 static unsigned changeAbsFunction(unsigned AbsKind,
8436                                   AbsoluteValueKind ValueKind) {
8437   switch (ValueKind) {
8438   case AVK_Integer:
8439     switch (AbsKind) {
8440     default:
8441       return 0;
8442     case Builtin::BI__builtin_fabsf:
8443     case Builtin::BI__builtin_fabs:
8444     case Builtin::BI__builtin_fabsl:
8445     case Builtin::BI__builtin_cabsf:
8446     case Builtin::BI__builtin_cabs:
8447     case Builtin::BI__builtin_cabsl:
8448       return Builtin::BI__builtin_abs;
8449     case Builtin::BIfabsf:
8450     case Builtin::BIfabs:
8451     case Builtin::BIfabsl:
8452     case Builtin::BIcabsf:
8453     case Builtin::BIcabs:
8454     case Builtin::BIcabsl:
8455       return Builtin::BIabs;
8456     }
8457   case AVK_Floating:
8458     switch (AbsKind) {
8459     default:
8460       return 0;
8461     case Builtin::BI__builtin_abs:
8462     case Builtin::BI__builtin_labs:
8463     case Builtin::BI__builtin_llabs:
8464     case Builtin::BI__builtin_cabsf:
8465     case Builtin::BI__builtin_cabs:
8466     case Builtin::BI__builtin_cabsl:
8467       return Builtin::BI__builtin_fabsf;
8468     case Builtin::BIabs:
8469     case Builtin::BIlabs:
8470     case Builtin::BIllabs:
8471     case Builtin::BIcabsf:
8472     case Builtin::BIcabs:
8473     case Builtin::BIcabsl:
8474       return Builtin::BIfabsf;
8475     }
8476   case AVK_Complex:
8477     switch (AbsKind) {
8478     default:
8479       return 0;
8480     case Builtin::BI__builtin_abs:
8481     case Builtin::BI__builtin_labs:
8482     case Builtin::BI__builtin_llabs:
8483     case Builtin::BI__builtin_fabsf:
8484     case Builtin::BI__builtin_fabs:
8485     case Builtin::BI__builtin_fabsl:
8486       return Builtin::BI__builtin_cabsf;
8487     case Builtin::BIabs:
8488     case Builtin::BIlabs:
8489     case Builtin::BIllabs:
8490     case Builtin::BIfabsf:
8491     case Builtin::BIfabs:
8492     case Builtin::BIfabsl:
8493       return Builtin::BIcabsf;
8494     }
8495   }
8496   llvm_unreachable("Unable to convert function");
8497 }
8498 
8499 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8500   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8501   if (!FnInfo)
8502     return 0;
8503 
8504   switch (FDecl->getBuiltinID()) {
8505   default:
8506     return 0;
8507   case Builtin::BI__builtin_abs:
8508   case Builtin::BI__builtin_fabs:
8509   case Builtin::BI__builtin_fabsf:
8510   case Builtin::BI__builtin_fabsl:
8511   case Builtin::BI__builtin_labs:
8512   case Builtin::BI__builtin_llabs:
8513   case Builtin::BI__builtin_cabs:
8514   case Builtin::BI__builtin_cabsf:
8515   case Builtin::BI__builtin_cabsl:
8516   case Builtin::BIabs:
8517   case Builtin::BIlabs:
8518   case Builtin::BIllabs:
8519   case Builtin::BIfabs:
8520   case Builtin::BIfabsf:
8521   case Builtin::BIfabsl:
8522   case Builtin::BIcabs:
8523   case Builtin::BIcabsf:
8524   case Builtin::BIcabsl:
8525     return FDecl->getBuiltinID();
8526   }
8527   llvm_unreachable("Unknown Builtin type");
8528 }
8529 
8530 // If the replacement is valid, emit a note with replacement function.
8531 // Additionally, suggest including the proper header if not already included.
8532 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8533                             unsigned AbsKind, QualType ArgType) {
8534   bool EmitHeaderHint = true;
8535   const char *HeaderName = nullptr;
8536   const char *FunctionName = nullptr;
8537   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8538     FunctionName = "std::abs";
8539     if (ArgType->isIntegralOrEnumerationType()) {
8540       HeaderName = "cstdlib";
8541     } else if (ArgType->isRealFloatingType()) {
8542       HeaderName = "cmath";
8543     } else {
8544       llvm_unreachable("Invalid Type");
8545     }
8546 
8547     // Lookup all std::abs
8548     if (NamespaceDecl *Std = S.getStdNamespace()) {
8549       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8550       R.suppressDiagnostics();
8551       S.LookupQualifiedName(R, Std);
8552 
8553       for (const auto *I : R) {
8554         const FunctionDecl *FDecl = nullptr;
8555         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8556           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8557         } else {
8558           FDecl = dyn_cast<FunctionDecl>(I);
8559         }
8560         if (!FDecl)
8561           continue;
8562 
8563         // Found std::abs(), check that they are the right ones.
8564         if (FDecl->getNumParams() != 1)
8565           continue;
8566 
8567         // Check that the parameter type can handle the argument.
8568         QualType ParamType = FDecl->getParamDecl(0)->getType();
8569         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8570             S.Context.getTypeSize(ArgType) <=
8571                 S.Context.getTypeSize(ParamType)) {
8572           // Found a function, don't need the header hint.
8573           EmitHeaderHint = false;
8574           break;
8575         }
8576       }
8577     }
8578   } else {
8579     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8580     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8581 
8582     if (HeaderName) {
8583       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8584       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8585       R.suppressDiagnostics();
8586       S.LookupName(R, S.getCurScope());
8587 
8588       if (R.isSingleResult()) {
8589         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8590         if (FD && FD->getBuiltinID() == AbsKind) {
8591           EmitHeaderHint = false;
8592         } else {
8593           return;
8594         }
8595       } else if (!R.empty()) {
8596         return;
8597       }
8598     }
8599   }
8600 
8601   S.Diag(Loc, diag::note_replace_abs_function)
8602       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8603 
8604   if (!HeaderName)
8605     return;
8606 
8607   if (!EmitHeaderHint)
8608     return;
8609 
8610   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8611                                                     << FunctionName;
8612 }
8613 
8614 template <std::size_t StrLen>
8615 static bool IsStdFunction(const FunctionDecl *FDecl,
8616                           const char (&Str)[StrLen]) {
8617   if (!FDecl)
8618     return false;
8619   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8620     return false;
8621   if (!FDecl->isInStdNamespace())
8622     return false;
8623 
8624   return true;
8625 }
8626 
8627 // Warn when using the wrong abs() function.
8628 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8629                                       const FunctionDecl *FDecl) {
8630   if (Call->getNumArgs() != 1)
8631     return;
8632 
8633   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8634   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8635   if (AbsKind == 0 && !IsStdAbs)
8636     return;
8637 
8638   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8639   QualType ParamType = Call->getArg(0)->getType();
8640 
8641   // Unsigned types cannot be negative.  Suggest removing the absolute value
8642   // function call.
8643   if (ArgType->isUnsignedIntegerType()) {
8644     const char *FunctionName =
8645         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8646     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8647     Diag(Call->getExprLoc(), diag::note_remove_abs)
8648         << FunctionName
8649         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8650     return;
8651   }
8652 
8653   // Taking the absolute value of a pointer is very suspicious, they probably
8654   // wanted to index into an array, dereference a pointer, call a function, etc.
8655   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8656     unsigned DiagType = 0;
8657     if (ArgType->isFunctionType())
8658       DiagType = 1;
8659     else if (ArgType->isArrayType())
8660       DiagType = 2;
8661 
8662     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8663     return;
8664   }
8665 
8666   // std::abs has overloads which prevent most of the absolute value problems
8667   // from occurring.
8668   if (IsStdAbs)
8669     return;
8670 
8671   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8672   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8673 
8674   // The argument and parameter are the same kind.  Check if they are the right
8675   // size.
8676   if (ArgValueKind == ParamValueKind) {
8677     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8678       return;
8679 
8680     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8681     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8682         << FDecl << ArgType << ParamType;
8683 
8684     if (NewAbsKind == 0)
8685       return;
8686 
8687     emitReplacement(*this, Call->getExprLoc(),
8688                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8689     return;
8690   }
8691 
8692   // ArgValueKind != ParamValueKind
8693   // The wrong type of absolute value function was used.  Attempt to find the
8694   // proper one.
8695   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8696   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8697   if (NewAbsKind == 0)
8698     return;
8699 
8700   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8701       << FDecl << ParamValueKind << ArgValueKind;
8702 
8703   emitReplacement(*this, Call->getExprLoc(),
8704                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8705 }
8706 
8707 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8708 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8709                                 const FunctionDecl *FDecl) {
8710   if (!Call || !FDecl) return;
8711 
8712   // Ignore template specializations and macros.
8713   if (inTemplateInstantiation()) return;
8714   if (Call->getExprLoc().isMacroID()) return;
8715 
8716   // Only care about the one template argument, two function parameter std::max
8717   if (Call->getNumArgs() != 2) return;
8718   if (!IsStdFunction(FDecl, "max")) return;
8719   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8720   if (!ArgList) return;
8721   if (ArgList->size() != 1) return;
8722 
8723   // Check that template type argument is unsigned integer.
8724   const auto& TA = ArgList->get(0);
8725   if (TA.getKind() != TemplateArgument::Type) return;
8726   QualType ArgType = TA.getAsType();
8727   if (!ArgType->isUnsignedIntegerType()) return;
8728 
8729   // See if either argument is a literal zero.
8730   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8731     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8732     if (!MTE) return false;
8733     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8734     if (!Num) return false;
8735     if (Num->getValue() != 0) return false;
8736     return true;
8737   };
8738 
8739   const Expr *FirstArg = Call->getArg(0);
8740   const Expr *SecondArg = Call->getArg(1);
8741   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8742   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8743 
8744   // Only warn when exactly one argument is zero.
8745   if (IsFirstArgZero == IsSecondArgZero) return;
8746 
8747   SourceRange FirstRange = FirstArg->getSourceRange();
8748   SourceRange SecondRange = SecondArg->getSourceRange();
8749 
8750   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8751 
8752   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8753       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8754 
8755   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8756   SourceRange RemovalRange;
8757   if (IsFirstArgZero) {
8758     RemovalRange = SourceRange(FirstRange.getBegin(),
8759                                SecondRange.getBegin().getLocWithOffset(-1));
8760   } else {
8761     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8762                                SecondRange.getEnd());
8763   }
8764 
8765   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8766         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8767         << FixItHint::CreateRemoval(RemovalRange);
8768 }
8769 
8770 //===--- CHECK: Standard memory functions ---------------------------------===//
8771 
8772 /// Takes the expression passed to the size_t parameter of functions
8773 /// such as memcmp, strncat, etc and warns if it's a comparison.
8774 ///
8775 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8776 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8777                                            IdentifierInfo *FnName,
8778                                            SourceLocation FnLoc,
8779                                            SourceLocation RParenLoc) {
8780   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8781   if (!Size)
8782     return false;
8783 
8784   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8785   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8786     return false;
8787 
8788   SourceRange SizeRange = Size->getSourceRange();
8789   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8790       << SizeRange << FnName;
8791   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8792       << FnName
8793       << FixItHint::CreateInsertion(
8794              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8795       << FixItHint::CreateRemoval(RParenLoc);
8796   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8797       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8798       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8799                                     ")");
8800 
8801   return true;
8802 }
8803 
8804 /// Determine whether the given type is or contains a dynamic class type
8805 /// (e.g., whether it has a vtable).
8806 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8807                                                      bool &IsContained) {
8808   // Look through array types while ignoring qualifiers.
8809   const Type *Ty = T->getBaseElementTypeUnsafe();
8810   IsContained = false;
8811 
8812   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8813   RD = RD ? RD->getDefinition() : nullptr;
8814   if (!RD || RD->isInvalidDecl())
8815     return nullptr;
8816 
8817   if (RD->isDynamicClass())
8818     return RD;
8819 
8820   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8821   // It's impossible for a class to transitively contain itself by value, so
8822   // infinite recursion is impossible.
8823   for (auto *FD : RD->fields()) {
8824     bool SubContained;
8825     if (const CXXRecordDecl *ContainedRD =
8826             getContainedDynamicClass(FD->getType(), SubContained)) {
8827       IsContained = true;
8828       return ContainedRD;
8829     }
8830   }
8831 
8832   return nullptr;
8833 }
8834 
8835 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8836   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8837     if (Unary->getKind() == UETT_SizeOf)
8838       return Unary;
8839   return nullptr;
8840 }
8841 
8842 /// If E is a sizeof expression, returns its argument expression,
8843 /// otherwise returns NULL.
8844 static const Expr *getSizeOfExprArg(const Expr *E) {
8845   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8846     if (!SizeOf->isArgumentType())
8847       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8848   return nullptr;
8849 }
8850 
8851 /// If E is a sizeof expression, returns its argument type.
8852 static QualType getSizeOfArgType(const Expr *E) {
8853   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8854     return SizeOf->getTypeOfArgument();
8855   return QualType();
8856 }
8857 
8858 namespace {
8859 
8860 struct SearchNonTrivialToInitializeField
8861     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8862   using Super =
8863       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8864 
8865   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8866 
8867   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8868                      SourceLocation SL) {
8869     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8870       asDerived().visitArray(PDIK, AT, SL);
8871       return;
8872     }
8873 
8874     Super::visitWithKind(PDIK, FT, SL);
8875   }
8876 
8877   void visitARCStrong(QualType FT, SourceLocation SL) {
8878     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8879   }
8880   void visitARCWeak(QualType FT, SourceLocation SL) {
8881     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8882   }
8883   void visitStruct(QualType FT, SourceLocation SL) {
8884     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8885       visit(FD->getType(), FD->getLocation());
8886   }
8887   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8888                   const ArrayType *AT, SourceLocation SL) {
8889     visit(getContext().getBaseElementType(AT), SL);
8890   }
8891   void visitTrivial(QualType FT, SourceLocation SL) {}
8892 
8893   static void diag(QualType RT, const Expr *E, Sema &S) {
8894     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8895   }
8896 
8897   ASTContext &getContext() { return S.getASTContext(); }
8898 
8899   const Expr *E;
8900   Sema &S;
8901 };
8902 
8903 struct SearchNonTrivialToCopyField
8904     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8905   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8906 
8907   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8908 
8909   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8910                      SourceLocation SL) {
8911     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8912       asDerived().visitArray(PCK, AT, SL);
8913       return;
8914     }
8915 
8916     Super::visitWithKind(PCK, FT, SL);
8917   }
8918 
8919   void visitARCStrong(QualType FT, SourceLocation SL) {
8920     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8921   }
8922   void visitARCWeak(QualType FT, SourceLocation SL) {
8923     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8924   }
8925   void visitStruct(QualType FT, SourceLocation SL) {
8926     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8927       visit(FD->getType(), FD->getLocation());
8928   }
8929   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8930                   SourceLocation SL) {
8931     visit(getContext().getBaseElementType(AT), SL);
8932   }
8933   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8934                 SourceLocation SL) {}
8935   void visitTrivial(QualType FT, SourceLocation SL) {}
8936   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8937 
8938   static void diag(QualType RT, const Expr *E, Sema &S) {
8939     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8940   }
8941 
8942   ASTContext &getContext() { return S.getASTContext(); }
8943 
8944   const Expr *E;
8945   Sema &S;
8946 };
8947 
8948 }
8949 
8950 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8951 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8952   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8953 
8954   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8955     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8956       return false;
8957 
8958     return doesExprLikelyComputeSize(BO->getLHS()) ||
8959            doesExprLikelyComputeSize(BO->getRHS());
8960   }
8961 
8962   return getAsSizeOfExpr(SizeofExpr) != nullptr;
8963 }
8964 
8965 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8966 ///
8967 /// \code
8968 ///   #define MACRO 0
8969 ///   foo(MACRO);
8970 ///   foo(0);
8971 /// \endcode
8972 ///
8973 /// This should return true for the first call to foo, but not for the second
8974 /// (regardless of whether foo is a macro or function).
8975 static bool isArgumentExpandedFromMacro(SourceManager &SM,
8976                                         SourceLocation CallLoc,
8977                                         SourceLocation ArgLoc) {
8978   if (!CallLoc.isMacroID())
8979     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8980 
8981   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8982          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8983 }
8984 
8985 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8986 /// last two arguments transposed.
8987 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8988   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8989     return;
8990 
8991   const Expr *SizeArg =
8992     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8993 
8994   auto isLiteralZero = [](const Expr *E) {
8995     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8996   };
8997 
8998   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8999   SourceLocation CallLoc = Call->getRParenLoc();
9000   SourceManager &SM = S.getSourceManager();
9001   if (isLiteralZero(SizeArg) &&
9002       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9003 
9004     SourceLocation DiagLoc = SizeArg->getExprLoc();
9005 
9006     // Some platforms #define bzero to __builtin_memset. See if this is the
9007     // case, and if so, emit a better diagnostic.
9008     if (BId == Builtin::BIbzero ||
9009         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9010                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9011       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9012       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9013     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9014       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9015       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9016     }
9017     return;
9018   }
9019 
9020   // If the second argument to a memset is a sizeof expression and the third
9021   // isn't, this is also likely an error. This should catch
9022   // 'memset(buf, sizeof(buf), 0xff)'.
9023   if (BId == Builtin::BImemset &&
9024       doesExprLikelyComputeSize(Call->getArg(1)) &&
9025       !doesExprLikelyComputeSize(Call->getArg(2))) {
9026     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9027     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9028     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9029     return;
9030   }
9031 }
9032 
9033 /// Check for dangerous or invalid arguments to memset().
9034 ///
9035 /// This issues warnings on known problematic, dangerous or unspecified
9036 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9037 /// function calls.
9038 ///
9039 /// \param Call The call expression to diagnose.
9040 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9041                                    unsigned BId,
9042                                    IdentifierInfo *FnName) {
9043   assert(BId != 0);
9044 
9045   // It is possible to have a non-standard definition of memset.  Validate
9046   // we have enough arguments, and if not, abort further checking.
9047   unsigned ExpectedNumArgs =
9048       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9049   if (Call->getNumArgs() < ExpectedNumArgs)
9050     return;
9051 
9052   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9053                       BId == Builtin::BIstrndup ? 1 : 2);
9054   unsigned LenArg =
9055       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9056   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9057 
9058   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9059                                      Call->getBeginLoc(), Call->getRParenLoc()))
9060     return;
9061 
9062   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9063   CheckMemaccessSize(*this, BId, Call);
9064 
9065   // We have special checking when the length is a sizeof expression.
9066   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9067   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9068   llvm::FoldingSetNodeID SizeOfArgID;
9069 
9070   // Although widely used, 'bzero' is not a standard function. Be more strict
9071   // with the argument types before allowing diagnostics and only allow the
9072   // form bzero(ptr, sizeof(...)).
9073   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9074   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9075     return;
9076 
9077   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9078     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9079     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9080 
9081     QualType DestTy = Dest->getType();
9082     QualType PointeeTy;
9083     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9084       PointeeTy = DestPtrTy->getPointeeType();
9085 
9086       // Never warn about void type pointers. This can be used to suppress
9087       // false positives.
9088       if (PointeeTy->isVoidType())
9089         continue;
9090 
9091       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9092       // actually comparing the expressions for equality. Because computing the
9093       // expression IDs can be expensive, we only do this if the diagnostic is
9094       // enabled.
9095       if (SizeOfArg &&
9096           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9097                            SizeOfArg->getExprLoc())) {
9098         // We only compute IDs for expressions if the warning is enabled, and
9099         // cache the sizeof arg's ID.
9100         if (SizeOfArgID == llvm::FoldingSetNodeID())
9101           SizeOfArg->Profile(SizeOfArgID, Context, true);
9102         llvm::FoldingSetNodeID DestID;
9103         Dest->Profile(DestID, Context, true);
9104         if (DestID == SizeOfArgID) {
9105           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9106           //       over sizeof(src) as well.
9107           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9108           StringRef ReadableName = FnName->getName();
9109 
9110           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9111             if (UnaryOp->getOpcode() == UO_AddrOf)
9112               ActionIdx = 1; // If its an address-of operator, just remove it.
9113           if (!PointeeTy->isIncompleteType() &&
9114               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9115             ActionIdx = 2; // If the pointee's size is sizeof(char),
9116                            // suggest an explicit length.
9117 
9118           // If the function is defined as a builtin macro, do not show macro
9119           // expansion.
9120           SourceLocation SL = SizeOfArg->getExprLoc();
9121           SourceRange DSR = Dest->getSourceRange();
9122           SourceRange SSR = SizeOfArg->getSourceRange();
9123           SourceManager &SM = getSourceManager();
9124 
9125           if (SM.isMacroArgExpansion(SL)) {
9126             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9127             SL = SM.getSpellingLoc(SL);
9128             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9129                              SM.getSpellingLoc(DSR.getEnd()));
9130             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9131                              SM.getSpellingLoc(SSR.getEnd()));
9132           }
9133 
9134           DiagRuntimeBehavior(SL, SizeOfArg,
9135                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9136                                 << ReadableName
9137                                 << PointeeTy
9138                                 << DestTy
9139                                 << DSR
9140                                 << SSR);
9141           DiagRuntimeBehavior(SL, SizeOfArg,
9142                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9143                                 << ActionIdx
9144                                 << SSR);
9145 
9146           break;
9147         }
9148       }
9149 
9150       // Also check for cases where the sizeof argument is the exact same
9151       // type as the memory argument, and where it points to a user-defined
9152       // record type.
9153       if (SizeOfArgTy != QualType()) {
9154         if (PointeeTy->isRecordType() &&
9155             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9156           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9157                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9158                                 << FnName << SizeOfArgTy << ArgIdx
9159                                 << PointeeTy << Dest->getSourceRange()
9160                                 << LenExpr->getSourceRange());
9161           break;
9162         }
9163       }
9164     } else if (DestTy->isArrayType()) {
9165       PointeeTy = DestTy;
9166     }
9167 
9168     if (PointeeTy == QualType())
9169       continue;
9170 
9171     // Always complain about dynamic classes.
9172     bool IsContained;
9173     if (const CXXRecordDecl *ContainedRD =
9174             getContainedDynamicClass(PointeeTy, IsContained)) {
9175 
9176       unsigned OperationType = 0;
9177       // "overwritten" if we're warning about the destination for any call
9178       // but memcmp; otherwise a verb appropriate to the call.
9179       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
9180         if (BId == Builtin::BImemcpy)
9181           OperationType = 1;
9182         else if(BId == Builtin::BImemmove)
9183           OperationType = 2;
9184         else if (BId == Builtin::BImemcmp)
9185           OperationType = 3;
9186       }
9187 
9188       DiagRuntimeBehavior(
9189         Dest->getExprLoc(), Dest,
9190         PDiag(diag::warn_dyn_class_memaccess)
9191           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
9192           << FnName << IsContained << ContainedRD << OperationType
9193           << Call->getCallee()->getSourceRange());
9194     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9195              BId != Builtin::BImemset)
9196       DiagRuntimeBehavior(
9197         Dest->getExprLoc(), Dest,
9198         PDiag(diag::warn_arc_object_memaccess)
9199           << ArgIdx << FnName << PointeeTy
9200           << Call->getCallee()->getSourceRange());
9201     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9202       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9203           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9204         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9205                             PDiag(diag::warn_cstruct_memaccess)
9206                                 << ArgIdx << FnName << PointeeTy << 0);
9207         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9208       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9209                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9210         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9211                             PDiag(diag::warn_cstruct_memaccess)
9212                                 << ArgIdx << FnName << PointeeTy << 1);
9213         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9214       } else {
9215         continue;
9216       }
9217     } else
9218       continue;
9219 
9220     DiagRuntimeBehavior(
9221       Dest->getExprLoc(), Dest,
9222       PDiag(diag::note_bad_memaccess_silence)
9223         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9224     break;
9225   }
9226 }
9227 
9228 // A little helper routine: ignore addition and subtraction of integer literals.
9229 // This intentionally does not ignore all integer constant expressions because
9230 // we don't want to remove sizeof().
9231 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9232   Ex = Ex->IgnoreParenCasts();
9233 
9234   while (true) {
9235     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9236     if (!BO || !BO->isAdditiveOp())
9237       break;
9238 
9239     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9240     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9241 
9242     if (isa<IntegerLiteral>(RHS))
9243       Ex = LHS;
9244     else if (isa<IntegerLiteral>(LHS))
9245       Ex = RHS;
9246     else
9247       break;
9248   }
9249 
9250   return Ex;
9251 }
9252 
9253 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9254                                                       ASTContext &Context) {
9255   // Only handle constant-sized or VLAs, but not flexible members.
9256   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9257     // Only issue the FIXIT for arrays of size > 1.
9258     if (CAT->getSize().getSExtValue() <= 1)
9259       return false;
9260   } else if (!Ty->isVariableArrayType()) {
9261     return false;
9262   }
9263   return true;
9264 }
9265 
9266 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9267 // be the size of the source, instead of the destination.
9268 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9269                                     IdentifierInfo *FnName) {
9270 
9271   // Don't crash if the user has the wrong number of arguments
9272   unsigned NumArgs = Call->getNumArgs();
9273   if ((NumArgs != 3) && (NumArgs != 4))
9274     return;
9275 
9276   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9277   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9278   const Expr *CompareWithSrc = nullptr;
9279 
9280   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9281                                      Call->getBeginLoc(), Call->getRParenLoc()))
9282     return;
9283 
9284   // Look for 'strlcpy(dst, x, sizeof(x))'
9285   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9286     CompareWithSrc = Ex;
9287   else {
9288     // Look for 'strlcpy(dst, x, strlen(x))'
9289     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9290       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9291           SizeCall->getNumArgs() == 1)
9292         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9293     }
9294   }
9295 
9296   if (!CompareWithSrc)
9297     return;
9298 
9299   // Determine if the argument to sizeof/strlen is equal to the source
9300   // argument.  In principle there's all kinds of things you could do
9301   // here, for instance creating an == expression and evaluating it with
9302   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9303   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9304   if (!SrcArgDRE)
9305     return;
9306 
9307   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9308   if (!CompareWithSrcDRE ||
9309       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9310     return;
9311 
9312   const Expr *OriginalSizeArg = Call->getArg(2);
9313   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9314       << OriginalSizeArg->getSourceRange() << FnName;
9315 
9316   // Output a FIXIT hint if the destination is an array (rather than a
9317   // pointer to an array).  This could be enhanced to handle some
9318   // pointers if we know the actual size, like if DstArg is 'array+2'
9319   // we could say 'sizeof(array)-2'.
9320   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9321   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9322     return;
9323 
9324   SmallString<128> sizeString;
9325   llvm::raw_svector_ostream OS(sizeString);
9326   OS << "sizeof(";
9327   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9328   OS << ")";
9329 
9330   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9331       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9332                                       OS.str());
9333 }
9334 
9335 /// Check if two expressions refer to the same declaration.
9336 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9337   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9338     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9339       return D1->getDecl() == D2->getDecl();
9340   return false;
9341 }
9342 
9343 static const Expr *getStrlenExprArg(const Expr *E) {
9344   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9345     const FunctionDecl *FD = CE->getDirectCallee();
9346     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9347       return nullptr;
9348     return CE->getArg(0)->IgnoreParenCasts();
9349   }
9350   return nullptr;
9351 }
9352 
9353 // Warn on anti-patterns as the 'size' argument to strncat.
9354 // The correct size argument should look like following:
9355 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9356 void Sema::CheckStrncatArguments(const CallExpr *CE,
9357                                  IdentifierInfo *FnName) {
9358   // Don't crash if the user has the wrong number of arguments.
9359   if (CE->getNumArgs() < 3)
9360     return;
9361   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9362   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9363   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9364 
9365   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9366                                      CE->getRParenLoc()))
9367     return;
9368 
9369   // Identify common expressions, which are wrongly used as the size argument
9370   // to strncat and may lead to buffer overflows.
9371   unsigned PatternType = 0;
9372   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9373     // - sizeof(dst)
9374     if (referToTheSameDecl(SizeOfArg, DstArg))
9375       PatternType = 1;
9376     // - sizeof(src)
9377     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9378       PatternType = 2;
9379   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9380     if (BE->getOpcode() == BO_Sub) {
9381       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9382       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9383       // - sizeof(dst) - strlen(dst)
9384       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9385           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9386         PatternType = 1;
9387       // - sizeof(src) - (anything)
9388       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9389         PatternType = 2;
9390     }
9391   }
9392 
9393   if (PatternType == 0)
9394     return;
9395 
9396   // Generate the diagnostic.
9397   SourceLocation SL = LenArg->getBeginLoc();
9398   SourceRange SR = LenArg->getSourceRange();
9399   SourceManager &SM = getSourceManager();
9400 
9401   // If the function is defined as a builtin macro, do not show macro expansion.
9402   if (SM.isMacroArgExpansion(SL)) {
9403     SL = SM.getSpellingLoc(SL);
9404     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9405                      SM.getSpellingLoc(SR.getEnd()));
9406   }
9407 
9408   // Check if the destination is an array (rather than a pointer to an array).
9409   QualType DstTy = DstArg->getType();
9410   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9411                                                                     Context);
9412   if (!isKnownSizeArray) {
9413     if (PatternType == 1)
9414       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9415     else
9416       Diag(SL, diag::warn_strncat_src_size) << SR;
9417     return;
9418   }
9419 
9420   if (PatternType == 1)
9421     Diag(SL, diag::warn_strncat_large_size) << SR;
9422   else
9423     Diag(SL, diag::warn_strncat_src_size) << SR;
9424 
9425   SmallString<128> sizeString;
9426   llvm::raw_svector_ostream OS(sizeString);
9427   OS << "sizeof(";
9428   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9429   OS << ") - ";
9430   OS << "strlen(";
9431   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9432   OS << ") - 1";
9433 
9434   Diag(SL, diag::note_strncat_wrong_size)
9435     << FixItHint::CreateReplacement(SR, OS.str());
9436 }
9437 
9438 void
9439 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9440                          SourceLocation ReturnLoc,
9441                          bool isObjCMethod,
9442                          const AttrVec *Attrs,
9443                          const FunctionDecl *FD) {
9444   // Check if the return value is null but should not be.
9445   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9446        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9447       CheckNonNullExpr(*this, RetValExp))
9448     Diag(ReturnLoc, diag::warn_null_ret)
9449       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9450 
9451   // C++11 [basic.stc.dynamic.allocation]p4:
9452   //   If an allocation function declared with a non-throwing
9453   //   exception-specification fails to allocate storage, it shall return
9454   //   a null pointer. Any other allocation function that fails to allocate
9455   //   storage shall indicate failure only by throwing an exception [...]
9456   if (FD) {
9457     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9458     if (Op == OO_New || Op == OO_Array_New) {
9459       const FunctionProtoType *Proto
9460         = FD->getType()->castAs<FunctionProtoType>();
9461       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9462           CheckNonNullExpr(*this, RetValExp))
9463         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9464           << FD << getLangOpts().CPlusPlus11;
9465     }
9466   }
9467 }
9468 
9469 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9470 
9471 /// Check for comparisons of floating point operands using != and ==.
9472 /// Issue a warning if these are no self-comparisons, as they are not likely
9473 /// to do what the programmer intended.
9474 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9475   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9476   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9477 
9478   // Special case: check for x == x (which is OK).
9479   // Do not emit warnings for such cases.
9480   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9481     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9482       if (DRL->getDecl() == DRR->getDecl())
9483         return;
9484 
9485   // Special case: check for comparisons against literals that can be exactly
9486   //  represented by APFloat.  In such cases, do not emit a warning.  This
9487   //  is a heuristic: often comparison against such literals are used to
9488   //  detect if a value in a variable has not changed.  This clearly can
9489   //  lead to false negatives.
9490   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9491     if (FLL->isExact())
9492       return;
9493   } else
9494     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9495       if (FLR->isExact())
9496         return;
9497 
9498   // Check for comparisons with builtin types.
9499   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9500     if (CL->getBuiltinCallee())
9501       return;
9502 
9503   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9504     if (CR->getBuiltinCallee())
9505       return;
9506 
9507   // Emit the diagnostic.
9508   Diag(Loc, diag::warn_floatingpoint_eq)
9509     << LHS->getSourceRange() << RHS->getSourceRange();
9510 }
9511 
9512 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9513 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9514 
9515 namespace {
9516 
9517 /// Structure recording the 'active' range of an integer-valued
9518 /// expression.
9519 struct IntRange {
9520   /// The number of bits active in the int.
9521   unsigned Width;
9522 
9523   /// True if the int is known not to have negative values.
9524   bool NonNegative;
9525 
9526   IntRange(unsigned Width, bool NonNegative)
9527       : Width(Width), NonNegative(NonNegative) {}
9528 
9529   /// Returns the range of the bool type.
9530   static IntRange forBoolType() {
9531     return IntRange(1, true);
9532   }
9533 
9534   /// Returns the range of an opaque value of the given integral type.
9535   static IntRange forValueOfType(ASTContext &C, QualType T) {
9536     return forValueOfCanonicalType(C,
9537                           T->getCanonicalTypeInternal().getTypePtr());
9538   }
9539 
9540   /// Returns the range of an opaque value of a canonical integral type.
9541   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9542     assert(T->isCanonicalUnqualified());
9543 
9544     if (const VectorType *VT = dyn_cast<VectorType>(T))
9545       T = VT->getElementType().getTypePtr();
9546     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9547       T = CT->getElementType().getTypePtr();
9548     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9549       T = AT->getValueType().getTypePtr();
9550 
9551     if (!C.getLangOpts().CPlusPlus) {
9552       // For enum types in C code, use the underlying datatype.
9553       if (const EnumType *ET = dyn_cast<EnumType>(T))
9554         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9555     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9556       // For enum types in C++, use the known bit width of the enumerators.
9557       EnumDecl *Enum = ET->getDecl();
9558       // In C++11, enums can have a fixed underlying type. Use this type to
9559       // compute the range.
9560       if (Enum->isFixed()) {
9561         return IntRange(C.getIntWidth(QualType(T, 0)),
9562                         !ET->isSignedIntegerOrEnumerationType());
9563       }
9564 
9565       unsigned NumPositive = Enum->getNumPositiveBits();
9566       unsigned NumNegative = Enum->getNumNegativeBits();
9567 
9568       if (NumNegative == 0)
9569         return IntRange(NumPositive, true/*NonNegative*/);
9570       else
9571         return IntRange(std::max(NumPositive + 1, NumNegative),
9572                         false/*NonNegative*/);
9573     }
9574 
9575     const BuiltinType *BT = cast<BuiltinType>(T);
9576     assert(BT->isInteger());
9577 
9578     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9579   }
9580 
9581   /// Returns the "target" range of a canonical integral type, i.e.
9582   /// the range of values expressible in the type.
9583   ///
9584   /// This matches forValueOfCanonicalType except that enums have the
9585   /// full range of their type, not the range of their enumerators.
9586   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9587     assert(T->isCanonicalUnqualified());
9588 
9589     if (const VectorType *VT = dyn_cast<VectorType>(T))
9590       T = VT->getElementType().getTypePtr();
9591     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9592       T = CT->getElementType().getTypePtr();
9593     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9594       T = AT->getValueType().getTypePtr();
9595     if (const EnumType *ET = dyn_cast<EnumType>(T))
9596       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9597 
9598     const BuiltinType *BT = cast<BuiltinType>(T);
9599     assert(BT->isInteger());
9600 
9601     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9602   }
9603 
9604   /// Returns the supremum of two ranges: i.e. their conservative merge.
9605   static IntRange join(IntRange L, IntRange R) {
9606     return IntRange(std::max(L.Width, R.Width),
9607                     L.NonNegative && R.NonNegative);
9608   }
9609 
9610   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9611   static IntRange meet(IntRange L, IntRange R) {
9612     return IntRange(std::min(L.Width, R.Width),
9613                     L.NonNegative || R.NonNegative);
9614   }
9615 };
9616 
9617 } // namespace
9618 
9619 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9620                               unsigned MaxWidth) {
9621   if (value.isSigned() && value.isNegative())
9622     return IntRange(value.getMinSignedBits(), false);
9623 
9624   if (value.getBitWidth() > MaxWidth)
9625     value = value.trunc(MaxWidth);
9626 
9627   // isNonNegative() just checks the sign bit without considering
9628   // signedness.
9629   return IntRange(value.getActiveBits(), true);
9630 }
9631 
9632 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9633                               unsigned MaxWidth) {
9634   if (result.isInt())
9635     return GetValueRange(C, result.getInt(), MaxWidth);
9636 
9637   if (result.isVector()) {
9638     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9639     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9640       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9641       R = IntRange::join(R, El);
9642     }
9643     return R;
9644   }
9645 
9646   if (result.isComplexInt()) {
9647     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9648     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9649     return IntRange::join(R, I);
9650   }
9651 
9652   // This can happen with lossless casts to intptr_t of "based" lvalues.
9653   // Assume it might use arbitrary bits.
9654   // FIXME: The only reason we need to pass the type in here is to get
9655   // the sign right on this one case.  It would be nice if APValue
9656   // preserved this.
9657   assert(result.isLValue() || result.isAddrLabelDiff());
9658   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9659 }
9660 
9661 static QualType GetExprType(const Expr *E) {
9662   QualType Ty = E->getType();
9663   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9664     Ty = AtomicRHS->getValueType();
9665   return Ty;
9666 }
9667 
9668 /// Pseudo-evaluate the given integer expression, estimating the
9669 /// range of values it might take.
9670 ///
9671 /// \param MaxWidth - the width to which the value will be truncated
9672 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9673   E = E->IgnoreParens();
9674 
9675   // Try a full evaluation first.
9676   Expr::EvalResult result;
9677   if (E->EvaluateAsRValue(result, C))
9678     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9679 
9680   // I think we only want to look through implicit casts here; if the
9681   // user has an explicit widening cast, we should treat the value as
9682   // being of the new, wider type.
9683   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9684     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9685       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9686 
9687     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9688 
9689     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9690                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9691 
9692     // Assume that non-integer casts can span the full range of the type.
9693     if (!isIntegerCast)
9694       return OutputTypeRange;
9695 
9696     IntRange SubRange
9697       = GetExprRange(C, CE->getSubExpr(),
9698                      std::min(MaxWidth, OutputTypeRange.Width));
9699 
9700     // Bail out if the subexpr's range is as wide as the cast type.
9701     if (SubRange.Width >= OutputTypeRange.Width)
9702       return OutputTypeRange;
9703 
9704     // Otherwise, we take the smaller width, and we're non-negative if
9705     // either the output type or the subexpr is.
9706     return IntRange(SubRange.Width,
9707                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9708   }
9709 
9710   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9711     // If we can fold the condition, just take that operand.
9712     bool CondResult;
9713     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9714       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9715                                         : CO->getFalseExpr(),
9716                           MaxWidth);
9717 
9718     // Otherwise, conservatively merge.
9719     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9720     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9721     return IntRange::join(L, R);
9722   }
9723 
9724   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9725     switch (BO->getOpcode()) {
9726     case BO_Cmp:
9727       llvm_unreachable("builtin <=> should have class type");
9728 
9729     // Boolean-valued operations are single-bit and positive.
9730     case BO_LAnd:
9731     case BO_LOr:
9732     case BO_LT:
9733     case BO_GT:
9734     case BO_LE:
9735     case BO_GE:
9736     case BO_EQ:
9737     case BO_NE:
9738       return IntRange::forBoolType();
9739 
9740     // The type of the assignments is the type of the LHS, so the RHS
9741     // is not necessarily the same type.
9742     case BO_MulAssign:
9743     case BO_DivAssign:
9744     case BO_RemAssign:
9745     case BO_AddAssign:
9746     case BO_SubAssign:
9747     case BO_XorAssign:
9748     case BO_OrAssign:
9749       // TODO: bitfields?
9750       return IntRange::forValueOfType(C, GetExprType(E));
9751 
9752     // Simple assignments just pass through the RHS, which will have
9753     // been coerced to the LHS type.
9754     case BO_Assign:
9755       // TODO: bitfields?
9756       return GetExprRange(C, BO->getRHS(), MaxWidth);
9757 
9758     // Operations with opaque sources are black-listed.
9759     case BO_PtrMemD:
9760     case BO_PtrMemI:
9761       return IntRange::forValueOfType(C, GetExprType(E));
9762 
9763     // Bitwise-and uses the *infinum* of the two source ranges.
9764     case BO_And:
9765     case BO_AndAssign:
9766       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9767                             GetExprRange(C, BO->getRHS(), MaxWidth));
9768 
9769     // Left shift gets black-listed based on a judgement call.
9770     case BO_Shl:
9771       // ...except that we want to treat '1 << (blah)' as logically
9772       // positive.  It's an important idiom.
9773       if (IntegerLiteral *I
9774             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9775         if (I->getValue() == 1) {
9776           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9777           return IntRange(R.Width, /*NonNegative*/ true);
9778         }
9779       }
9780       LLVM_FALLTHROUGH;
9781 
9782     case BO_ShlAssign:
9783       return IntRange::forValueOfType(C, GetExprType(E));
9784 
9785     // Right shift by a constant can narrow its left argument.
9786     case BO_Shr:
9787     case BO_ShrAssign: {
9788       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9789 
9790       // If the shift amount is a positive constant, drop the width by
9791       // that much.
9792       llvm::APSInt shift;
9793       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9794           shift.isNonNegative()) {
9795         unsigned zext = shift.getZExtValue();
9796         if (zext >= L.Width)
9797           L.Width = (L.NonNegative ? 0 : 1);
9798         else
9799           L.Width -= zext;
9800       }
9801 
9802       return L;
9803     }
9804 
9805     // Comma acts as its right operand.
9806     case BO_Comma:
9807       return GetExprRange(C, BO->getRHS(), MaxWidth);
9808 
9809     // Black-list pointer subtractions.
9810     case BO_Sub:
9811       if (BO->getLHS()->getType()->isPointerType())
9812         return IntRange::forValueOfType(C, GetExprType(E));
9813       break;
9814 
9815     // The width of a division result is mostly determined by the size
9816     // of the LHS.
9817     case BO_Div: {
9818       // Don't 'pre-truncate' the operands.
9819       unsigned opWidth = C.getIntWidth(GetExprType(E));
9820       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9821 
9822       // If the divisor is constant, use that.
9823       llvm::APSInt divisor;
9824       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9825         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9826         if (log2 >= L.Width)
9827           L.Width = (L.NonNegative ? 0 : 1);
9828         else
9829           L.Width = std::min(L.Width - log2, MaxWidth);
9830         return L;
9831       }
9832 
9833       // Otherwise, just use the LHS's width.
9834       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9835       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9836     }
9837 
9838     // The result of a remainder can't be larger than the result of
9839     // either side.
9840     case BO_Rem: {
9841       // Don't 'pre-truncate' the operands.
9842       unsigned opWidth = C.getIntWidth(GetExprType(E));
9843       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9844       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9845 
9846       IntRange meet = IntRange::meet(L, R);
9847       meet.Width = std::min(meet.Width, MaxWidth);
9848       return meet;
9849     }
9850 
9851     // The default behavior is okay for these.
9852     case BO_Mul:
9853     case BO_Add:
9854     case BO_Xor:
9855     case BO_Or:
9856       break;
9857     }
9858 
9859     // The default case is to treat the operation as if it were closed
9860     // on the narrowest type that encompasses both operands.
9861     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9862     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9863     return IntRange::join(L, R);
9864   }
9865 
9866   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9867     switch (UO->getOpcode()) {
9868     // Boolean-valued operations are white-listed.
9869     case UO_LNot:
9870       return IntRange::forBoolType();
9871 
9872     // Operations with opaque sources are black-listed.
9873     case UO_Deref:
9874     case UO_AddrOf: // should be impossible
9875       return IntRange::forValueOfType(C, GetExprType(E));
9876 
9877     default:
9878       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9879     }
9880   }
9881 
9882   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9883     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9884 
9885   if (const auto *BitField = E->getSourceBitField())
9886     return IntRange(BitField->getBitWidthValue(C),
9887                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9888 
9889   return IntRange::forValueOfType(C, GetExprType(E));
9890 }
9891 
9892 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9893   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9894 }
9895 
9896 /// Checks whether the given value, which currently has the given
9897 /// source semantics, has the same value when coerced through the
9898 /// target semantics.
9899 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9900                                  const llvm::fltSemantics &Src,
9901                                  const llvm::fltSemantics &Tgt) {
9902   llvm::APFloat truncated = value;
9903 
9904   bool ignored;
9905   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9906   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9907 
9908   return truncated.bitwiseIsEqual(value);
9909 }
9910 
9911 /// Checks whether the given value, which currently has the given
9912 /// source semantics, has the same value when coerced through the
9913 /// target semantics.
9914 ///
9915 /// The value might be a vector of floats (or a complex number).
9916 static bool IsSameFloatAfterCast(const APValue &value,
9917                                  const llvm::fltSemantics &Src,
9918                                  const llvm::fltSemantics &Tgt) {
9919   if (value.isFloat())
9920     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9921 
9922   if (value.isVector()) {
9923     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9924       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9925         return false;
9926     return true;
9927   }
9928 
9929   assert(value.isComplexFloat());
9930   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9931           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9932 }
9933 
9934 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9935 
9936 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9937   // Suppress cases where we are comparing against an enum constant.
9938   if (const DeclRefExpr *DR =
9939       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9940     if (isa<EnumConstantDecl>(DR->getDecl()))
9941       return true;
9942 
9943   // Suppress cases where the '0' value is expanded from a macro.
9944   if (E->getBeginLoc().isMacroID())
9945     return true;
9946 
9947   return false;
9948 }
9949 
9950 static bool isKnownToHaveUnsignedValue(Expr *E) {
9951   return E->getType()->isIntegerType() &&
9952          (!E->getType()->isSignedIntegerType() ||
9953           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9954 }
9955 
9956 namespace {
9957 /// The promoted range of values of a type. In general this has the
9958 /// following structure:
9959 ///
9960 ///     |-----------| . . . |-----------|
9961 ///     ^           ^       ^           ^
9962 ///    Min       HoleMin  HoleMax      Max
9963 ///
9964 /// ... where there is only a hole if a signed type is promoted to unsigned
9965 /// (in which case Min and Max are the smallest and largest representable
9966 /// values).
9967 struct PromotedRange {
9968   // Min, or HoleMax if there is a hole.
9969   llvm::APSInt PromotedMin;
9970   // Max, or HoleMin if there is a hole.
9971   llvm::APSInt PromotedMax;
9972 
9973   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9974     if (R.Width == 0)
9975       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9976     else if (R.Width >= BitWidth && !Unsigned) {
9977       // Promotion made the type *narrower*. This happens when promoting
9978       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9979       // Treat all values of 'signed int' as being in range for now.
9980       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9981       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9982     } else {
9983       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9984                         .extOrTrunc(BitWidth);
9985       PromotedMin.setIsUnsigned(Unsigned);
9986 
9987       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9988                         .extOrTrunc(BitWidth);
9989       PromotedMax.setIsUnsigned(Unsigned);
9990     }
9991   }
9992 
9993   // Determine whether this range is contiguous (has no hole).
9994   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9995 
9996   // Where a constant value is within the range.
9997   enum ComparisonResult {
9998     LT = 0x1,
9999     LE = 0x2,
10000     GT = 0x4,
10001     GE = 0x8,
10002     EQ = 0x10,
10003     NE = 0x20,
10004     InRangeFlag = 0x40,
10005 
10006     Less = LE | LT | NE,
10007     Min = LE | InRangeFlag,
10008     InRange = InRangeFlag,
10009     Max = GE | InRangeFlag,
10010     Greater = GE | GT | NE,
10011 
10012     OnlyValue = LE | GE | EQ | InRangeFlag,
10013     InHole = NE
10014   };
10015 
10016   ComparisonResult compare(const llvm::APSInt &Value) const {
10017     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10018            Value.isUnsigned() == PromotedMin.isUnsigned());
10019     if (!isContiguous()) {
10020       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10021       if (Value.isMinValue()) return Min;
10022       if (Value.isMaxValue()) return Max;
10023       if (Value >= PromotedMin) return InRange;
10024       if (Value <= PromotedMax) return InRange;
10025       return InHole;
10026     }
10027 
10028     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10029     case -1: return Less;
10030     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10031     case 1:
10032       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10033       case -1: return InRange;
10034       case 0: return Max;
10035       case 1: return Greater;
10036       }
10037     }
10038 
10039     llvm_unreachable("impossible compare result");
10040   }
10041 
10042   static llvm::Optional<StringRef>
10043   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10044     if (Op == BO_Cmp) {
10045       ComparisonResult LTFlag = LT, GTFlag = GT;
10046       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10047 
10048       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10049       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10050       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10051       return llvm::None;
10052     }
10053 
10054     ComparisonResult TrueFlag, FalseFlag;
10055     if (Op == BO_EQ) {
10056       TrueFlag = EQ;
10057       FalseFlag = NE;
10058     } else if (Op == BO_NE) {
10059       TrueFlag = NE;
10060       FalseFlag = EQ;
10061     } else {
10062       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10063         TrueFlag = LT;
10064         FalseFlag = GE;
10065       } else {
10066         TrueFlag = GT;
10067         FalseFlag = LE;
10068       }
10069       if (Op == BO_GE || Op == BO_LE)
10070         std::swap(TrueFlag, FalseFlag);
10071     }
10072     if (R & TrueFlag)
10073       return StringRef("true");
10074     if (R & FalseFlag)
10075       return StringRef("false");
10076     return llvm::None;
10077   }
10078 };
10079 }
10080 
10081 static bool HasEnumType(Expr *E) {
10082   // Strip off implicit integral promotions.
10083   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10084     if (ICE->getCastKind() != CK_IntegralCast &&
10085         ICE->getCastKind() != CK_NoOp)
10086       break;
10087     E = ICE->getSubExpr();
10088   }
10089 
10090   return E->getType()->isEnumeralType();
10091 }
10092 
10093 static int classifyConstantValue(Expr *Constant) {
10094   // The values of this enumeration are used in the diagnostics
10095   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10096   enum ConstantValueKind {
10097     Miscellaneous = 0,
10098     LiteralTrue,
10099     LiteralFalse
10100   };
10101   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10102     return BL->getValue() ? ConstantValueKind::LiteralTrue
10103                           : ConstantValueKind::LiteralFalse;
10104   return ConstantValueKind::Miscellaneous;
10105 }
10106 
10107 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10108                                         Expr *Constant, Expr *Other,
10109                                         const llvm::APSInt &Value,
10110                                         bool RhsConstant) {
10111   if (S.inTemplateInstantiation())
10112     return false;
10113 
10114   Expr *OriginalOther = Other;
10115 
10116   Constant = Constant->IgnoreParenImpCasts();
10117   Other = Other->IgnoreParenImpCasts();
10118 
10119   // Suppress warnings on tautological comparisons between values of the same
10120   // enumeration type. There are only two ways we could warn on this:
10121   //  - If the constant is outside the range of representable values of
10122   //    the enumeration. In such a case, we should warn about the cast
10123   //    to enumeration type, not about the comparison.
10124   //  - If the constant is the maximum / minimum in-range value. For an
10125   //    enumeratin type, such comparisons can be meaningful and useful.
10126   if (Constant->getType()->isEnumeralType() &&
10127       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10128     return false;
10129 
10130   // TODO: Investigate using GetExprRange() to get tighter bounds
10131   // on the bit ranges.
10132   QualType OtherT = Other->getType();
10133   if (const auto *AT = OtherT->getAs<AtomicType>())
10134     OtherT = AT->getValueType();
10135   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10136 
10137   // Whether we're treating Other as being a bool because of the form of
10138   // expression despite it having another type (typically 'int' in C).
10139   bool OtherIsBooleanDespiteType =
10140       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10141   if (OtherIsBooleanDespiteType)
10142     OtherRange = IntRange::forBoolType();
10143 
10144   // Determine the promoted range of the other type and see if a comparison of
10145   // the constant against that range is tautological.
10146   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10147                                    Value.isUnsigned());
10148   auto Cmp = OtherPromotedRange.compare(Value);
10149   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10150   if (!Result)
10151     return false;
10152 
10153   // Suppress the diagnostic for an in-range comparison if the constant comes
10154   // from a macro or enumerator. We don't want to diagnose
10155   //
10156   //   some_long_value <= INT_MAX
10157   //
10158   // when sizeof(int) == sizeof(long).
10159   bool InRange = Cmp & PromotedRange::InRangeFlag;
10160   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10161     return false;
10162 
10163   // If this is a comparison to an enum constant, include that
10164   // constant in the diagnostic.
10165   const EnumConstantDecl *ED = nullptr;
10166   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10167     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10168 
10169   // Should be enough for uint128 (39 decimal digits)
10170   SmallString<64> PrettySourceValue;
10171   llvm::raw_svector_ostream OS(PrettySourceValue);
10172   if (ED)
10173     OS << '\'' << *ED << "' (" << Value << ")";
10174   else
10175     OS << Value;
10176 
10177   // FIXME: We use a somewhat different formatting for the in-range cases and
10178   // cases involving boolean values for historical reasons. We should pick a
10179   // consistent way of presenting these diagnostics.
10180   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10181     S.DiagRuntimeBehavior(
10182       E->getOperatorLoc(), E,
10183       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10184                        : diag::warn_tautological_bool_compare)
10185           << OS.str() << classifyConstantValue(Constant)
10186           << OtherT << OtherIsBooleanDespiteType << *Result
10187           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10188   } else {
10189     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10190                         ? (HasEnumType(OriginalOther)
10191                                ? diag::warn_unsigned_enum_always_true_comparison
10192                                : diag::warn_unsigned_always_true_comparison)
10193                         : diag::warn_tautological_constant_compare;
10194 
10195     S.Diag(E->getOperatorLoc(), Diag)
10196         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10197         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10198   }
10199 
10200   return true;
10201 }
10202 
10203 /// Analyze the operands of the given comparison.  Implements the
10204 /// fallback case from AnalyzeComparison.
10205 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10206   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10207   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10208 }
10209 
10210 /// Implements -Wsign-compare.
10211 ///
10212 /// \param E the binary operator to check for warnings
10213 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10214   // The type the comparison is being performed in.
10215   QualType T = E->getLHS()->getType();
10216 
10217   // Only analyze comparison operators where both sides have been converted to
10218   // the same type.
10219   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10220     return AnalyzeImpConvsInComparison(S, E);
10221 
10222   // Don't analyze value-dependent comparisons directly.
10223   if (E->isValueDependent())
10224     return AnalyzeImpConvsInComparison(S, E);
10225 
10226   Expr *LHS = E->getLHS();
10227   Expr *RHS = E->getRHS();
10228 
10229   if (T->isIntegralType(S.Context)) {
10230     llvm::APSInt RHSValue;
10231     llvm::APSInt LHSValue;
10232 
10233     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10234     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10235 
10236     // We don't care about expressions whose result is a constant.
10237     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10238       return AnalyzeImpConvsInComparison(S, E);
10239 
10240     // We only care about expressions where just one side is literal
10241     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10242       // Is the constant on the RHS or LHS?
10243       const bool RhsConstant = IsRHSIntegralLiteral;
10244       Expr *Const = RhsConstant ? RHS : LHS;
10245       Expr *Other = RhsConstant ? LHS : RHS;
10246       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10247 
10248       // Check whether an integer constant comparison results in a value
10249       // of 'true' or 'false'.
10250       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10251         return AnalyzeImpConvsInComparison(S, E);
10252     }
10253   }
10254 
10255   if (!T->hasUnsignedIntegerRepresentation()) {
10256     // We don't do anything special if this isn't an unsigned integral
10257     // comparison:  we're only interested in integral comparisons, and
10258     // signed comparisons only happen in cases we don't care to warn about.
10259     return AnalyzeImpConvsInComparison(S, E);
10260   }
10261 
10262   LHS = LHS->IgnoreParenImpCasts();
10263   RHS = RHS->IgnoreParenImpCasts();
10264 
10265   if (!S.getLangOpts().CPlusPlus) {
10266     // Avoid warning about comparison of integers with different signs when
10267     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10268     // the type of `E`.
10269     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10270       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10271     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10272       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10273   }
10274 
10275   // Check to see if one of the (unmodified) operands is of different
10276   // signedness.
10277   Expr *signedOperand, *unsignedOperand;
10278   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10279     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10280            "unsigned comparison between two signed integer expressions?");
10281     signedOperand = LHS;
10282     unsignedOperand = RHS;
10283   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10284     signedOperand = RHS;
10285     unsignedOperand = LHS;
10286   } else {
10287     return AnalyzeImpConvsInComparison(S, E);
10288   }
10289 
10290   // Otherwise, calculate the effective range of the signed operand.
10291   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10292 
10293   // Go ahead and analyze implicit conversions in the operands.  Note
10294   // that we skip the implicit conversions on both sides.
10295   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10296   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10297 
10298   // If the signed range is non-negative, -Wsign-compare won't fire.
10299   if (signedRange.NonNegative)
10300     return;
10301 
10302   // For (in)equality comparisons, if the unsigned operand is a
10303   // constant which cannot collide with a overflowed signed operand,
10304   // then reinterpreting the signed operand as unsigned will not
10305   // change the result of the comparison.
10306   if (E->isEqualityOp()) {
10307     unsigned comparisonWidth = S.Context.getIntWidth(T);
10308     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10309 
10310     // We should never be unable to prove that the unsigned operand is
10311     // non-negative.
10312     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10313 
10314     if (unsignedRange.Width < comparisonWidth)
10315       return;
10316   }
10317 
10318   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10319     S.PDiag(diag::warn_mixed_sign_comparison)
10320       << LHS->getType() << RHS->getType()
10321       << LHS->getSourceRange() << RHS->getSourceRange());
10322 }
10323 
10324 /// Analyzes an attempt to assign the given value to a bitfield.
10325 ///
10326 /// Returns true if there was something fishy about the attempt.
10327 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10328                                       SourceLocation InitLoc) {
10329   assert(Bitfield->isBitField());
10330   if (Bitfield->isInvalidDecl())
10331     return false;
10332 
10333   // White-list bool bitfields.
10334   QualType BitfieldType = Bitfield->getType();
10335   if (BitfieldType->isBooleanType())
10336      return false;
10337 
10338   if (BitfieldType->isEnumeralType()) {
10339     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10340     // If the underlying enum type was not explicitly specified as an unsigned
10341     // type and the enum contain only positive values, MSVC++ will cause an
10342     // inconsistency by storing this as a signed type.
10343     if (S.getLangOpts().CPlusPlus11 &&
10344         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10345         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10346         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10347       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10348         << BitfieldEnumDecl->getNameAsString();
10349     }
10350   }
10351 
10352   if (Bitfield->getType()->isBooleanType())
10353     return false;
10354 
10355   // Ignore value- or type-dependent expressions.
10356   if (Bitfield->getBitWidth()->isValueDependent() ||
10357       Bitfield->getBitWidth()->isTypeDependent() ||
10358       Init->isValueDependent() ||
10359       Init->isTypeDependent())
10360     return false;
10361 
10362   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10363   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10364 
10365   Expr::EvalResult Result;
10366   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10367                                    Expr::SE_AllowSideEffects)) {
10368     // The RHS is not constant.  If the RHS has an enum type, make sure the
10369     // bitfield is wide enough to hold all the values of the enum without
10370     // truncation.
10371     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10372       EnumDecl *ED = EnumTy->getDecl();
10373       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10374 
10375       // Enum types are implicitly signed on Windows, so check if there are any
10376       // negative enumerators to see if the enum was intended to be signed or
10377       // not.
10378       bool SignedEnum = ED->getNumNegativeBits() > 0;
10379 
10380       // Check for surprising sign changes when assigning enum values to a
10381       // bitfield of different signedness.  If the bitfield is signed and we
10382       // have exactly the right number of bits to store this unsigned enum,
10383       // suggest changing the enum to an unsigned type. This typically happens
10384       // on Windows where unfixed enums always use an underlying type of 'int'.
10385       unsigned DiagID = 0;
10386       if (SignedEnum && !SignedBitfield) {
10387         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10388       } else if (SignedBitfield && !SignedEnum &&
10389                  ED->getNumPositiveBits() == FieldWidth) {
10390         DiagID = diag::warn_signed_bitfield_enum_conversion;
10391       }
10392 
10393       if (DiagID) {
10394         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10395         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10396         SourceRange TypeRange =
10397             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10398         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10399             << SignedEnum << TypeRange;
10400       }
10401 
10402       // Compute the required bitwidth. If the enum has negative values, we need
10403       // one more bit than the normal number of positive bits to represent the
10404       // sign bit.
10405       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10406                                                   ED->getNumNegativeBits())
10407                                        : ED->getNumPositiveBits();
10408 
10409       // Check the bitwidth.
10410       if (BitsNeeded > FieldWidth) {
10411         Expr *WidthExpr = Bitfield->getBitWidth();
10412         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10413             << Bitfield << ED;
10414         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10415             << BitsNeeded << ED << WidthExpr->getSourceRange();
10416       }
10417     }
10418 
10419     return false;
10420   }
10421 
10422   llvm::APSInt Value = Result.Val.getInt();
10423 
10424   unsigned OriginalWidth = Value.getBitWidth();
10425 
10426   if (!Value.isSigned() || Value.isNegative())
10427     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10428       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10429         OriginalWidth = Value.getMinSignedBits();
10430 
10431   if (OriginalWidth <= FieldWidth)
10432     return false;
10433 
10434   // Compute the value which the bitfield will contain.
10435   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10436   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10437 
10438   // Check whether the stored value is equal to the original value.
10439   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10440   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10441     return false;
10442 
10443   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10444   // therefore don't strictly fit into a signed bitfield of width 1.
10445   if (FieldWidth == 1 && Value == 1)
10446     return false;
10447 
10448   std::string PrettyValue = Value.toString(10);
10449   std::string PrettyTrunc = TruncatedValue.toString(10);
10450 
10451   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10452     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10453     << Init->getSourceRange();
10454 
10455   return true;
10456 }
10457 
10458 /// Analyze the given simple or compound assignment for warning-worthy
10459 /// operations.
10460 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10461   // Just recurse on the LHS.
10462   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10463 
10464   // We want to recurse on the RHS as normal unless we're assigning to
10465   // a bitfield.
10466   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10467     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10468                                   E->getOperatorLoc())) {
10469       // Recurse, ignoring any implicit conversions on the RHS.
10470       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10471                                         E->getOperatorLoc());
10472     }
10473   }
10474 
10475   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10476 
10477   // Diagnose implicitly sequentially-consistent atomic assignment.
10478   if (E->getLHS()->getType()->isAtomicType())
10479     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10480 }
10481 
10482 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10483 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10484                             SourceLocation CContext, unsigned diag,
10485                             bool pruneControlFlow = false) {
10486   if (pruneControlFlow) {
10487     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10488                           S.PDiag(diag)
10489                             << SourceType << T << E->getSourceRange()
10490                             << SourceRange(CContext));
10491     return;
10492   }
10493   S.Diag(E->getExprLoc(), diag)
10494     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10495 }
10496 
10497 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10498 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10499                             SourceLocation CContext,
10500                             unsigned diag, bool pruneControlFlow = false) {
10501   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10502 }
10503 
10504 /// Diagnose an implicit cast from a floating point value to an integer value.
10505 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10506                                     SourceLocation CContext) {
10507   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10508   const bool PruneWarnings = S.inTemplateInstantiation();
10509 
10510   Expr *InnerE = E->IgnoreParenImpCasts();
10511   // We also want to warn on, e.g., "int i = -1.234"
10512   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10513     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10514       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10515 
10516   const bool IsLiteral =
10517       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10518 
10519   llvm::APFloat Value(0.0);
10520   bool IsConstant =
10521     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10522   if (!IsConstant) {
10523     return DiagnoseImpCast(S, E, T, CContext,
10524                            diag::warn_impcast_float_integer, PruneWarnings);
10525   }
10526 
10527   bool isExact = false;
10528 
10529   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10530                             T->hasUnsignedIntegerRepresentation());
10531   llvm::APFloat::opStatus Result = Value.convertToInteger(
10532       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10533 
10534   if (Result == llvm::APFloat::opOK && isExact) {
10535     if (IsLiteral) return;
10536     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10537                            PruneWarnings);
10538   }
10539 
10540   // Conversion of a floating-point value to a non-bool integer where the
10541   // integral part cannot be represented by the integer type is undefined.
10542   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10543     return DiagnoseImpCast(
10544         S, E, T, CContext,
10545         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10546                   : diag::warn_impcast_float_to_integer_out_of_range,
10547         PruneWarnings);
10548 
10549   unsigned DiagID = 0;
10550   if (IsLiteral) {
10551     // Warn on floating point literal to integer.
10552     DiagID = diag::warn_impcast_literal_float_to_integer;
10553   } else if (IntegerValue == 0) {
10554     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10555       return DiagnoseImpCast(S, E, T, CContext,
10556                              diag::warn_impcast_float_integer, PruneWarnings);
10557     }
10558     // Warn on non-zero to zero conversion.
10559     DiagID = diag::warn_impcast_float_to_integer_zero;
10560   } else {
10561     if (IntegerValue.isUnsigned()) {
10562       if (!IntegerValue.isMaxValue()) {
10563         return DiagnoseImpCast(S, E, T, CContext,
10564                                diag::warn_impcast_float_integer, PruneWarnings);
10565       }
10566     } else {  // IntegerValue.isSigned()
10567       if (!IntegerValue.isMaxSignedValue() &&
10568           !IntegerValue.isMinSignedValue()) {
10569         return DiagnoseImpCast(S, E, T, CContext,
10570                                diag::warn_impcast_float_integer, PruneWarnings);
10571       }
10572     }
10573     // Warn on evaluatable floating point expression to integer conversion.
10574     DiagID = diag::warn_impcast_float_to_integer;
10575   }
10576 
10577   // FIXME: Force the precision of the source value down so we don't print
10578   // digits which are usually useless (we don't really care here if we
10579   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10580   // would automatically print the shortest representation, but it's a bit
10581   // tricky to implement.
10582   SmallString<16> PrettySourceValue;
10583   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10584   precision = (precision * 59 + 195) / 196;
10585   Value.toString(PrettySourceValue, precision);
10586 
10587   SmallString<16> PrettyTargetValue;
10588   if (IsBool)
10589     PrettyTargetValue = Value.isZero() ? "false" : "true";
10590   else
10591     IntegerValue.toString(PrettyTargetValue);
10592 
10593   if (PruneWarnings) {
10594     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10595                           S.PDiag(DiagID)
10596                               << E->getType() << T.getUnqualifiedType()
10597                               << PrettySourceValue << PrettyTargetValue
10598                               << E->getSourceRange() << SourceRange(CContext));
10599   } else {
10600     S.Diag(E->getExprLoc(), DiagID)
10601         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10602         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10603   }
10604 }
10605 
10606 /// Analyze the given compound assignment for the possible losing of
10607 /// floating-point precision.
10608 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10609   assert(isa<CompoundAssignOperator>(E) &&
10610          "Must be compound assignment operation");
10611   // Recurse on the LHS and RHS in here
10612   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10613   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10614 
10615   if (E->getLHS()->getType()->isAtomicType())
10616     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10617 
10618   // Now check the outermost expression
10619   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10620   const auto *RBT = cast<CompoundAssignOperator>(E)
10621                         ->getComputationResultType()
10622                         ->getAs<BuiltinType>();
10623 
10624   // The below checks assume source is floating point.
10625   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10626 
10627   // If source is floating point but target is not.
10628   if (!ResultBT->isFloatingPoint())
10629     return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
10630                                    E->getExprLoc());
10631 
10632   // If both source and target are floating points.
10633   // Builtin FP kinds are ordered by increasing FP rank.
10634   if (ResultBT->getKind() < RBT->getKind() &&
10635       // We don't want to warn for system macro.
10636       !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10637     // warn about dropping FP rank.
10638     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10639                     diag::warn_impcast_float_result_precision);
10640 }
10641 
10642 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10643                                       IntRange Range) {
10644   if (!Range.Width) return "0";
10645 
10646   llvm::APSInt ValueInRange = Value;
10647   ValueInRange.setIsSigned(!Range.NonNegative);
10648   ValueInRange = ValueInRange.trunc(Range.Width);
10649   return ValueInRange.toString(10);
10650 }
10651 
10652 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10653   if (!isa<ImplicitCastExpr>(Ex))
10654     return false;
10655 
10656   Expr *InnerE = Ex->IgnoreParenImpCasts();
10657   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10658   const Type *Source =
10659     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10660   if (Target->isDependentType())
10661     return false;
10662 
10663   const BuiltinType *FloatCandidateBT =
10664     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10665   const Type *BoolCandidateType = ToBool ? Target : Source;
10666 
10667   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10668           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10669 }
10670 
10671 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10672                                              SourceLocation CC) {
10673   unsigned NumArgs = TheCall->getNumArgs();
10674   for (unsigned i = 0; i < NumArgs; ++i) {
10675     Expr *CurrA = TheCall->getArg(i);
10676     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10677       continue;
10678 
10679     bool IsSwapped = ((i > 0) &&
10680         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10681     IsSwapped |= ((i < (NumArgs - 1)) &&
10682         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10683     if (IsSwapped) {
10684       // Warn on this floating-point to bool conversion.
10685       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10686                       CurrA->getType(), CC,
10687                       diag::warn_impcast_floating_point_to_bool);
10688     }
10689   }
10690 }
10691 
10692 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10693                                    SourceLocation CC) {
10694   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10695                         E->getExprLoc()))
10696     return;
10697 
10698   // Don't warn on functions which have return type nullptr_t.
10699   if (isa<CallExpr>(E))
10700     return;
10701 
10702   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10703   const Expr::NullPointerConstantKind NullKind =
10704       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10705   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10706     return;
10707 
10708   // Return if target type is a safe conversion.
10709   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10710       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10711     return;
10712 
10713   SourceLocation Loc = E->getSourceRange().getBegin();
10714 
10715   // Venture through the macro stacks to get to the source of macro arguments.
10716   // The new location is a better location than the complete location that was
10717   // passed in.
10718   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10719   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10720 
10721   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10722   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10723     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10724         Loc, S.SourceMgr, S.getLangOpts());
10725     if (MacroName == "NULL")
10726       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10727   }
10728 
10729   // Only warn if the null and context location are in the same macro expansion.
10730   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10731     return;
10732 
10733   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10734       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10735       << FixItHint::CreateReplacement(Loc,
10736                                       S.getFixItZeroLiteralForType(T, Loc));
10737 }
10738 
10739 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10740                                   ObjCArrayLiteral *ArrayLiteral);
10741 
10742 static void
10743 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10744                            ObjCDictionaryLiteral *DictionaryLiteral);
10745 
10746 /// Check a single element within a collection literal against the
10747 /// target element type.
10748 static void checkObjCCollectionLiteralElement(Sema &S,
10749                                               QualType TargetElementType,
10750                                               Expr *Element,
10751                                               unsigned ElementKind) {
10752   // Skip a bitcast to 'id' or qualified 'id'.
10753   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10754     if (ICE->getCastKind() == CK_BitCast &&
10755         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10756       Element = ICE->getSubExpr();
10757   }
10758 
10759   QualType ElementType = Element->getType();
10760   ExprResult ElementResult(Element);
10761   if (ElementType->getAs<ObjCObjectPointerType>() &&
10762       S.CheckSingleAssignmentConstraints(TargetElementType,
10763                                          ElementResult,
10764                                          false, false)
10765         != Sema::Compatible) {
10766     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10767         << ElementType << ElementKind << TargetElementType
10768         << Element->getSourceRange();
10769   }
10770 
10771   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10772     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10773   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10774     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10775 }
10776 
10777 /// Check an Objective-C array literal being converted to the given
10778 /// target type.
10779 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10780                                   ObjCArrayLiteral *ArrayLiteral) {
10781   if (!S.NSArrayDecl)
10782     return;
10783 
10784   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10785   if (!TargetObjCPtr)
10786     return;
10787 
10788   if (TargetObjCPtr->isUnspecialized() ||
10789       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10790         != S.NSArrayDecl->getCanonicalDecl())
10791     return;
10792 
10793   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10794   if (TypeArgs.size() != 1)
10795     return;
10796 
10797   QualType TargetElementType = TypeArgs[0];
10798   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10799     checkObjCCollectionLiteralElement(S, TargetElementType,
10800                                       ArrayLiteral->getElement(I),
10801                                       0);
10802   }
10803 }
10804 
10805 /// Check an Objective-C dictionary literal being converted to the given
10806 /// target type.
10807 static void
10808 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10809                            ObjCDictionaryLiteral *DictionaryLiteral) {
10810   if (!S.NSDictionaryDecl)
10811     return;
10812 
10813   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10814   if (!TargetObjCPtr)
10815     return;
10816 
10817   if (TargetObjCPtr->isUnspecialized() ||
10818       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10819         != S.NSDictionaryDecl->getCanonicalDecl())
10820     return;
10821 
10822   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10823   if (TypeArgs.size() != 2)
10824     return;
10825 
10826   QualType TargetKeyType = TypeArgs[0];
10827   QualType TargetObjectType = TypeArgs[1];
10828   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10829     auto Element = DictionaryLiteral->getKeyValueElement(I);
10830     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10831     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10832   }
10833 }
10834 
10835 // Helper function to filter out cases for constant width constant conversion.
10836 // Don't warn on char array initialization or for non-decimal values.
10837 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10838                                           SourceLocation CC) {
10839   // If initializing from a constant, and the constant starts with '0',
10840   // then it is a binary, octal, or hexadecimal.  Allow these constants
10841   // to fill all the bits, even if there is a sign change.
10842   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10843     const char FirstLiteralCharacter =
10844         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10845     if (FirstLiteralCharacter == '0')
10846       return false;
10847   }
10848 
10849   // If the CC location points to a '{', and the type is char, then assume
10850   // assume it is an array initialization.
10851   if (CC.isValid() && T->isCharType()) {
10852     const char FirstContextCharacter =
10853         S.getSourceManager().getCharacterData(CC)[0];
10854     if (FirstContextCharacter == '{')
10855       return false;
10856   }
10857 
10858   return true;
10859 }
10860 
10861 static void
10862 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10863                         bool *ICContext = nullptr) {
10864   if (E->isTypeDependent() || E->isValueDependent()) return;
10865 
10866   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10867   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10868   if (Source == Target) return;
10869   if (Target->isDependentType()) return;
10870 
10871   // If the conversion context location is invalid don't complain. We also
10872   // don't want to emit a warning if the issue occurs from the expansion of
10873   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10874   // delay this check as long as possible. Once we detect we are in that
10875   // scenario, we just return.
10876   if (CC.isInvalid())
10877     return;
10878 
10879   if (Source->isAtomicType())
10880     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10881 
10882   // Diagnose implicit casts to bool.
10883   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10884     if (isa<StringLiteral>(E))
10885       // Warn on string literal to bool.  Checks for string literals in logical
10886       // and expressions, for instance, assert(0 && "error here"), are
10887       // prevented by a check in AnalyzeImplicitConversions().
10888       return DiagnoseImpCast(S, E, T, CC,
10889                              diag::warn_impcast_string_literal_to_bool);
10890     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10891         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10892       // This covers the literal expressions that evaluate to Objective-C
10893       // objects.
10894       return DiagnoseImpCast(S, E, T, CC,
10895                              diag::warn_impcast_objective_c_literal_to_bool);
10896     }
10897     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10898       // Warn on pointer to bool conversion that is always true.
10899       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10900                                      SourceRange(CC));
10901     }
10902   }
10903 
10904   // Check implicit casts from Objective-C collection literals to specialized
10905   // collection types, e.g., NSArray<NSString *> *.
10906   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10907     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10908   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10909     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10910 
10911   // Strip vector types.
10912   if (isa<VectorType>(Source)) {
10913     if (!isa<VectorType>(Target)) {
10914       if (S.SourceMgr.isInSystemMacro(CC))
10915         return;
10916       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10917     }
10918 
10919     // If the vector cast is cast between two vectors of the same size, it is
10920     // a bitcast, not a conversion.
10921     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10922       return;
10923 
10924     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10925     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10926   }
10927   if (auto VecTy = dyn_cast<VectorType>(Target))
10928     Target = VecTy->getElementType().getTypePtr();
10929 
10930   // Strip complex types.
10931   if (isa<ComplexType>(Source)) {
10932     if (!isa<ComplexType>(Target)) {
10933       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10934         return;
10935 
10936       return DiagnoseImpCast(S, E, T, CC,
10937                              S.getLangOpts().CPlusPlus
10938                                  ? diag::err_impcast_complex_scalar
10939                                  : diag::warn_impcast_complex_scalar);
10940     }
10941 
10942     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10943     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10944   }
10945 
10946   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10947   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10948 
10949   // If the source is floating point...
10950   if (SourceBT && SourceBT->isFloatingPoint()) {
10951     // ...and the target is floating point...
10952     if (TargetBT && TargetBT->isFloatingPoint()) {
10953       // ...then warn if we're dropping FP rank.
10954 
10955       // Builtin FP kinds are ordered by increasing FP rank.
10956       if (SourceBT->getKind() > TargetBT->getKind()) {
10957         // Don't warn about float constants that are precisely
10958         // representable in the target type.
10959         Expr::EvalResult result;
10960         if (E->EvaluateAsRValue(result, S.Context)) {
10961           // Value might be a float, a float vector, or a float complex.
10962           if (IsSameFloatAfterCast(result.Val,
10963                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10964                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10965             return;
10966         }
10967 
10968         if (S.SourceMgr.isInSystemMacro(CC))
10969           return;
10970 
10971         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10972       }
10973       // ... or possibly if we're increasing rank, too
10974       else if (TargetBT->getKind() > SourceBT->getKind()) {
10975         if (S.SourceMgr.isInSystemMacro(CC))
10976           return;
10977 
10978         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10979       }
10980       return;
10981     }
10982 
10983     // If the target is integral, always warn.
10984     if (TargetBT && TargetBT->isInteger()) {
10985       if (S.SourceMgr.isInSystemMacro(CC))
10986         return;
10987 
10988       DiagnoseFloatingImpCast(S, E, T, CC);
10989     }
10990 
10991     // Detect the case where a call result is converted from floating-point to
10992     // to bool, and the final argument to the call is converted from bool, to
10993     // discover this typo:
10994     //
10995     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10996     //
10997     // FIXME: This is an incredibly special case; is there some more general
10998     // way to detect this class of misplaced-parentheses bug?
10999     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11000       // Check last argument of function call to see if it is an
11001       // implicit cast from a type matching the type the result
11002       // is being cast to.
11003       CallExpr *CEx = cast<CallExpr>(E);
11004       if (unsigned NumArgs = CEx->getNumArgs()) {
11005         Expr *LastA = CEx->getArg(NumArgs - 1);
11006         Expr *InnerE = LastA->IgnoreParenImpCasts();
11007         if (isa<ImplicitCastExpr>(LastA) &&
11008             InnerE->getType()->isBooleanType()) {
11009           // Warn on this floating-point to bool conversion
11010           DiagnoseImpCast(S, E, T, CC,
11011                           diag::warn_impcast_floating_point_to_bool);
11012         }
11013       }
11014     }
11015     return;
11016   }
11017 
11018   DiagnoseNullConversion(S, E, T, CC);
11019 
11020   S.DiscardMisalignedMemberAddress(Target, E);
11021 
11022   if (!Source->isIntegerType() || !Target->isIntegerType())
11023     return;
11024 
11025   // TODO: remove this early return once the false positives for constant->bool
11026   // in templates, macros, etc, are reduced or removed.
11027   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11028     return;
11029 
11030   IntRange SourceRange = GetExprRange(S.Context, E);
11031   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11032 
11033   if (SourceRange.Width > TargetRange.Width) {
11034     // If the source is a constant, use a default-on diagnostic.
11035     // TODO: this should happen for bitfield stores, too.
11036     Expr::EvalResult Result;
11037     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11038       llvm::APSInt Value(32);
11039       Value = Result.Val.getInt();
11040 
11041       if (S.SourceMgr.isInSystemMacro(CC))
11042         return;
11043 
11044       std::string PrettySourceValue = Value.toString(10);
11045       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11046 
11047       S.DiagRuntimeBehavior(E->getExprLoc(), E,
11048         S.PDiag(diag::warn_impcast_integer_precision_constant)
11049             << PrettySourceValue << PrettyTargetValue
11050             << E->getType() << T << E->getSourceRange()
11051             << clang::SourceRange(CC));
11052       return;
11053     }
11054 
11055     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11056     if (S.SourceMgr.isInSystemMacro(CC))
11057       return;
11058 
11059     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11060       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11061                              /* pruneControlFlow */ true);
11062     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11063   }
11064 
11065   if (TargetRange.Width > SourceRange.Width) {
11066     if (auto *UO = dyn_cast<UnaryOperator>(E))
11067       if (UO->getOpcode() == UO_Minus)
11068         if (Source->isUnsignedIntegerType()) {
11069           if (Target->isUnsignedIntegerType())
11070             return DiagnoseImpCast(S, E, T, CC,
11071                                    diag::warn_impcast_high_order_zero_bits);
11072           if (Target->isSignedIntegerType())
11073             return DiagnoseImpCast(S, E, T, CC,
11074                                    diag::warn_impcast_nonnegative_result);
11075         }
11076   }
11077 
11078   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11079       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11080     // Warn when doing a signed to signed conversion, warn if the positive
11081     // source value is exactly the width of the target type, which will
11082     // cause a negative value to be stored.
11083 
11084     Expr::EvalResult Result;
11085     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11086         !S.SourceMgr.isInSystemMacro(CC)) {
11087       llvm::APSInt Value = Result.Val.getInt();
11088       if (isSameWidthConstantConversion(S, E, T, CC)) {
11089         std::string PrettySourceValue = Value.toString(10);
11090         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11091 
11092         S.DiagRuntimeBehavior(
11093             E->getExprLoc(), E,
11094             S.PDiag(diag::warn_impcast_integer_precision_constant)
11095                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11096                 << E->getSourceRange() << clang::SourceRange(CC));
11097         return;
11098       }
11099     }
11100 
11101     // Fall through for non-constants to give a sign conversion warning.
11102   }
11103 
11104   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11105       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11106        SourceRange.Width == TargetRange.Width)) {
11107     if (S.SourceMgr.isInSystemMacro(CC))
11108       return;
11109 
11110     unsigned DiagID = diag::warn_impcast_integer_sign;
11111 
11112     // Traditionally, gcc has warned about this under -Wsign-compare.
11113     // We also want to warn about it in -Wconversion.
11114     // So if -Wconversion is off, use a completely identical diagnostic
11115     // in the sign-compare group.
11116     // The conditional-checking code will
11117     if (ICContext) {
11118       DiagID = diag::warn_impcast_integer_sign_conditional;
11119       *ICContext = true;
11120     }
11121 
11122     return DiagnoseImpCast(S, E, T, CC, DiagID);
11123   }
11124 
11125   // Diagnose conversions between different enumeration types.
11126   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11127   // type, to give us better diagnostics.
11128   QualType SourceType = E->getType();
11129   if (!S.getLangOpts().CPlusPlus) {
11130     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11131       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11132         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11133         SourceType = S.Context.getTypeDeclType(Enum);
11134         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11135       }
11136   }
11137 
11138   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11139     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11140       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11141           TargetEnum->getDecl()->hasNameForLinkage() &&
11142           SourceEnum != TargetEnum) {
11143         if (S.SourceMgr.isInSystemMacro(CC))
11144           return;
11145 
11146         return DiagnoseImpCast(S, E, SourceType, T, CC,
11147                                diag::warn_impcast_different_enum_types);
11148       }
11149 }
11150 
11151 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11152                                      SourceLocation CC, QualType T);
11153 
11154 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11155                                     SourceLocation CC, bool &ICContext) {
11156   E = E->IgnoreParenImpCasts();
11157 
11158   if (isa<ConditionalOperator>(E))
11159     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11160 
11161   AnalyzeImplicitConversions(S, E, CC);
11162   if (E->getType() != T)
11163     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11164 }
11165 
11166 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11167                                      SourceLocation CC, QualType T) {
11168   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11169 
11170   bool Suspicious = false;
11171   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11172   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11173 
11174   // If -Wconversion would have warned about either of the candidates
11175   // for a signedness conversion to the context type...
11176   if (!Suspicious) return;
11177 
11178   // ...but it's currently ignored...
11179   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11180     return;
11181 
11182   // ...then check whether it would have warned about either of the
11183   // candidates for a signedness conversion to the condition type.
11184   if (E->getType() == T) return;
11185 
11186   Suspicious = false;
11187   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11188                           E->getType(), CC, &Suspicious);
11189   if (!Suspicious)
11190     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11191                             E->getType(), CC, &Suspicious);
11192 }
11193 
11194 /// Check conversion of given expression to boolean.
11195 /// Input argument E is a logical expression.
11196 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11197   if (S.getLangOpts().Bool)
11198     return;
11199   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11200     return;
11201   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11202 }
11203 
11204 /// AnalyzeImplicitConversions - Find and report any interesting
11205 /// implicit conversions in the given expression.  There are a couple
11206 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11207 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11208                                        SourceLocation CC) {
11209   QualType T = OrigE->getType();
11210   Expr *E = OrigE->IgnoreParenImpCasts();
11211 
11212   if (E->isTypeDependent() || E->isValueDependent())
11213     return;
11214 
11215   // For conditional operators, we analyze the arguments as if they
11216   // were being fed directly into the output.
11217   if (isa<ConditionalOperator>(E)) {
11218     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11219     CheckConditionalOperator(S, CO, CC, T);
11220     return;
11221   }
11222 
11223   // Check implicit argument conversions for function calls.
11224   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11225     CheckImplicitArgumentConversions(S, Call, CC);
11226 
11227   // Go ahead and check any implicit conversions we might have skipped.
11228   // The non-canonical typecheck is just an optimization;
11229   // CheckImplicitConversion will filter out dead implicit conversions.
11230   if (E->getType() != T)
11231     CheckImplicitConversion(S, E, T, CC);
11232 
11233   // Now continue drilling into this expression.
11234 
11235   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11236     // The bound subexpressions in a PseudoObjectExpr are not reachable
11237     // as transitive children.
11238     // FIXME: Use a more uniform representation for this.
11239     for (auto *SE : POE->semantics())
11240       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11241         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11242   }
11243 
11244   // Skip past explicit casts.
11245   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11246     E = CE->getSubExpr()->IgnoreParenImpCasts();
11247     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11248       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11249     return AnalyzeImplicitConversions(S, E, CC);
11250   }
11251 
11252   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11253     // Do a somewhat different check with comparison operators.
11254     if (BO->isComparisonOp())
11255       return AnalyzeComparison(S, BO);
11256 
11257     // And with simple assignments.
11258     if (BO->getOpcode() == BO_Assign)
11259       return AnalyzeAssignment(S, BO);
11260     // And with compound assignments.
11261     if (BO->isAssignmentOp())
11262       return AnalyzeCompoundAssignment(S, BO);
11263   }
11264 
11265   // These break the otherwise-useful invariant below.  Fortunately,
11266   // we don't really need to recurse into them, because any internal
11267   // expressions should have been analyzed already when they were
11268   // built into statements.
11269   if (isa<StmtExpr>(E)) return;
11270 
11271   // Don't descend into unevaluated contexts.
11272   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11273 
11274   // Now just recurse over the expression's children.
11275   CC = E->getExprLoc();
11276   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11277   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11278   for (Stmt *SubStmt : E->children()) {
11279     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11280     if (!ChildExpr)
11281       continue;
11282 
11283     if (IsLogicalAndOperator &&
11284         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11285       // Ignore checking string literals that are in logical and operators.
11286       // This is a common pattern for asserts.
11287       continue;
11288     AnalyzeImplicitConversions(S, ChildExpr, CC);
11289   }
11290 
11291   if (BO && BO->isLogicalOp()) {
11292     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11293     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11294       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11295 
11296     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11297     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11298       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11299   }
11300 
11301   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11302     if (U->getOpcode() == UO_LNot) {
11303       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11304     } else if (U->getOpcode() != UO_AddrOf) {
11305       if (U->getSubExpr()->getType()->isAtomicType())
11306         S.Diag(U->getSubExpr()->getBeginLoc(),
11307                diag::warn_atomic_implicit_seq_cst);
11308     }
11309   }
11310 }
11311 
11312 /// Diagnose integer type and any valid implicit conversion to it.
11313 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11314   // Taking into account implicit conversions,
11315   // allow any integer.
11316   if (!E->getType()->isIntegerType()) {
11317     S.Diag(E->getBeginLoc(),
11318            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11319     return true;
11320   }
11321   // Potentially emit standard warnings for implicit conversions if enabled
11322   // using -Wconversion.
11323   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11324   return false;
11325 }
11326 
11327 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11328 // Returns true when emitting a warning about taking the address of a reference.
11329 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11330                               const PartialDiagnostic &PD) {
11331   E = E->IgnoreParenImpCasts();
11332 
11333   const FunctionDecl *FD = nullptr;
11334 
11335   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11336     if (!DRE->getDecl()->getType()->isReferenceType())
11337       return false;
11338   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11339     if (!M->getMemberDecl()->getType()->isReferenceType())
11340       return false;
11341   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11342     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11343       return false;
11344     FD = Call->getDirectCallee();
11345   } else {
11346     return false;
11347   }
11348 
11349   SemaRef.Diag(E->getExprLoc(), PD);
11350 
11351   // If possible, point to location of function.
11352   if (FD) {
11353     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11354   }
11355 
11356   return true;
11357 }
11358 
11359 // Returns true if the SourceLocation is expanded from any macro body.
11360 // Returns false if the SourceLocation is invalid, is from not in a macro
11361 // expansion, or is from expanded from a top-level macro argument.
11362 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11363   if (Loc.isInvalid())
11364     return false;
11365 
11366   while (Loc.isMacroID()) {
11367     if (SM.isMacroBodyExpansion(Loc))
11368       return true;
11369     Loc = SM.getImmediateMacroCallerLoc(Loc);
11370   }
11371 
11372   return false;
11373 }
11374 
11375 /// Diagnose pointers that are always non-null.
11376 /// \param E the expression containing the pointer
11377 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11378 /// compared to a null pointer
11379 /// \param IsEqual True when the comparison is equal to a null pointer
11380 /// \param Range Extra SourceRange to highlight in the diagnostic
11381 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11382                                         Expr::NullPointerConstantKind NullKind,
11383                                         bool IsEqual, SourceRange Range) {
11384   if (!E)
11385     return;
11386 
11387   // Don't warn inside macros.
11388   if (E->getExprLoc().isMacroID()) {
11389     const SourceManager &SM = getSourceManager();
11390     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11391         IsInAnyMacroBody(SM, Range.getBegin()))
11392       return;
11393   }
11394   E = E->IgnoreImpCasts();
11395 
11396   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11397 
11398   if (isa<CXXThisExpr>(E)) {
11399     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11400                                 : diag::warn_this_bool_conversion;
11401     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11402     return;
11403   }
11404 
11405   bool IsAddressOf = false;
11406 
11407   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11408     if (UO->getOpcode() != UO_AddrOf)
11409       return;
11410     IsAddressOf = true;
11411     E = UO->getSubExpr();
11412   }
11413 
11414   if (IsAddressOf) {
11415     unsigned DiagID = IsCompare
11416                           ? diag::warn_address_of_reference_null_compare
11417                           : diag::warn_address_of_reference_bool_conversion;
11418     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11419                                          << IsEqual;
11420     if (CheckForReference(*this, E, PD)) {
11421       return;
11422     }
11423   }
11424 
11425   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11426     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11427     std::string Str;
11428     llvm::raw_string_ostream S(Str);
11429     E->printPretty(S, nullptr, getPrintingPolicy());
11430     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11431                                 : diag::warn_cast_nonnull_to_bool;
11432     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11433       << E->getSourceRange() << Range << IsEqual;
11434     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11435   };
11436 
11437   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11438   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11439     if (auto *Callee = Call->getDirectCallee()) {
11440       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11441         ComplainAboutNonnullParamOrCall(A);
11442         return;
11443       }
11444     }
11445   }
11446 
11447   // Expect to find a single Decl.  Skip anything more complicated.
11448   ValueDecl *D = nullptr;
11449   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11450     D = R->getDecl();
11451   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11452     D = M->getMemberDecl();
11453   }
11454 
11455   // Weak Decls can be null.
11456   if (!D || D->isWeak())
11457     return;
11458 
11459   // Check for parameter decl with nonnull attribute
11460   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11461     if (getCurFunction() &&
11462         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11463       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11464         ComplainAboutNonnullParamOrCall(A);
11465         return;
11466       }
11467 
11468       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11469         auto ParamIter = llvm::find(FD->parameters(), PV);
11470         assert(ParamIter != FD->param_end());
11471         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11472 
11473         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11474           if (!NonNull->args_size()) {
11475               ComplainAboutNonnullParamOrCall(NonNull);
11476               return;
11477           }
11478 
11479           for (const ParamIdx &ArgNo : NonNull->args()) {
11480             if (ArgNo.getASTIndex() == ParamNo) {
11481               ComplainAboutNonnullParamOrCall(NonNull);
11482               return;
11483             }
11484           }
11485         }
11486       }
11487     }
11488   }
11489 
11490   QualType T = D->getType();
11491   const bool IsArray = T->isArrayType();
11492   const bool IsFunction = T->isFunctionType();
11493 
11494   // Address of function is used to silence the function warning.
11495   if (IsAddressOf && IsFunction) {
11496     return;
11497   }
11498 
11499   // Found nothing.
11500   if (!IsAddressOf && !IsFunction && !IsArray)
11501     return;
11502 
11503   // Pretty print the expression for the diagnostic.
11504   std::string Str;
11505   llvm::raw_string_ostream S(Str);
11506   E->printPretty(S, nullptr, getPrintingPolicy());
11507 
11508   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11509                               : diag::warn_impcast_pointer_to_bool;
11510   enum {
11511     AddressOf,
11512     FunctionPointer,
11513     ArrayPointer
11514   } DiagType;
11515   if (IsAddressOf)
11516     DiagType = AddressOf;
11517   else if (IsFunction)
11518     DiagType = FunctionPointer;
11519   else if (IsArray)
11520     DiagType = ArrayPointer;
11521   else
11522     llvm_unreachable("Could not determine diagnostic.");
11523   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11524                                 << Range << IsEqual;
11525 
11526   if (!IsFunction)
11527     return;
11528 
11529   // Suggest '&' to silence the function warning.
11530   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11531       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11532 
11533   // Check to see if '()' fixit should be emitted.
11534   QualType ReturnType;
11535   UnresolvedSet<4> NonTemplateOverloads;
11536   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11537   if (ReturnType.isNull())
11538     return;
11539 
11540   if (IsCompare) {
11541     // There are two cases here.  If there is null constant, the only suggest
11542     // for a pointer return type.  If the null is 0, then suggest if the return
11543     // type is a pointer or an integer type.
11544     if (!ReturnType->isPointerType()) {
11545       if (NullKind == Expr::NPCK_ZeroExpression ||
11546           NullKind == Expr::NPCK_ZeroLiteral) {
11547         if (!ReturnType->isIntegerType())
11548           return;
11549       } else {
11550         return;
11551       }
11552     }
11553   } else { // !IsCompare
11554     // For function to bool, only suggest if the function pointer has bool
11555     // return type.
11556     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11557       return;
11558   }
11559   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11560       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11561 }
11562 
11563 /// Diagnoses "dangerous" implicit conversions within the given
11564 /// expression (which is a full expression).  Implements -Wconversion
11565 /// and -Wsign-compare.
11566 ///
11567 /// \param CC the "context" location of the implicit conversion, i.e.
11568 ///   the most location of the syntactic entity requiring the implicit
11569 ///   conversion
11570 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11571   // Don't diagnose in unevaluated contexts.
11572   if (isUnevaluatedContext())
11573     return;
11574 
11575   // Don't diagnose for value- or type-dependent expressions.
11576   if (E->isTypeDependent() || E->isValueDependent())
11577     return;
11578 
11579   // Check for array bounds violations in cases where the check isn't triggered
11580   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11581   // ArraySubscriptExpr is on the RHS of a variable initialization.
11582   CheckArrayAccess(E);
11583 
11584   // This is not the right CC for (e.g.) a variable initialization.
11585   AnalyzeImplicitConversions(*this, E, CC);
11586 }
11587 
11588 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11589 /// Input argument E is a logical expression.
11590 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11591   ::CheckBoolLikeConversion(*this, E, CC);
11592 }
11593 
11594 /// Diagnose when expression is an integer constant expression and its evaluation
11595 /// results in integer overflow
11596 void Sema::CheckForIntOverflow (Expr *E) {
11597   // Use a work list to deal with nested struct initializers.
11598   SmallVector<Expr *, 2> Exprs(1, E);
11599 
11600   do {
11601     Expr *OriginalE = Exprs.pop_back_val();
11602     Expr *E = OriginalE->IgnoreParenCasts();
11603 
11604     if (isa<BinaryOperator>(E)) {
11605       E->EvaluateForOverflow(Context);
11606       continue;
11607     }
11608 
11609     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11610       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11611     else if (isa<ObjCBoxedExpr>(OriginalE))
11612       E->EvaluateForOverflow(Context);
11613     else if (auto Call = dyn_cast<CallExpr>(E))
11614       Exprs.append(Call->arg_begin(), Call->arg_end());
11615     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11616       Exprs.append(Message->arg_begin(), Message->arg_end());
11617   } while (!Exprs.empty());
11618 }
11619 
11620 namespace {
11621 
11622 /// Visitor for expressions which looks for unsequenced operations on the
11623 /// same object.
11624 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11625   using Base = EvaluatedExprVisitor<SequenceChecker>;
11626 
11627   /// A tree of sequenced regions within an expression. Two regions are
11628   /// unsequenced if one is an ancestor or a descendent of the other. When we
11629   /// finish processing an expression with sequencing, such as a comma
11630   /// expression, we fold its tree nodes into its parent, since they are
11631   /// unsequenced with respect to nodes we will visit later.
11632   class SequenceTree {
11633     struct Value {
11634       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11635       unsigned Parent : 31;
11636       unsigned Merged : 1;
11637     };
11638     SmallVector<Value, 8> Values;
11639 
11640   public:
11641     /// A region within an expression which may be sequenced with respect
11642     /// to some other region.
11643     class Seq {
11644       friend class SequenceTree;
11645 
11646       unsigned Index = 0;
11647 
11648       explicit Seq(unsigned N) : Index(N) {}
11649 
11650     public:
11651       Seq() = default;
11652     };
11653 
11654     SequenceTree() { Values.push_back(Value(0)); }
11655     Seq root() const { return Seq(0); }
11656 
11657     /// Create a new sequence of operations, which is an unsequenced
11658     /// subset of \p Parent. This sequence of operations is sequenced with
11659     /// respect to other children of \p Parent.
11660     Seq allocate(Seq Parent) {
11661       Values.push_back(Value(Parent.Index));
11662       return Seq(Values.size() - 1);
11663     }
11664 
11665     /// Merge a sequence of operations into its parent.
11666     void merge(Seq S) {
11667       Values[S.Index].Merged = true;
11668     }
11669 
11670     /// Determine whether two operations are unsequenced. This operation
11671     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11672     /// should have been merged into its parent as appropriate.
11673     bool isUnsequenced(Seq Cur, Seq Old) {
11674       unsigned C = representative(Cur.Index);
11675       unsigned Target = representative(Old.Index);
11676       while (C >= Target) {
11677         if (C == Target)
11678           return true;
11679         C = Values[C].Parent;
11680       }
11681       return false;
11682     }
11683 
11684   private:
11685     /// Pick a representative for a sequence.
11686     unsigned representative(unsigned K) {
11687       if (Values[K].Merged)
11688         // Perform path compression as we go.
11689         return Values[K].Parent = representative(Values[K].Parent);
11690       return K;
11691     }
11692   };
11693 
11694   /// An object for which we can track unsequenced uses.
11695   using Object = NamedDecl *;
11696 
11697   /// Different flavors of object usage which we track. We only track the
11698   /// least-sequenced usage of each kind.
11699   enum UsageKind {
11700     /// A read of an object. Multiple unsequenced reads are OK.
11701     UK_Use,
11702 
11703     /// A modification of an object which is sequenced before the value
11704     /// computation of the expression, such as ++n in C++.
11705     UK_ModAsValue,
11706 
11707     /// A modification of an object which is not sequenced before the value
11708     /// computation of the expression, such as n++.
11709     UK_ModAsSideEffect,
11710 
11711     UK_Count = UK_ModAsSideEffect + 1
11712   };
11713 
11714   struct Usage {
11715     Expr *Use = nullptr;
11716     SequenceTree::Seq Seq;
11717 
11718     Usage() = default;
11719   };
11720 
11721   struct UsageInfo {
11722     Usage Uses[UK_Count];
11723 
11724     /// Have we issued a diagnostic for this variable already?
11725     bool Diagnosed = false;
11726 
11727     UsageInfo() = default;
11728   };
11729   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11730 
11731   Sema &SemaRef;
11732 
11733   /// Sequenced regions within the expression.
11734   SequenceTree Tree;
11735 
11736   /// Declaration modifications and references which we have seen.
11737   UsageInfoMap UsageMap;
11738 
11739   /// The region we are currently within.
11740   SequenceTree::Seq Region;
11741 
11742   /// Filled in with declarations which were modified as a side-effect
11743   /// (that is, post-increment operations).
11744   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11745 
11746   /// Expressions to check later. We defer checking these to reduce
11747   /// stack usage.
11748   SmallVectorImpl<Expr *> &WorkList;
11749 
11750   /// RAII object wrapping the visitation of a sequenced subexpression of an
11751   /// expression. At the end of this process, the side-effects of the evaluation
11752   /// become sequenced with respect to the value computation of the result, so
11753   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11754   /// UK_ModAsValue.
11755   struct SequencedSubexpression {
11756     SequencedSubexpression(SequenceChecker &Self)
11757       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11758       Self.ModAsSideEffect = &ModAsSideEffect;
11759     }
11760 
11761     ~SequencedSubexpression() {
11762       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11763         UsageInfo &U = Self.UsageMap[M.first];
11764         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11765         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11766         SideEffectUsage = M.second;
11767       }
11768       Self.ModAsSideEffect = OldModAsSideEffect;
11769     }
11770 
11771     SequenceChecker &Self;
11772     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11773     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11774   };
11775 
11776   /// RAII object wrapping the visitation of a subexpression which we might
11777   /// choose to evaluate as a constant. If any subexpression is evaluated and
11778   /// found to be non-constant, this allows us to suppress the evaluation of
11779   /// the outer expression.
11780   class EvaluationTracker {
11781   public:
11782     EvaluationTracker(SequenceChecker &Self)
11783         : Self(Self), Prev(Self.EvalTracker) {
11784       Self.EvalTracker = this;
11785     }
11786 
11787     ~EvaluationTracker() {
11788       Self.EvalTracker = Prev;
11789       if (Prev)
11790         Prev->EvalOK &= EvalOK;
11791     }
11792 
11793     bool evaluate(const Expr *E, bool &Result) {
11794       if (!EvalOK || E->isValueDependent())
11795         return false;
11796       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11797       return EvalOK;
11798     }
11799 
11800   private:
11801     SequenceChecker &Self;
11802     EvaluationTracker *Prev;
11803     bool EvalOK = true;
11804   } *EvalTracker = nullptr;
11805 
11806   /// Find the object which is produced by the specified expression,
11807   /// if any.
11808   Object getObject(Expr *E, bool Mod) const {
11809     E = E->IgnoreParenCasts();
11810     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11811       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11812         return getObject(UO->getSubExpr(), Mod);
11813     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11814       if (BO->getOpcode() == BO_Comma)
11815         return getObject(BO->getRHS(), Mod);
11816       if (Mod && BO->isAssignmentOp())
11817         return getObject(BO->getLHS(), Mod);
11818     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11819       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11820       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11821         return ME->getMemberDecl();
11822     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11823       // FIXME: If this is a reference, map through to its value.
11824       return DRE->getDecl();
11825     return nullptr;
11826   }
11827 
11828   /// Note that an object was modified or used by an expression.
11829   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11830     Usage &U = UI.Uses[UK];
11831     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11832       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11833         ModAsSideEffect->push_back(std::make_pair(O, U));
11834       U.Use = Ref;
11835       U.Seq = Region;
11836     }
11837   }
11838 
11839   /// Check whether a modification or use conflicts with a prior usage.
11840   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11841                   bool IsModMod) {
11842     if (UI.Diagnosed)
11843       return;
11844 
11845     const Usage &U = UI.Uses[OtherKind];
11846     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11847       return;
11848 
11849     Expr *Mod = U.Use;
11850     Expr *ModOrUse = Ref;
11851     if (OtherKind == UK_Use)
11852       std::swap(Mod, ModOrUse);
11853 
11854     SemaRef.Diag(Mod->getExprLoc(),
11855                  IsModMod ? diag::warn_unsequenced_mod_mod
11856                           : diag::warn_unsequenced_mod_use)
11857       << O << SourceRange(ModOrUse->getExprLoc());
11858     UI.Diagnosed = true;
11859   }
11860 
11861   void notePreUse(Object O, Expr *Use) {
11862     UsageInfo &U = UsageMap[O];
11863     // Uses conflict with other modifications.
11864     checkUsage(O, U, Use, UK_ModAsValue, false);
11865   }
11866 
11867   void notePostUse(Object O, Expr *Use) {
11868     UsageInfo &U = UsageMap[O];
11869     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11870     addUsage(U, O, Use, UK_Use);
11871   }
11872 
11873   void notePreMod(Object O, Expr *Mod) {
11874     UsageInfo &U = UsageMap[O];
11875     // Modifications conflict with other modifications and with uses.
11876     checkUsage(O, U, Mod, UK_ModAsValue, true);
11877     checkUsage(O, U, Mod, UK_Use, false);
11878   }
11879 
11880   void notePostMod(Object O, Expr *Use, UsageKind UK) {
11881     UsageInfo &U = UsageMap[O];
11882     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11883     addUsage(U, O, Use, UK);
11884   }
11885 
11886 public:
11887   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
11888       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
11889     Visit(E);
11890   }
11891 
11892   void VisitStmt(Stmt *S) {
11893     // Skip all statements which aren't expressions for now.
11894   }
11895 
11896   void VisitExpr(Expr *E) {
11897     // By default, just recurse to evaluated subexpressions.
11898     Base::VisitStmt(E);
11899   }
11900 
11901   void VisitCastExpr(CastExpr *E) {
11902     Object O = Object();
11903     if (E->getCastKind() == CK_LValueToRValue)
11904       O = getObject(E->getSubExpr(), false);
11905 
11906     if (O)
11907       notePreUse(O, E);
11908     VisitExpr(E);
11909     if (O)
11910       notePostUse(O, E);
11911   }
11912 
11913   void VisitBinComma(BinaryOperator *BO) {
11914     // C++11 [expr.comma]p1:
11915     //   Every value computation and side effect associated with the left
11916     //   expression is sequenced before every value computation and side
11917     //   effect associated with the right expression.
11918     SequenceTree::Seq LHS = Tree.allocate(Region);
11919     SequenceTree::Seq RHS = Tree.allocate(Region);
11920     SequenceTree::Seq OldRegion = Region;
11921 
11922     {
11923       SequencedSubexpression SeqLHS(*this);
11924       Region = LHS;
11925       Visit(BO->getLHS());
11926     }
11927 
11928     Region = RHS;
11929     Visit(BO->getRHS());
11930 
11931     Region = OldRegion;
11932 
11933     // Forget that LHS and RHS are sequenced. They are both unsequenced
11934     // with respect to other stuff.
11935     Tree.merge(LHS);
11936     Tree.merge(RHS);
11937   }
11938 
11939   void VisitBinAssign(BinaryOperator *BO) {
11940     // The modification is sequenced after the value computation of the LHS
11941     // and RHS, so check it before inspecting the operands and update the
11942     // map afterwards.
11943     Object O = getObject(BO->getLHS(), true);
11944     if (!O)
11945       return VisitExpr(BO);
11946 
11947     notePreMod(O, BO);
11948 
11949     // C++11 [expr.ass]p7:
11950     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11951     //   only once.
11952     //
11953     // Therefore, for a compound assignment operator, O is considered used
11954     // everywhere except within the evaluation of E1 itself.
11955     if (isa<CompoundAssignOperator>(BO))
11956       notePreUse(O, BO);
11957 
11958     Visit(BO->getLHS());
11959 
11960     if (isa<CompoundAssignOperator>(BO))
11961       notePostUse(O, BO);
11962 
11963     Visit(BO->getRHS());
11964 
11965     // C++11 [expr.ass]p1:
11966     //   the assignment is sequenced [...] before the value computation of the
11967     //   assignment expression.
11968     // C11 6.5.16/3 has no such rule.
11969     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11970                                                        : UK_ModAsSideEffect);
11971   }
11972 
11973   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11974     VisitBinAssign(CAO);
11975   }
11976 
11977   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11978   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11979   void VisitUnaryPreIncDec(UnaryOperator *UO) {
11980     Object O = getObject(UO->getSubExpr(), true);
11981     if (!O)
11982       return VisitExpr(UO);
11983 
11984     notePreMod(O, UO);
11985     Visit(UO->getSubExpr());
11986     // C++11 [expr.pre.incr]p1:
11987     //   the expression ++x is equivalent to x+=1
11988     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11989                                                        : UK_ModAsSideEffect);
11990   }
11991 
11992   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11993   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11994   void VisitUnaryPostIncDec(UnaryOperator *UO) {
11995     Object O = getObject(UO->getSubExpr(), true);
11996     if (!O)
11997       return VisitExpr(UO);
11998 
11999     notePreMod(O, UO);
12000     Visit(UO->getSubExpr());
12001     notePostMod(O, UO, UK_ModAsSideEffect);
12002   }
12003 
12004   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12005   void VisitBinLOr(BinaryOperator *BO) {
12006     // The side-effects of the LHS of an '&&' are sequenced before the
12007     // value computation of the RHS, and hence before the value computation
12008     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12009     // as if they were unconditionally sequenced.
12010     EvaluationTracker Eval(*this);
12011     {
12012       SequencedSubexpression Sequenced(*this);
12013       Visit(BO->getLHS());
12014     }
12015 
12016     bool Result;
12017     if (Eval.evaluate(BO->getLHS(), Result)) {
12018       if (!Result)
12019         Visit(BO->getRHS());
12020     } else {
12021       // Check for unsequenced operations in the RHS, treating it as an
12022       // entirely separate evaluation.
12023       //
12024       // FIXME: If there are operations in the RHS which are unsequenced
12025       // with respect to operations outside the RHS, and those operations
12026       // are unconditionally evaluated, diagnose them.
12027       WorkList.push_back(BO->getRHS());
12028     }
12029   }
12030   void VisitBinLAnd(BinaryOperator *BO) {
12031     EvaluationTracker Eval(*this);
12032     {
12033       SequencedSubexpression Sequenced(*this);
12034       Visit(BO->getLHS());
12035     }
12036 
12037     bool Result;
12038     if (Eval.evaluate(BO->getLHS(), Result)) {
12039       if (Result)
12040         Visit(BO->getRHS());
12041     } else {
12042       WorkList.push_back(BO->getRHS());
12043     }
12044   }
12045 
12046   // Only visit the condition, unless we can be sure which subexpression will
12047   // be chosen.
12048   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12049     EvaluationTracker Eval(*this);
12050     {
12051       SequencedSubexpression Sequenced(*this);
12052       Visit(CO->getCond());
12053     }
12054 
12055     bool Result;
12056     if (Eval.evaluate(CO->getCond(), Result))
12057       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12058     else {
12059       WorkList.push_back(CO->getTrueExpr());
12060       WorkList.push_back(CO->getFalseExpr());
12061     }
12062   }
12063 
12064   void VisitCallExpr(CallExpr *CE) {
12065     // C++11 [intro.execution]p15:
12066     //   When calling a function [...], every value computation and side effect
12067     //   associated with any argument expression, or with the postfix expression
12068     //   designating the called function, is sequenced before execution of every
12069     //   expression or statement in the body of the function [and thus before
12070     //   the value computation of its result].
12071     SequencedSubexpression Sequenced(*this);
12072     Base::VisitCallExpr(CE);
12073 
12074     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12075   }
12076 
12077   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12078     // This is a call, so all subexpressions are sequenced before the result.
12079     SequencedSubexpression Sequenced(*this);
12080 
12081     if (!CCE->isListInitialization())
12082       return VisitExpr(CCE);
12083 
12084     // In C++11, list initializations are sequenced.
12085     SmallVector<SequenceTree::Seq, 32> Elts;
12086     SequenceTree::Seq Parent = Region;
12087     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12088                                         E = CCE->arg_end();
12089          I != E; ++I) {
12090       Region = Tree.allocate(Parent);
12091       Elts.push_back(Region);
12092       Visit(*I);
12093     }
12094 
12095     // Forget that the initializers are sequenced.
12096     Region = Parent;
12097     for (unsigned I = 0; I < Elts.size(); ++I)
12098       Tree.merge(Elts[I]);
12099   }
12100 
12101   void VisitInitListExpr(InitListExpr *ILE) {
12102     if (!SemaRef.getLangOpts().CPlusPlus11)
12103       return VisitExpr(ILE);
12104 
12105     // In C++11, list initializations are sequenced.
12106     SmallVector<SequenceTree::Seq, 32> Elts;
12107     SequenceTree::Seq Parent = Region;
12108     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12109       Expr *E = ILE->getInit(I);
12110       if (!E) continue;
12111       Region = Tree.allocate(Parent);
12112       Elts.push_back(Region);
12113       Visit(E);
12114     }
12115 
12116     // Forget that the initializers are sequenced.
12117     Region = Parent;
12118     for (unsigned I = 0; I < Elts.size(); ++I)
12119       Tree.merge(Elts[I]);
12120   }
12121 };
12122 
12123 } // namespace
12124 
12125 void Sema::CheckUnsequencedOperations(Expr *E) {
12126   SmallVector<Expr *, 8> WorkList;
12127   WorkList.push_back(E);
12128   while (!WorkList.empty()) {
12129     Expr *Item = WorkList.pop_back_val();
12130     SequenceChecker(*this, Item, WorkList);
12131   }
12132 }
12133 
12134 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12135                               bool IsConstexpr) {
12136   CheckImplicitConversions(E, CheckLoc);
12137   if (!E->isInstantiationDependent())
12138     CheckUnsequencedOperations(E);
12139   if (!IsConstexpr && !E->isValueDependent())
12140     CheckForIntOverflow(E);
12141   DiagnoseMisalignedMembers();
12142 }
12143 
12144 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12145                                        FieldDecl *BitField,
12146                                        Expr *Init) {
12147   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12148 }
12149 
12150 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12151                                          SourceLocation Loc) {
12152   if (!PType->isVariablyModifiedType())
12153     return;
12154   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12155     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12156     return;
12157   }
12158   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12159     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12160     return;
12161   }
12162   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12163     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12164     return;
12165   }
12166 
12167   const ArrayType *AT = S.Context.getAsArrayType(PType);
12168   if (!AT)
12169     return;
12170 
12171   if (AT->getSizeModifier() != ArrayType::Star) {
12172     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12173     return;
12174   }
12175 
12176   S.Diag(Loc, diag::err_array_star_in_function_definition);
12177 }
12178 
12179 /// CheckParmsForFunctionDef - Check that the parameters of the given
12180 /// function are appropriate for the definition of a function. This
12181 /// takes care of any checks that cannot be performed on the
12182 /// declaration itself, e.g., that the types of each of the function
12183 /// parameters are complete.
12184 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12185                                     bool CheckParameterNames) {
12186   bool HasInvalidParm = false;
12187   for (ParmVarDecl *Param : Parameters) {
12188     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12189     // function declarator that is part of a function definition of
12190     // that function shall not have incomplete type.
12191     //
12192     // This is also C++ [dcl.fct]p6.
12193     if (!Param->isInvalidDecl() &&
12194         RequireCompleteType(Param->getLocation(), Param->getType(),
12195                             diag::err_typecheck_decl_incomplete_type)) {
12196       Param->setInvalidDecl();
12197       HasInvalidParm = true;
12198     }
12199 
12200     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12201     // declaration of each parameter shall include an identifier.
12202     if (CheckParameterNames &&
12203         Param->getIdentifier() == nullptr &&
12204         !Param->isImplicit() &&
12205         !getLangOpts().CPlusPlus)
12206       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12207 
12208     // C99 6.7.5.3p12:
12209     //   If the function declarator is not part of a definition of that
12210     //   function, parameters may have incomplete type and may use the [*]
12211     //   notation in their sequences of declarator specifiers to specify
12212     //   variable length array types.
12213     QualType PType = Param->getOriginalType();
12214     // FIXME: This diagnostic should point the '[*]' if source-location
12215     // information is added for it.
12216     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12217 
12218     // If the parameter is a c++ class type and it has to be destructed in the
12219     // callee function, declare the destructor so that it can be called by the
12220     // callee function. Do not perform any direct access check on the dtor here.
12221     if (!Param->isInvalidDecl()) {
12222       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12223         if (!ClassDecl->isInvalidDecl() &&
12224             !ClassDecl->hasIrrelevantDestructor() &&
12225             !ClassDecl->isDependentContext() &&
12226             ClassDecl->isParamDestroyedInCallee()) {
12227           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12228           MarkFunctionReferenced(Param->getLocation(), Destructor);
12229           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12230         }
12231       }
12232     }
12233 
12234     // Parameters with the pass_object_size attribute only need to be marked
12235     // constant at function definitions. Because we lack information about
12236     // whether we're on a declaration or definition when we're instantiating the
12237     // attribute, we need to check for constness here.
12238     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12239       if (!Param->getType().isConstQualified())
12240         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12241             << Attr->getSpelling() << 1;
12242 
12243     // Check for parameter names shadowing fields from the class.
12244     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12245       // The owning context for the parameter should be the function, but we
12246       // want to see if this function's declaration context is a record.
12247       DeclContext *DC = Param->getDeclContext();
12248       if (DC && DC->isFunctionOrMethod()) {
12249         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12250           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12251                                      RD, /*DeclIsField*/ false);
12252       }
12253     }
12254   }
12255 
12256   return HasInvalidParm;
12257 }
12258 
12259 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12260 /// or MemberExpr.
12261 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12262                               ASTContext &Context) {
12263   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12264     return Context.getDeclAlign(DRE->getDecl());
12265 
12266   if (const auto *ME = dyn_cast<MemberExpr>(E))
12267     return Context.getDeclAlign(ME->getMemberDecl());
12268 
12269   return TypeAlign;
12270 }
12271 
12272 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12273 /// pointer cast increases the alignment requirements.
12274 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12275   // This is actually a lot of work to potentially be doing on every
12276   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12277   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12278     return;
12279 
12280   // Ignore dependent types.
12281   if (T->isDependentType() || Op->getType()->isDependentType())
12282     return;
12283 
12284   // Require that the destination be a pointer type.
12285   const PointerType *DestPtr = T->getAs<PointerType>();
12286   if (!DestPtr) return;
12287 
12288   // If the destination has alignment 1, we're done.
12289   QualType DestPointee = DestPtr->getPointeeType();
12290   if (DestPointee->isIncompleteType()) return;
12291   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12292   if (DestAlign.isOne()) return;
12293 
12294   // Require that the source be a pointer type.
12295   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12296   if (!SrcPtr) return;
12297   QualType SrcPointee = SrcPtr->getPointeeType();
12298 
12299   // Whitelist casts from cv void*.  We already implicitly
12300   // whitelisted casts to cv void*, since they have alignment 1.
12301   // Also whitelist casts involving incomplete types, which implicitly
12302   // includes 'void'.
12303   if (SrcPointee->isIncompleteType()) return;
12304 
12305   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12306 
12307   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12308     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12309       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12310   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12311     if (UO->getOpcode() == UO_AddrOf)
12312       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12313   }
12314 
12315   if (SrcAlign >= DestAlign) return;
12316 
12317   Diag(TRange.getBegin(), diag::warn_cast_align)
12318     << Op->getType() << T
12319     << static_cast<unsigned>(SrcAlign.getQuantity())
12320     << static_cast<unsigned>(DestAlign.getQuantity())
12321     << TRange << Op->getSourceRange();
12322 }
12323 
12324 /// Check whether this array fits the idiom of a size-one tail padded
12325 /// array member of a struct.
12326 ///
12327 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12328 /// commonly used to emulate flexible arrays in C89 code.
12329 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12330                                     const NamedDecl *ND) {
12331   if (Size != 1 || !ND) return false;
12332 
12333   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12334   if (!FD) return false;
12335 
12336   // Don't consider sizes resulting from macro expansions or template argument
12337   // substitution to form C89 tail-padded arrays.
12338 
12339   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12340   while (TInfo) {
12341     TypeLoc TL = TInfo->getTypeLoc();
12342     // Look through typedefs.
12343     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12344       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12345       TInfo = TDL->getTypeSourceInfo();
12346       continue;
12347     }
12348     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12349       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12350       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12351         return false;
12352     }
12353     break;
12354   }
12355 
12356   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12357   if (!RD) return false;
12358   if (RD->isUnion()) return false;
12359   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12360     if (!CRD->isStandardLayout()) return false;
12361   }
12362 
12363   // See if this is the last field decl in the record.
12364   const Decl *D = FD;
12365   while ((D = D->getNextDeclInContext()))
12366     if (isa<FieldDecl>(D))
12367       return false;
12368   return true;
12369 }
12370 
12371 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12372                             const ArraySubscriptExpr *ASE,
12373                             bool AllowOnePastEnd, bool IndexNegated) {
12374   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12375   if (IndexExpr->isValueDependent())
12376     return;
12377 
12378   const Type *EffectiveType =
12379       BaseExpr->getType()->getPointeeOrArrayElementType();
12380   BaseExpr = BaseExpr->IgnoreParenCasts();
12381   const ConstantArrayType *ArrayTy =
12382     Context.getAsConstantArrayType(BaseExpr->getType());
12383   if (!ArrayTy)
12384     return;
12385 
12386   Expr::EvalResult Result;
12387   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12388     return;
12389 
12390   llvm::APSInt index = Result.Val.getInt();
12391   if (IndexNegated)
12392     index = -index;
12393 
12394   const NamedDecl *ND = nullptr;
12395   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12396     ND = DRE->getDecl();
12397   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12398     ND = ME->getMemberDecl();
12399 
12400   if (index.isUnsigned() || !index.isNegative()) {
12401     llvm::APInt size = ArrayTy->getSize();
12402     if (!size.isStrictlyPositive())
12403       return;
12404 
12405     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
12406     if (BaseType != EffectiveType) {
12407       // Make sure we're comparing apples to apples when comparing index to size
12408       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12409       uint64_t array_typesize = Context.getTypeSize(BaseType);
12410       // Handle ptrarith_typesize being zero, such as when casting to void*
12411       if (!ptrarith_typesize) ptrarith_typesize = 1;
12412       if (ptrarith_typesize != array_typesize) {
12413         // There's a cast to a different size type involved
12414         uint64_t ratio = array_typesize / ptrarith_typesize;
12415         // TODO: Be smarter about handling cases where array_typesize is not a
12416         // multiple of ptrarith_typesize
12417         if (ptrarith_typesize * ratio == array_typesize)
12418           size *= llvm::APInt(size.getBitWidth(), ratio);
12419       }
12420     }
12421 
12422     if (size.getBitWidth() > index.getBitWidth())
12423       index = index.zext(size.getBitWidth());
12424     else if (size.getBitWidth() < index.getBitWidth())
12425       size = size.zext(index.getBitWidth());
12426 
12427     // For array subscripting the index must be less than size, but for pointer
12428     // arithmetic also allow the index (offset) to be equal to size since
12429     // computing the next address after the end of the array is legal and
12430     // commonly done e.g. in C++ iterators and range-based for loops.
12431     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12432       return;
12433 
12434     // Also don't warn for arrays of size 1 which are members of some
12435     // structure. These are often used to approximate flexible arrays in C89
12436     // code.
12437     if (IsTailPaddedMemberArray(*this, size, ND))
12438       return;
12439 
12440     // Suppress the warning if the subscript expression (as identified by the
12441     // ']' location) and the index expression are both from macro expansions
12442     // within a system header.
12443     if (ASE) {
12444       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12445           ASE->getRBracketLoc());
12446       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12447         SourceLocation IndexLoc =
12448             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12449         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12450           return;
12451       }
12452     }
12453 
12454     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12455     if (ASE)
12456       DiagID = diag::warn_array_index_exceeds_bounds;
12457 
12458     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12459                         PDiag(DiagID) << index.toString(10, true)
12460                                       << size.toString(10, true)
12461                                       << (unsigned)size.getLimitedValue(~0U)
12462                                       << IndexExpr->getSourceRange());
12463   } else {
12464     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12465     if (!ASE) {
12466       DiagID = diag::warn_ptr_arith_precedes_bounds;
12467       if (index.isNegative()) index = -index;
12468     }
12469 
12470     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12471                         PDiag(DiagID) << index.toString(10, true)
12472                                       << IndexExpr->getSourceRange());
12473   }
12474 
12475   if (!ND) {
12476     // Try harder to find a NamedDecl to point at in the note.
12477     while (const ArraySubscriptExpr *ASE =
12478            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12479       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12480     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12481       ND = DRE->getDecl();
12482     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12483       ND = ME->getMemberDecl();
12484   }
12485 
12486   if (ND)
12487     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12488                         PDiag(diag::note_array_index_out_of_bounds)
12489                             << ND->getDeclName());
12490 }
12491 
12492 void Sema::CheckArrayAccess(const Expr *expr) {
12493   int AllowOnePastEnd = 0;
12494   while (expr) {
12495     expr = expr->IgnoreParenImpCasts();
12496     switch (expr->getStmtClass()) {
12497       case Stmt::ArraySubscriptExprClass: {
12498         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12499         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12500                          AllowOnePastEnd > 0);
12501         expr = ASE->getBase();
12502         break;
12503       }
12504       case Stmt::MemberExprClass: {
12505         expr = cast<MemberExpr>(expr)->getBase();
12506         break;
12507       }
12508       case Stmt::OMPArraySectionExprClass: {
12509         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12510         if (ASE->getLowerBound())
12511           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12512                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12513         return;
12514       }
12515       case Stmt::UnaryOperatorClass: {
12516         // Only unwrap the * and & unary operators
12517         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12518         expr = UO->getSubExpr();
12519         switch (UO->getOpcode()) {
12520           case UO_AddrOf:
12521             AllowOnePastEnd++;
12522             break;
12523           case UO_Deref:
12524             AllowOnePastEnd--;
12525             break;
12526           default:
12527             return;
12528         }
12529         break;
12530       }
12531       case Stmt::ConditionalOperatorClass: {
12532         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12533         if (const Expr *lhs = cond->getLHS())
12534           CheckArrayAccess(lhs);
12535         if (const Expr *rhs = cond->getRHS())
12536           CheckArrayAccess(rhs);
12537         return;
12538       }
12539       case Stmt::CXXOperatorCallExprClass: {
12540         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12541         for (const auto *Arg : OCE->arguments())
12542           CheckArrayAccess(Arg);
12543         return;
12544       }
12545       default:
12546         return;
12547     }
12548   }
12549 }
12550 
12551 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12552 
12553 namespace {
12554 
12555 struct RetainCycleOwner {
12556   VarDecl *Variable = nullptr;
12557   SourceRange Range;
12558   SourceLocation Loc;
12559   bool Indirect = false;
12560 
12561   RetainCycleOwner() = default;
12562 
12563   void setLocsFrom(Expr *e) {
12564     Loc = e->getExprLoc();
12565     Range = e->getSourceRange();
12566   }
12567 };
12568 
12569 } // namespace
12570 
12571 /// Consider whether capturing the given variable can possibly lead to
12572 /// a retain cycle.
12573 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12574   // In ARC, it's captured strongly iff the variable has __strong
12575   // lifetime.  In MRR, it's captured strongly if the variable is
12576   // __block and has an appropriate type.
12577   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12578     return false;
12579 
12580   owner.Variable = var;
12581   if (ref)
12582     owner.setLocsFrom(ref);
12583   return true;
12584 }
12585 
12586 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12587   while (true) {
12588     e = e->IgnoreParens();
12589     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12590       switch (cast->getCastKind()) {
12591       case CK_BitCast:
12592       case CK_LValueBitCast:
12593       case CK_LValueToRValue:
12594       case CK_ARCReclaimReturnedObject:
12595         e = cast->getSubExpr();
12596         continue;
12597 
12598       default:
12599         return false;
12600       }
12601     }
12602 
12603     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12604       ObjCIvarDecl *ivar = ref->getDecl();
12605       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12606         return false;
12607 
12608       // Try to find a retain cycle in the base.
12609       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12610         return false;
12611 
12612       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12613       owner.Indirect = true;
12614       return true;
12615     }
12616 
12617     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12618       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12619       if (!var) return false;
12620       return considerVariable(var, ref, owner);
12621     }
12622 
12623     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12624       if (member->isArrow()) return false;
12625 
12626       // Don't count this as an indirect ownership.
12627       e = member->getBase();
12628       continue;
12629     }
12630 
12631     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12632       // Only pay attention to pseudo-objects on property references.
12633       ObjCPropertyRefExpr *pre
12634         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12635                                               ->IgnoreParens());
12636       if (!pre) return false;
12637       if (pre->isImplicitProperty()) return false;
12638       ObjCPropertyDecl *property = pre->getExplicitProperty();
12639       if (!property->isRetaining() &&
12640           !(property->getPropertyIvarDecl() &&
12641             property->getPropertyIvarDecl()->getType()
12642               .getObjCLifetime() == Qualifiers::OCL_Strong))
12643           return false;
12644 
12645       owner.Indirect = true;
12646       if (pre->isSuperReceiver()) {
12647         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12648         if (!owner.Variable)
12649           return false;
12650         owner.Loc = pre->getLocation();
12651         owner.Range = pre->getSourceRange();
12652         return true;
12653       }
12654       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12655                               ->getSourceExpr());
12656       continue;
12657     }
12658 
12659     // Array ivars?
12660 
12661     return false;
12662   }
12663 }
12664 
12665 namespace {
12666 
12667   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12668     ASTContext &Context;
12669     VarDecl *Variable;
12670     Expr *Capturer = nullptr;
12671     bool VarWillBeReased = false;
12672 
12673     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12674         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12675           Context(Context), Variable(variable) {}
12676 
12677     void VisitDeclRefExpr(DeclRefExpr *ref) {
12678       if (ref->getDecl() == Variable && !Capturer)
12679         Capturer = ref;
12680     }
12681 
12682     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12683       if (Capturer) return;
12684       Visit(ref->getBase());
12685       if (Capturer && ref->isFreeIvar())
12686         Capturer = ref;
12687     }
12688 
12689     void VisitBlockExpr(BlockExpr *block) {
12690       // Look inside nested blocks
12691       if (block->getBlockDecl()->capturesVariable(Variable))
12692         Visit(block->getBlockDecl()->getBody());
12693     }
12694 
12695     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12696       if (Capturer) return;
12697       if (OVE->getSourceExpr())
12698         Visit(OVE->getSourceExpr());
12699     }
12700 
12701     void VisitBinaryOperator(BinaryOperator *BinOp) {
12702       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12703         return;
12704       Expr *LHS = BinOp->getLHS();
12705       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12706         if (DRE->getDecl() != Variable)
12707           return;
12708         if (Expr *RHS = BinOp->getRHS()) {
12709           RHS = RHS->IgnoreParenCasts();
12710           llvm::APSInt Value;
12711           VarWillBeReased =
12712             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12713         }
12714       }
12715     }
12716   };
12717 
12718 } // namespace
12719 
12720 /// Check whether the given argument is a block which captures a
12721 /// variable.
12722 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12723   assert(owner.Variable && owner.Loc.isValid());
12724 
12725   e = e->IgnoreParenCasts();
12726 
12727   // Look through [^{...} copy] and Block_copy(^{...}).
12728   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12729     Selector Cmd = ME->getSelector();
12730     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12731       e = ME->getInstanceReceiver();
12732       if (!e)
12733         return nullptr;
12734       e = e->IgnoreParenCasts();
12735     }
12736   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12737     if (CE->getNumArgs() == 1) {
12738       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12739       if (Fn) {
12740         const IdentifierInfo *FnI = Fn->getIdentifier();
12741         if (FnI && FnI->isStr("_Block_copy")) {
12742           e = CE->getArg(0)->IgnoreParenCasts();
12743         }
12744       }
12745     }
12746   }
12747 
12748   BlockExpr *block = dyn_cast<BlockExpr>(e);
12749   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12750     return nullptr;
12751 
12752   FindCaptureVisitor visitor(S.Context, owner.Variable);
12753   visitor.Visit(block->getBlockDecl()->getBody());
12754   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12755 }
12756 
12757 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12758                                 RetainCycleOwner &owner) {
12759   assert(capturer);
12760   assert(owner.Variable && owner.Loc.isValid());
12761 
12762   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12763     << owner.Variable << capturer->getSourceRange();
12764   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12765     << owner.Indirect << owner.Range;
12766 }
12767 
12768 /// Check for a keyword selector that starts with the word 'add' or
12769 /// 'set'.
12770 static bool isSetterLikeSelector(Selector sel) {
12771   if (sel.isUnarySelector()) return false;
12772 
12773   StringRef str = sel.getNameForSlot(0);
12774   while (!str.empty() && str.front() == '_') str = str.substr(1);
12775   if (str.startswith("set"))
12776     str = str.substr(3);
12777   else if (str.startswith("add")) {
12778     // Specially whitelist 'addOperationWithBlock:'.
12779     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12780       return false;
12781     str = str.substr(3);
12782   }
12783   else
12784     return false;
12785 
12786   if (str.empty()) return true;
12787   return !isLowercase(str.front());
12788 }
12789 
12790 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12791                                                     ObjCMessageExpr *Message) {
12792   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12793                                                 Message->getReceiverInterface(),
12794                                                 NSAPI::ClassId_NSMutableArray);
12795   if (!IsMutableArray) {
12796     return None;
12797   }
12798 
12799   Selector Sel = Message->getSelector();
12800 
12801   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12802     S.NSAPIObj->getNSArrayMethodKind(Sel);
12803   if (!MKOpt) {
12804     return None;
12805   }
12806 
12807   NSAPI::NSArrayMethodKind MK = *MKOpt;
12808 
12809   switch (MK) {
12810     case NSAPI::NSMutableArr_addObject:
12811     case NSAPI::NSMutableArr_insertObjectAtIndex:
12812     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12813       return 0;
12814     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12815       return 1;
12816 
12817     default:
12818       return None;
12819   }
12820 
12821   return None;
12822 }
12823 
12824 static
12825 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12826                                                   ObjCMessageExpr *Message) {
12827   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12828                                             Message->getReceiverInterface(),
12829                                             NSAPI::ClassId_NSMutableDictionary);
12830   if (!IsMutableDictionary) {
12831     return None;
12832   }
12833 
12834   Selector Sel = Message->getSelector();
12835 
12836   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12837     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12838   if (!MKOpt) {
12839     return None;
12840   }
12841 
12842   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12843 
12844   switch (MK) {
12845     case NSAPI::NSMutableDict_setObjectForKey:
12846     case NSAPI::NSMutableDict_setValueForKey:
12847     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12848       return 0;
12849 
12850     default:
12851       return None;
12852   }
12853 
12854   return None;
12855 }
12856 
12857 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
12858   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12859                                                 Message->getReceiverInterface(),
12860                                                 NSAPI::ClassId_NSMutableSet);
12861 
12862   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12863                                             Message->getReceiverInterface(),
12864                                             NSAPI::ClassId_NSMutableOrderedSet);
12865   if (!IsMutableSet && !IsMutableOrderedSet) {
12866     return None;
12867   }
12868 
12869   Selector Sel = Message->getSelector();
12870 
12871   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12872   if (!MKOpt) {
12873     return None;
12874   }
12875 
12876   NSAPI::NSSetMethodKind MK = *MKOpt;
12877 
12878   switch (MK) {
12879     case NSAPI::NSMutableSet_addObject:
12880     case NSAPI::NSOrderedSet_setObjectAtIndex:
12881     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12882     case NSAPI::NSOrderedSet_insertObjectAtIndex:
12883       return 0;
12884     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12885       return 1;
12886   }
12887 
12888   return None;
12889 }
12890 
12891 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12892   if (!Message->isInstanceMessage()) {
12893     return;
12894   }
12895 
12896   Optional<int> ArgOpt;
12897 
12898   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12899       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12900       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12901     return;
12902   }
12903 
12904   int ArgIndex = *ArgOpt;
12905 
12906   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12907   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12908     Arg = OE->getSourceExpr()->IgnoreImpCasts();
12909   }
12910 
12911   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12912     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12913       if (ArgRE->isObjCSelfExpr()) {
12914         Diag(Message->getSourceRange().getBegin(),
12915              diag::warn_objc_circular_container)
12916           << ArgRE->getDecl() << StringRef("'super'");
12917       }
12918     }
12919   } else {
12920     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12921 
12922     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12923       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12924     }
12925 
12926     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12927       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12928         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12929           ValueDecl *Decl = ReceiverRE->getDecl();
12930           Diag(Message->getSourceRange().getBegin(),
12931                diag::warn_objc_circular_container)
12932             << Decl << Decl;
12933           if (!ArgRE->isObjCSelfExpr()) {
12934             Diag(Decl->getLocation(),
12935                  diag::note_objc_circular_container_declared_here)
12936               << Decl;
12937           }
12938         }
12939       }
12940     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12941       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12942         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12943           ObjCIvarDecl *Decl = IvarRE->getDecl();
12944           Diag(Message->getSourceRange().getBegin(),
12945                diag::warn_objc_circular_container)
12946             << Decl << Decl;
12947           Diag(Decl->getLocation(),
12948                diag::note_objc_circular_container_declared_here)
12949             << Decl;
12950         }
12951       }
12952     }
12953   }
12954 }
12955 
12956 /// Check a message send to see if it's likely to cause a retain cycle.
12957 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12958   // Only check instance methods whose selector looks like a setter.
12959   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12960     return;
12961 
12962   // Try to find a variable that the receiver is strongly owned by.
12963   RetainCycleOwner owner;
12964   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
12965     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
12966       return;
12967   } else {
12968     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12969     owner.Variable = getCurMethodDecl()->getSelfDecl();
12970     owner.Loc = msg->getSuperLoc();
12971     owner.Range = msg->getSuperLoc();
12972   }
12973 
12974   // Check whether the receiver is captured by any of the arguments.
12975   const ObjCMethodDecl *MD = msg->getMethodDecl();
12976   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12977     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12978       // noescape blocks should not be retained by the method.
12979       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12980         continue;
12981       return diagnoseRetainCycle(*this, capturer, owner);
12982     }
12983   }
12984 }
12985 
12986 /// Check a property assign to see if it's likely to cause a retain cycle.
12987 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12988   RetainCycleOwner owner;
12989   if (!findRetainCycleOwner(*this, receiver, owner))
12990     return;
12991 
12992   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12993     diagnoseRetainCycle(*this, capturer, owner);
12994 }
12995 
12996 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12997   RetainCycleOwner Owner;
12998   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
12999     return;
13000 
13001   // Because we don't have an expression for the variable, we have to set the
13002   // location explicitly here.
13003   Owner.Loc = Var->getLocation();
13004   Owner.Range = Var->getSourceRange();
13005 
13006   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13007     diagnoseRetainCycle(*this, Capturer, Owner);
13008 }
13009 
13010 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13011                                      Expr *RHS, bool isProperty) {
13012   // Check if RHS is an Objective-C object literal, which also can get
13013   // immediately zapped in a weak reference.  Note that we explicitly
13014   // allow ObjCStringLiterals, since those are designed to never really die.
13015   RHS = RHS->IgnoreParenImpCasts();
13016 
13017   // This enum needs to match with the 'select' in
13018   // warn_objc_arc_literal_assign (off-by-1).
13019   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13020   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13021     return false;
13022 
13023   S.Diag(Loc, diag::warn_arc_literal_assign)
13024     << (unsigned) Kind
13025     << (isProperty ? 0 : 1)
13026     << RHS->getSourceRange();
13027 
13028   return true;
13029 }
13030 
13031 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13032                                     Qualifiers::ObjCLifetime LT,
13033                                     Expr *RHS, bool isProperty) {
13034   // Strip off any implicit cast added to get to the one ARC-specific.
13035   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13036     if (cast->getCastKind() == CK_ARCConsumeObject) {
13037       S.Diag(Loc, diag::warn_arc_retained_assign)
13038         << (LT == Qualifiers::OCL_ExplicitNone)
13039         << (isProperty ? 0 : 1)
13040         << RHS->getSourceRange();
13041       return true;
13042     }
13043     RHS = cast->getSubExpr();
13044   }
13045 
13046   if (LT == Qualifiers::OCL_Weak &&
13047       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13048     return true;
13049 
13050   return false;
13051 }
13052 
13053 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13054                               QualType LHS, Expr *RHS) {
13055   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13056 
13057   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13058     return false;
13059 
13060   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13061     return true;
13062 
13063   return false;
13064 }
13065 
13066 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13067                               Expr *LHS, Expr *RHS) {
13068   QualType LHSType;
13069   // PropertyRef on LHS type need be directly obtained from
13070   // its declaration as it has a PseudoType.
13071   ObjCPropertyRefExpr *PRE
13072     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13073   if (PRE && !PRE->isImplicitProperty()) {
13074     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13075     if (PD)
13076       LHSType = PD->getType();
13077   }
13078 
13079   if (LHSType.isNull())
13080     LHSType = LHS->getType();
13081 
13082   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13083 
13084   if (LT == Qualifiers::OCL_Weak) {
13085     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13086       getCurFunction()->markSafeWeakUse(LHS);
13087   }
13088 
13089   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13090     return;
13091 
13092   // FIXME. Check for other life times.
13093   if (LT != Qualifiers::OCL_None)
13094     return;
13095 
13096   if (PRE) {
13097     if (PRE->isImplicitProperty())
13098       return;
13099     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13100     if (!PD)
13101       return;
13102 
13103     unsigned Attributes = PD->getPropertyAttributes();
13104     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13105       // when 'assign' attribute was not explicitly specified
13106       // by user, ignore it and rely on property type itself
13107       // for lifetime info.
13108       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13109       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13110           LHSType->isObjCRetainableType())
13111         return;
13112 
13113       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13114         if (cast->getCastKind() == CK_ARCConsumeObject) {
13115           Diag(Loc, diag::warn_arc_retained_property_assign)
13116           << RHS->getSourceRange();
13117           return;
13118         }
13119         RHS = cast->getSubExpr();
13120       }
13121     }
13122     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13123       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13124         return;
13125     }
13126   }
13127 }
13128 
13129 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13130 
13131 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13132                                         SourceLocation StmtLoc,
13133                                         const NullStmt *Body) {
13134   // Do not warn if the body is a macro that expands to nothing, e.g:
13135   //
13136   // #define CALL(x)
13137   // if (condition)
13138   //   CALL(0);
13139   if (Body->hasLeadingEmptyMacro())
13140     return false;
13141 
13142   // Get line numbers of statement and body.
13143   bool StmtLineInvalid;
13144   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13145                                                       &StmtLineInvalid);
13146   if (StmtLineInvalid)
13147     return false;
13148 
13149   bool BodyLineInvalid;
13150   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13151                                                       &BodyLineInvalid);
13152   if (BodyLineInvalid)
13153     return false;
13154 
13155   // Warn if null statement and body are on the same line.
13156   if (StmtLine != BodyLine)
13157     return false;
13158 
13159   return true;
13160 }
13161 
13162 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13163                                  const Stmt *Body,
13164                                  unsigned DiagID) {
13165   // Since this is a syntactic check, don't emit diagnostic for template
13166   // instantiations, this just adds noise.
13167   if (CurrentInstantiationScope)
13168     return;
13169 
13170   // The body should be a null statement.
13171   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13172   if (!NBody)
13173     return;
13174 
13175   // Do the usual checks.
13176   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13177     return;
13178 
13179   Diag(NBody->getSemiLoc(), DiagID);
13180   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13181 }
13182 
13183 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13184                                  const Stmt *PossibleBody) {
13185   assert(!CurrentInstantiationScope); // Ensured by caller
13186 
13187   SourceLocation StmtLoc;
13188   const Stmt *Body;
13189   unsigned DiagID;
13190   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13191     StmtLoc = FS->getRParenLoc();
13192     Body = FS->getBody();
13193     DiagID = diag::warn_empty_for_body;
13194   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13195     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13196     Body = WS->getBody();
13197     DiagID = diag::warn_empty_while_body;
13198   } else
13199     return; // Neither `for' nor `while'.
13200 
13201   // The body should be a null statement.
13202   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13203   if (!NBody)
13204     return;
13205 
13206   // Skip expensive checks if diagnostic is disabled.
13207   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13208     return;
13209 
13210   // Do the usual checks.
13211   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13212     return;
13213 
13214   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13215   // noise level low, emit diagnostics only if for/while is followed by a
13216   // CompoundStmt, e.g.:
13217   //    for (int i = 0; i < n; i++);
13218   //    {
13219   //      a(i);
13220   //    }
13221   // or if for/while is followed by a statement with more indentation
13222   // than for/while itself:
13223   //    for (int i = 0; i < n; i++);
13224   //      a(i);
13225   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13226   if (!ProbableTypo) {
13227     bool BodyColInvalid;
13228     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13229         PossibleBody->getBeginLoc(), &BodyColInvalid);
13230     if (BodyColInvalid)
13231       return;
13232 
13233     bool StmtColInvalid;
13234     unsigned StmtCol =
13235         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13236     if (StmtColInvalid)
13237       return;
13238 
13239     if (BodyCol > StmtCol)
13240       ProbableTypo = true;
13241   }
13242 
13243   if (ProbableTypo) {
13244     Diag(NBody->getSemiLoc(), DiagID);
13245     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13246   }
13247 }
13248 
13249 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13250 
13251 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13252 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13253                              SourceLocation OpLoc) {
13254   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13255     return;
13256 
13257   if (inTemplateInstantiation())
13258     return;
13259 
13260   // Strip parens and casts away.
13261   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13262   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13263 
13264   // Check for a call expression
13265   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13266   if (!CE || CE->getNumArgs() != 1)
13267     return;
13268 
13269   // Check for a call to std::move
13270   if (!CE->isCallToStdMove())
13271     return;
13272 
13273   // Get argument from std::move
13274   RHSExpr = CE->getArg(0);
13275 
13276   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13277   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13278 
13279   // Two DeclRefExpr's, check that the decls are the same.
13280   if (LHSDeclRef && RHSDeclRef) {
13281     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13282       return;
13283     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13284         RHSDeclRef->getDecl()->getCanonicalDecl())
13285       return;
13286 
13287     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13288                                         << LHSExpr->getSourceRange()
13289                                         << RHSExpr->getSourceRange();
13290     return;
13291   }
13292 
13293   // Member variables require a different approach to check for self moves.
13294   // MemberExpr's are the same if every nested MemberExpr refers to the same
13295   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13296   // the base Expr's are CXXThisExpr's.
13297   const Expr *LHSBase = LHSExpr;
13298   const Expr *RHSBase = RHSExpr;
13299   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13300   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13301   if (!LHSME || !RHSME)
13302     return;
13303 
13304   while (LHSME && RHSME) {
13305     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13306         RHSME->getMemberDecl()->getCanonicalDecl())
13307       return;
13308 
13309     LHSBase = LHSME->getBase();
13310     RHSBase = RHSME->getBase();
13311     LHSME = dyn_cast<MemberExpr>(LHSBase);
13312     RHSME = dyn_cast<MemberExpr>(RHSBase);
13313   }
13314 
13315   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13316   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13317   if (LHSDeclRef && RHSDeclRef) {
13318     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13319       return;
13320     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13321         RHSDeclRef->getDecl()->getCanonicalDecl())
13322       return;
13323 
13324     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13325                                         << LHSExpr->getSourceRange()
13326                                         << RHSExpr->getSourceRange();
13327     return;
13328   }
13329 
13330   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13331     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13332                                         << LHSExpr->getSourceRange()
13333                                         << RHSExpr->getSourceRange();
13334 }
13335 
13336 //===--- Layout compatibility ----------------------------------------------//
13337 
13338 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13339 
13340 /// Check if two enumeration types are layout-compatible.
13341 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13342   // C++11 [dcl.enum] p8:
13343   // Two enumeration types are layout-compatible if they have the same
13344   // underlying type.
13345   return ED1->isComplete() && ED2->isComplete() &&
13346          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13347 }
13348 
13349 /// Check if two fields are layout-compatible.
13350 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13351                                FieldDecl *Field2) {
13352   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13353     return false;
13354 
13355   if (Field1->isBitField() != Field2->isBitField())
13356     return false;
13357 
13358   if (Field1->isBitField()) {
13359     // Make sure that the bit-fields are the same length.
13360     unsigned Bits1 = Field1->getBitWidthValue(C);
13361     unsigned Bits2 = Field2->getBitWidthValue(C);
13362 
13363     if (Bits1 != Bits2)
13364       return false;
13365   }
13366 
13367   return true;
13368 }
13369 
13370 /// Check if two standard-layout structs are layout-compatible.
13371 /// (C++11 [class.mem] p17)
13372 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13373                                      RecordDecl *RD2) {
13374   // If both records are C++ classes, check that base classes match.
13375   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13376     // If one of records is a CXXRecordDecl we are in C++ mode,
13377     // thus the other one is a CXXRecordDecl, too.
13378     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13379     // Check number of base classes.
13380     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13381       return false;
13382 
13383     // Check the base classes.
13384     for (CXXRecordDecl::base_class_const_iterator
13385                Base1 = D1CXX->bases_begin(),
13386            BaseEnd1 = D1CXX->bases_end(),
13387               Base2 = D2CXX->bases_begin();
13388          Base1 != BaseEnd1;
13389          ++Base1, ++Base2) {
13390       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13391         return false;
13392     }
13393   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13394     // If only RD2 is a C++ class, it should have zero base classes.
13395     if (D2CXX->getNumBases() > 0)
13396       return false;
13397   }
13398 
13399   // Check the fields.
13400   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13401                              Field2End = RD2->field_end(),
13402                              Field1 = RD1->field_begin(),
13403                              Field1End = RD1->field_end();
13404   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13405     if (!isLayoutCompatible(C, *Field1, *Field2))
13406       return false;
13407   }
13408   if (Field1 != Field1End || Field2 != Field2End)
13409     return false;
13410 
13411   return true;
13412 }
13413 
13414 /// Check if two standard-layout unions are layout-compatible.
13415 /// (C++11 [class.mem] p18)
13416 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13417                                     RecordDecl *RD2) {
13418   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13419   for (auto *Field2 : RD2->fields())
13420     UnmatchedFields.insert(Field2);
13421 
13422   for (auto *Field1 : RD1->fields()) {
13423     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13424         I = UnmatchedFields.begin(),
13425         E = UnmatchedFields.end();
13426 
13427     for ( ; I != E; ++I) {
13428       if (isLayoutCompatible(C, Field1, *I)) {
13429         bool Result = UnmatchedFields.erase(*I);
13430         (void) Result;
13431         assert(Result);
13432         break;
13433       }
13434     }
13435     if (I == E)
13436       return false;
13437   }
13438 
13439   return UnmatchedFields.empty();
13440 }
13441 
13442 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13443                                RecordDecl *RD2) {
13444   if (RD1->isUnion() != RD2->isUnion())
13445     return false;
13446 
13447   if (RD1->isUnion())
13448     return isLayoutCompatibleUnion(C, RD1, RD2);
13449   else
13450     return isLayoutCompatibleStruct(C, RD1, RD2);
13451 }
13452 
13453 /// Check if two types are layout-compatible in C++11 sense.
13454 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13455   if (T1.isNull() || T2.isNull())
13456     return false;
13457 
13458   // C++11 [basic.types] p11:
13459   // If two types T1 and T2 are the same type, then T1 and T2 are
13460   // layout-compatible types.
13461   if (C.hasSameType(T1, T2))
13462     return true;
13463 
13464   T1 = T1.getCanonicalType().getUnqualifiedType();
13465   T2 = T2.getCanonicalType().getUnqualifiedType();
13466 
13467   const Type::TypeClass TC1 = T1->getTypeClass();
13468   const Type::TypeClass TC2 = T2->getTypeClass();
13469 
13470   if (TC1 != TC2)
13471     return false;
13472 
13473   if (TC1 == Type::Enum) {
13474     return isLayoutCompatible(C,
13475                               cast<EnumType>(T1)->getDecl(),
13476                               cast<EnumType>(T2)->getDecl());
13477   } else if (TC1 == Type::Record) {
13478     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13479       return false;
13480 
13481     return isLayoutCompatible(C,
13482                               cast<RecordType>(T1)->getDecl(),
13483                               cast<RecordType>(T2)->getDecl());
13484   }
13485 
13486   return false;
13487 }
13488 
13489 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13490 
13491 /// Given a type tag expression find the type tag itself.
13492 ///
13493 /// \param TypeExpr Type tag expression, as it appears in user's code.
13494 ///
13495 /// \param VD Declaration of an identifier that appears in a type tag.
13496 ///
13497 /// \param MagicValue Type tag magic value.
13498 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13499                             const ValueDecl **VD, uint64_t *MagicValue) {
13500   while(true) {
13501     if (!TypeExpr)
13502       return false;
13503 
13504     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13505 
13506     switch (TypeExpr->getStmtClass()) {
13507     case Stmt::UnaryOperatorClass: {
13508       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13509       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13510         TypeExpr = UO->getSubExpr();
13511         continue;
13512       }
13513       return false;
13514     }
13515 
13516     case Stmt::DeclRefExprClass: {
13517       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13518       *VD = DRE->getDecl();
13519       return true;
13520     }
13521 
13522     case Stmt::IntegerLiteralClass: {
13523       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13524       llvm::APInt MagicValueAPInt = IL->getValue();
13525       if (MagicValueAPInt.getActiveBits() <= 64) {
13526         *MagicValue = MagicValueAPInt.getZExtValue();
13527         return true;
13528       } else
13529         return false;
13530     }
13531 
13532     case Stmt::BinaryConditionalOperatorClass:
13533     case Stmt::ConditionalOperatorClass: {
13534       const AbstractConditionalOperator *ACO =
13535           cast<AbstractConditionalOperator>(TypeExpr);
13536       bool Result;
13537       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13538         if (Result)
13539           TypeExpr = ACO->getTrueExpr();
13540         else
13541           TypeExpr = ACO->getFalseExpr();
13542         continue;
13543       }
13544       return false;
13545     }
13546 
13547     case Stmt::BinaryOperatorClass: {
13548       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13549       if (BO->getOpcode() == BO_Comma) {
13550         TypeExpr = BO->getRHS();
13551         continue;
13552       }
13553       return false;
13554     }
13555 
13556     default:
13557       return false;
13558     }
13559   }
13560 }
13561 
13562 /// Retrieve the C type corresponding to type tag TypeExpr.
13563 ///
13564 /// \param TypeExpr Expression that specifies a type tag.
13565 ///
13566 /// \param MagicValues Registered magic values.
13567 ///
13568 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13569 ///        kind.
13570 ///
13571 /// \param TypeInfo Information about the corresponding C type.
13572 ///
13573 /// \returns true if the corresponding C type was found.
13574 static bool GetMatchingCType(
13575         const IdentifierInfo *ArgumentKind,
13576         const Expr *TypeExpr, const ASTContext &Ctx,
13577         const llvm::DenseMap<Sema::TypeTagMagicValue,
13578                              Sema::TypeTagData> *MagicValues,
13579         bool &FoundWrongKind,
13580         Sema::TypeTagData &TypeInfo) {
13581   FoundWrongKind = false;
13582 
13583   // Variable declaration that has type_tag_for_datatype attribute.
13584   const ValueDecl *VD = nullptr;
13585 
13586   uint64_t MagicValue;
13587 
13588   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13589     return false;
13590 
13591   if (VD) {
13592     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13593       if (I->getArgumentKind() != ArgumentKind) {
13594         FoundWrongKind = true;
13595         return false;
13596       }
13597       TypeInfo.Type = I->getMatchingCType();
13598       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13599       TypeInfo.MustBeNull = I->getMustBeNull();
13600       return true;
13601     }
13602     return false;
13603   }
13604 
13605   if (!MagicValues)
13606     return false;
13607 
13608   llvm::DenseMap<Sema::TypeTagMagicValue,
13609                  Sema::TypeTagData>::const_iterator I =
13610       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13611   if (I == MagicValues->end())
13612     return false;
13613 
13614   TypeInfo = I->second;
13615   return true;
13616 }
13617 
13618 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13619                                       uint64_t MagicValue, QualType Type,
13620                                       bool LayoutCompatible,
13621                                       bool MustBeNull) {
13622   if (!TypeTagForDatatypeMagicValues)
13623     TypeTagForDatatypeMagicValues.reset(
13624         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13625 
13626   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13627   (*TypeTagForDatatypeMagicValues)[Magic] =
13628       TypeTagData(Type, LayoutCompatible, MustBeNull);
13629 }
13630 
13631 static bool IsSameCharType(QualType T1, QualType T2) {
13632   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13633   if (!BT1)
13634     return false;
13635 
13636   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13637   if (!BT2)
13638     return false;
13639 
13640   BuiltinType::Kind T1Kind = BT1->getKind();
13641   BuiltinType::Kind T2Kind = BT2->getKind();
13642 
13643   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13644          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13645          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13646          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13647 }
13648 
13649 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13650                                     const ArrayRef<const Expr *> ExprArgs,
13651                                     SourceLocation CallSiteLoc) {
13652   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13653   bool IsPointerAttr = Attr->getIsPointer();
13654 
13655   // Retrieve the argument representing the 'type_tag'.
13656   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13657   if (TypeTagIdxAST >= ExprArgs.size()) {
13658     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13659         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13660     return;
13661   }
13662   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13663   bool FoundWrongKind;
13664   TypeTagData TypeInfo;
13665   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13666                         TypeTagForDatatypeMagicValues.get(),
13667                         FoundWrongKind, TypeInfo)) {
13668     if (FoundWrongKind)
13669       Diag(TypeTagExpr->getExprLoc(),
13670            diag::warn_type_tag_for_datatype_wrong_kind)
13671         << TypeTagExpr->getSourceRange();
13672     return;
13673   }
13674 
13675   // Retrieve the argument representing the 'arg_idx'.
13676   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13677   if (ArgumentIdxAST >= ExprArgs.size()) {
13678     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13679         << 1 << Attr->getArgumentIdx().getSourceIndex();
13680     return;
13681   }
13682   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13683   if (IsPointerAttr) {
13684     // Skip implicit cast of pointer to `void *' (as a function argument).
13685     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13686       if (ICE->getType()->isVoidPointerType() &&
13687           ICE->getCastKind() == CK_BitCast)
13688         ArgumentExpr = ICE->getSubExpr();
13689   }
13690   QualType ArgumentType = ArgumentExpr->getType();
13691 
13692   // Passing a `void*' pointer shouldn't trigger a warning.
13693   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13694     return;
13695 
13696   if (TypeInfo.MustBeNull) {
13697     // Type tag with matching void type requires a null pointer.
13698     if (!ArgumentExpr->isNullPointerConstant(Context,
13699                                              Expr::NPC_ValueDependentIsNotNull)) {
13700       Diag(ArgumentExpr->getExprLoc(),
13701            diag::warn_type_safety_null_pointer_required)
13702           << ArgumentKind->getName()
13703           << ArgumentExpr->getSourceRange()
13704           << TypeTagExpr->getSourceRange();
13705     }
13706     return;
13707   }
13708 
13709   QualType RequiredType = TypeInfo.Type;
13710   if (IsPointerAttr)
13711     RequiredType = Context.getPointerType(RequiredType);
13712 
13713   bool mismatch = false;
13714   if (!TypeInfo.LayoutCompatible) {
13715     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13716 
13717     // C++11 [basic.fundamental] p1:
13718     // Plain char, signed char, and unsigned char are three distinct types.
13719     //
13720     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13721     // char' depending on the current char signedness mode.
13722     if (mismatch)
13723       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13724                                            RequiredType->getPointeeType())) ||
13725           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13726         mismatch = false;
13727   } else
13728     if (IsPointerAttr)
13729       mismatch = !isLayoutCompatible(Context,
13730                                      ArgumentType->getPointeeType(),
13731                                      RequiredType->getPointeeType());
13732     else
13733       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13734 
13735   if (mismatch)
13736     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13737         << ArgumentType << ArgumentKind
13738         << TypeInfo.LayoutCompatible << RequiredType
13739         << ArgumentExpr->getSourceRange()
13740         << TypeTagExpr->getSourceRange();
13741 }
13742 
13743 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13744                                          CharUnits Alignment) {
13745   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13746 }
13747 
13748 void Sema::DiagnoseMisalignedMembers() {
13749   for (MisalignedMember &m : MisalignedMembers) {
13750     const NamedDecl *ND = m.RD;
13751     if (ND->getName().empty()) {
13752       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13753         ND = TD;
13754     }
13755     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
13756         << m.MD << ND << m.E->getSourceRange();
13757   }
13758   MisalignedMembers.clear();
13759 }
13760 
13761 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13762   E = E->IgnoreParens();
13763   if (!T->isPointerType() && !T->isIntegerType())
13764     return;
13765   if (isa<UnaryOperator>(E) &&
13766       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13767     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13768     if (isa<MemberExpr>(Op)) {
13769       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13770                           MisalignedMember(Op));
13771       if (MA != MisalignedMembers.end() &&
13772           (T->isIntegerType() ||
13773            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13774                                    Context.getTypeAlignInChars(
13775                                        T->getPointeeType()) <= MA->Alignment))))
13776         MisalignedMembers.erase(MA);
13777     }
13778   }
13779 }
13780 
13781 void Sema::RefersToMemberWithReducedAlignment(
13782     Expr *E,
13783     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13784         Action) {
13785   const auto *ME = dyn_cast<MemberExpr>(E);
13786   if (!ME)
13787     return;
13788 
13789   // No need to check expressions with an __unaligned-qualified type.
13790   if (E->getType().getQualifiers().hasUnaligned())
13791     return;
13792 
13793   // For a chain of MemberExpr like "a.b.c.d" this list
13794   // will keep FieldDecl's like [d, c, b].
13795   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13796   const MemberExpr *TopME = nullptr;
13797   bool AnyIsPacked = false;
13798   do {
13799     QualType BaseType = ME->getBase()->getType();
13800     if (ME->isArrow())
13801       BaseType = BaseType->getPointeeType();
13802     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13803     if (RD->isInvalidDecl())
13804       return;
13805 
13806     ValueDecl *MD = ME->getMemberDecl();
13807     auto *FD = dyn_cast<FieldDecl>(MD);
13808     // We do not care about non-data members.
13809     if (!FD || FD->isInvalidDecl())
13810       return;
13811 
13812     AnyIsPacked =
13813         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13814     ReverseMemberChain.push_back(FD);
13815 
13816     TopME = ME;
13817     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13818   } while (ME);
13819   assert(TopME && "We did not compute a topmost MemberExpr!");
13820 
13821   // Not the scope of this diagnostic.
13822   if (!AnyIsPacked)
13823     return;
13824 
13825   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13826   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13827   // TODO: The innermost base of the member expression may be too complicated.
13828   // For now, just disregard these cases. This is left for future
13829   // improvement.
13830   if (!DRE && !isa<CXXThisExpr>(TopBase))
13831       return;
13832 
13833   // Alignment expected by the whole expression.
13834   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13835 
13836   // No need to do anything else with this case.
13837   if (ExpectedAlignment.isOne())
13838     return;
13839 
13840   // Synthesize offset of the whole access.
13841   CharUnits Offset;
13842   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13843        I++) {
13844     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13845   }
13846 
13847   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13848   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13849       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13850 
13851   // The base expression of the innermost MemberExpr may give
13852   // stronger guarantees than the class containing the member.
13853   if (DRE && !TopME->isArrow()) {
13854     const ValueDecl *VD = DRE->getDecl();
13855     if (!VD->getType()->isReferenceType())
13856       CompleteObjectAlignment =
13857           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13858   }
13859 
13860   // Check if the synthesized offset fulfills the alignment.
13861   if (Offset % ExpectedAlignment != 0 ||
13862       // It may fulfill the offset it but the effective alignment may still be
13863       // lower than the expected expression alignment.
13864       CompleteObjectAlignment < ExpectedAlignment) {
13865     // If this happens, we want to determine a sensible culprit of this.
13866     // Intuitively, watching the chain of member expressions from right to
13867     // left, we start with the required alignment (as required by the field
13868     // type) but some packed attribute in that chain has reduced the alignment.
13869     // It may happen that another packed structure increases it again. But if
13870     // we are here such increase has not been enough. So pointing the first
13871     // FieldDecl that either is packed or else its RecordDecl is,
13872     // seems reasonable.
13873     FieldDecl *FD = nullptr;
13874     CharUnits Alignment;
13875     for (FieldDecl *FDI : ReverseMemberChain) {
13876       if (FDI->hasAttr<PackedAttr>() ||
13877           FDI->getParent()->hasAttr<PackedAttr>()) {
13878         FD = FDI;
13879         Alignment = std::min(
13880             Context.getTypeAlignInChars(FD->getType()),
13881             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13882         break;
13883       }
13884     }
13885     assert(FD && "We did not find a packed FieldDecl!");
13886     Action(E, FD->getParent(), FD, Alignment);
13887   }
13888 }
13889 
13890 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13891   using namespace std::placeholders;
13892 
13893   RefersToMemberWithReducedAlignment(
13894       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13895                      _2, _3, _4));
13896 }
13897