1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Analysis/Analyses/FormatString.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getLocEnd(), 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)->getLocStart(),
121                     call->getArg(argCount - 1)->getLocEnd());
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->getLocStart(), 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->getLocStart(), 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->getLocEnd(), 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->getLocStart(), 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->getLocStart());
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     Expr *Arg = TheCall->getArg(I);
201     QualType Ty = Arg->getType();
202     if (!Ty->isIntegerType()) {
203       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
204           << Ty << Arg->getSourceRange();
205       return true;
206     }
207   }
208 
209   // Third argument should be a pointer to a non-const integer.
210   // IRGen correctly handles volatile, restrict, and address spaces, and
211   // the other qualifiers aren't possible.
212   {
213     Expr *Arg = TheCall->getArg(2);
214     QualType Ty = Arg->getType();
215     const auto *PtrTy = Ty->getAs<PointerType>();
216     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
217           !PtrTy->getPointeeType().isConstQualified())) {
218       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
219           << Ty << Arg->getSourceRange();
220       return true;
221     }
222   }
223 
224   return false;
225 }
226 
227 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
228 		                  CallExpr *TheCall, unsigned SizeIdx,
229                                   unsigned DstSizeIdx) {
230   if (TheCall->getNumArgs() <= SizeIdx ||
231       TheCall->getNumArgs() <= DstSizeIdx)
232     return;
233 
234   const Expr *SizeArg = TheCall->getArg(SizeIdx);
235   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
236 
237   llvm::APSInt Size, DstSize;
238 
239   // find out if both sizes are known at compile time
240   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
241       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
242     return;
243 
244   if (Size.ule(DstSize))
245     return;
246 
247   // confirmed overflow so generate the diagnostic.
248   IdentifierInfo *FnName = FDecl->getIdentifier();
249   SourceLocation SL = TheCall->getLocStart();
250   SourceRange SR = TheCall->getSourceRange();
251 
252   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
253 }
254 
255 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
256   if (checkArgCount(S, BuiltinCall, 2))
257     return true;
258 
259   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
260   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
261   Expr *Call = BuiltinCall->getArg(0);
262   Expr *Chain = BuiltinCall->getArg(1);
263 
264   if (Call->getStmtClass() != Stmt::CallExprClass) {
265     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
266         << Call->getSourceRange();
267     return true;
268   }
269 
270   auto CE = cast<CallExpr>(Call);
271   if (CE->getCallee()->getType()->isBlockPointerType()) {
272     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
273         << Call->getSourceRange();
274     return true;
275   }
276 
277   const Decl *TargetDecl = CE->getCalleeDecl();
278   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
279     if (FD->getBuiltinID()) {
280       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
281           << Call->getSourceRange();
282       return true;
283     }
284 
285   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
286     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
287         << Call->getSourceRange();
288     return true;
289   }
290 
291   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
292   if (ChainResult.isInvalid())
293     return true;
294   if (!ChainResult.get()->getType()->isPointerType()) {
295     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
296         << Chain->getSourceRange();
297     return true;
298   }
299 
300   QualType ReturnTy = CE->getCallReturnType(S.Context);
301   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
302   QualType BuiltinTy = S.Context.getFunctionType(
303       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
304   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
305 
306   Builtin =
307       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
308 
309   BuiltinCall->setType(CE->getType());
310   BuiltinCall->setValueKind(CE->getValueKind());
311   BuiltinCall->setObjectKind(CE->getObjectKind());
312   BuiltinCall->setCallee(Builtin);
313   BuiltinCall->setArg(1, ChainResult.get());
314 
315   return false;
316 }
317 
318 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
319                                      Scope::ScopeFlags NeededScopeFlags,
320                                      unsigned DiagID) {
321   // Scopes aren't available during instantiation. Fortunately, builtin
322   // functions cannot be template args so they cannot be formed through template
323   // instantiation. Therefore checking once during the parse is sufficient.
324   if (SemaRef.inTemplateInstantiation())
325     return false;
326 
327   Scope *S = SemaRef.getCurScope();
328   while (S && !S->isSEHExceptScope())
329     S = S->getParent();
330   if (!S || !(S->getFlags() & NeededScopeFlags)) {
331     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
332     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
333         << DRE->getDecl()->getIdentifier();
334     return true;
335   }
336 
337   return false;
338 }
339 
340 static inline bool isBlockPointer(Expr *Arg) {
341   return Arg->getType()->isBlockPointerType();
342 }
343 
344 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
345 /// void*, which is a requirement of device side enqueue.
346 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
347   const BlockPointerType *BPT =
348       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
349   ArrayRef<QualType> Params =
350       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
351   unsigned ArgCounter = 0;
352   bool IllegalParams = false;
353   // Iterate through the block parameters until either one is found that is not
354   // a local void*, or the block is valid.
355   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
356        I != E; ++I, ++ArgCounter) {
357     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
358         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
359             LangAS::opencl_local) {
360       // Get the location of the error. If a block literal has been passed
361       // (BlockExpr) then we can point straight to the offending argument,
362       // else we just point to the variable reference.
363       SourceLocation ErrorLoc;
364       if (isa<BlockExpr>(BlockArg)) {
365         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
366         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
367       } else if (isa<DeclRefExpr>(BlockArg)) {
368         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
369       }
370       S.Diag(ErrorLoc,
371              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
372       IllegalParams = true;
373     }
374   }
375 
376   return IllegalParams;
377 }
378 
379 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
380   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
381     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
382           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
383     return true;
384   }
385   return false;
386 }
387 
388 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
389   if (checkArgCount(S, TheCall, 2))
390     return true;
391 
392   if (checkOpenCLSubgroupExt(S, TheCall))
393     return true;
394 
395   // First argument is an ndrange_t type.
396   Expr *NDRangeArg = TheCall->getArg(0);
397   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
398     S.Diag(NDRangeArg->getLocStart(),
399            diag::err_opencl_builtin_expected_type)
400         << TheCall->getDirectCallee() << "'ndrange_t'";
401     return true;
402   }
403 
404   Expr *BlockArg = TheCall->getArg(1);
405   if (!isBlockPointer(BlockArg)) {
406     S.Diag(BlockArg->getLocStart(),
407            diag::err_opencl_builtin_expected_type)
408         << TheCall->getDirectCallee() << "block";
409     return true;
410   }
411   return checkOpenCLBlockArgs(S, BlockArg);
412 }
413 
414 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
415 /// get_kernel_work_group_size
416 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
417 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
418   if (checkArgCount(S, TheCall, 1))
419     return true;
420 
421   Expr *BlockArg = TheCall->getArg(0);
422   if (!isBlockPointer(BlockArg)) {
423     S.Diag(BlockArg->getLocStart(),
424            diag::err_opencl_builtin_expected_type)
425         << TheCall->getDirectCallee() << "block";
426     return true;
427   }
428   return checkOpenCLBlockArgs(S, BlockArg);
429 }
430 
431 /// Diagnose integer type and any valid implicit conversion to it.
432 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
433                                       const QualType &IntType);
434 
435 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
436                                             unsigned Start, unsigned End) {
437   bool IllegalParams = false;
438   for (unsigned I = Start; I <= End; ++I)
439     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
440                                               S.Context.getSizeType());
441   return IllegalParams;
442 }
443 
444 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
445 /// 'local void*' parameter of passed block.
446 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
447                                            Expr *BlockArg,
448                                            unsigned NumNonVarArgs) {
449   const BlockPointerType *BPT =
450       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
451   unsigned NumBlockParams =
452       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
453   unsigned TotalNumArgs = TheCall->getNumArgs();
454 
455   // For each argument passed to the block, a corresponding uint needs to
456   // be passed to describe the size of the local memory.
457   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
458     S.Diag(TheCall->getLocStart(),
459            diag::err_opencl_enqueue_kernel_local_size_args);
460     return true;
461   }
462 
463   // Check that the sizes of the local memory are specified by integers.
464   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
465                                          TotalNumArgs - 1);
466 }
467 
468 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
469 /// overload formats specified in Table 6.13.17.1.
470 /// int enqueue_kernel(queue_t queue,
471 ///                    kernel_enqueue_flags_t flags,
472 ///                    const ndrange_t ndrange,
473 ///                    void (^block)(void))
474 /// int enqueue_kernel(queue_t queue,
475 ///                    kernel_enqueue_flags_t flags,
476 ///                    const ndrange_t ndrange,
477 ///                    uint num_events_in_wait_list,
478 ///                    clk_event_t *event_wait_list,
479 ///                    clk_event_t *event_ret,
480 ///                    void (^block)(void))
481 /// int enqueue_kernel(queue_t queue,
482 ///                    kernel_enqueue_flags_t flags,
483 ///                    const ndrange_t ndrange,
484 ///                    void (^block)(local void*, ...),
485 ///                    uint size0, ...)
486 /// int enqueue_kernel(queue_t queue,
487 ///                    kernel_enqueue_flags_t flags,
488 ///                    const ndrange_t ndrange,
489 ///                    uint num_events_in_wait_list,
490 ///                    clk_event_t *event_wait_list,
491 ///                    clk_event_t *event_ret,
492 ///                    void (^block)(local void*, ...),
493 ///                    uint size0, ...)
494 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
495   unsigned NumArgs = TheCall->getNumArgs();
496 
497   if (NumArgs < 4) {
498     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
499     return true;
500   }
501 
502   Expr *Arg0 = TheCall->getArg(0);
503   Expr *Arg1 = TheCall->getArg(1);
504   Expr *Arg2 = TheCall->getArg(2);
505   Expr *Arg3 = TheCall->getArg(3);
506 
507   // First argument always needs to be a queue_t type.
508   if (!Arg0->getType()->isQueueT()) {
509     S.Diag(TheCall->getArg(0)->getLocStart(),
510            diag::err_opencl_builtin_expected_type)
511         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
512     return true;
513   }
514 
515   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
516   if (!Arg1->getType()->isIntegerType()) {
517     S.Diag(TheCall->getArg(1)->getLocStart(),
518            diag::err_opencl_builtin_expected_type)
519         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
520     return true;
521   }
522 
523   // Third argument is always an ndrange_t type.
524   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
525     S.Diag(TheCall->getArg(2)->getLocStart(),
526            diag::err_opencl_builtin_expected_type)
527         << TheCall->getDirectCallee() << "'ndrange_t'";
528     return true;
529   }
530 
531   // With four arguments, there is only one form that the function could be
532   // called in: no events and no variable arguments.
533   if (NumArgs == 4) {
534     // check that the last argument is the right block type.
535     if (!isBlockPointer(Arg3)) {
536       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
537           << TheCall->getDirectCallee() << "block";
538       return true;
539     }
540     // we have a block type, check the prototype
541     const BlockPointerType *BPT =
542         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
543     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
544       S.Diag(Arg3->getLocStart(),
545              diag::err_opencl_enqueue_kernel_blocks_no_args);
546       return true;
547     }
548     return false;
549   }
550   // we can have block + varargs.
551   if (isBlockPointer(Arg3))
552     return (checkOpenCLBlockArgs(S, Arg3) ||
553             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
554   // last two cases with either exactly 7 args or 7 args and varargs.
555   if (NumArgs >= 7) {
556     // check common block argument.
557     Expr *Arg6 = TheCall->getArg(6);
558     if (!isBlockPointer(Arg6)) {
559       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
560           << TheCall->getDirectCallee() << "block";
561       return true;
562     }
563     if (checkOpenCLBlockArgs(S, Arg6))
564       return true;
565 
566     // Forth argument has to be any integer type.
567     if (!Arg3->getType()->isIntegerType()) {
568       S.Diag(TheCall->getArg(3)->getLocStart(),
569              diag::err_opencl_builtin_expected_type)
570           << TheCall->getDirectCallee() << "integer";
571       return true;
572     }
573     // check remaining common arguments.
574     Expr *Arg4 = TheCall->getArg(4);
575     Expr *Arg5 = TheCall->getArg(5);
576 
577     // Fifth argument is always passed as a pointer to clk_event_t.
578     if (!Arg4->isNullPointerConstant(S.Context,
579                                      Expr::NPC_ValueDependentIsNotNull) &&
580         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
581       S.Diag(TheCall->getArg(4)->getLocStart(),
582              diag::err_opencl_builtin_expected_type)
583           << TheCall->getDirectCallee()
584           << S.Context.getPointerType(S.Context.OCLClkEventTy);
585       return true;
586     }
587 
588     // Sixth argument is always passed as a pointer to clk_event_t.
589     if (!Arg5->isNullPointerConstant(S.Context,
590                                      Expr::NPC_ValueDependentIsNotNull) &&
591         !(Arg5->getType()->isPointerType() &&
592           Arg5->getType()->getPointeeType()->isClkEventT())) {
593       S.Diag(TheCall->getArg(5)->getLocStart(),
594              diag::err_opencl_builtin_expected_type)
595           << TheCall->getDirectCallee()
596           << S.Context.getPointerType(S.Context.OCLClkEventTy);
597       return true;
598     }
599 
600     if (NumArgs == 7)
601       return false;
602 
603     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
604   }
605 
606   // None of the specific case has been detected, give generic error
607   S.Diag(TheCall->getLocStart(),
608          diag::err_opencl_enqueue_kernel_incorrect_args);
609   return true;
610 }
611 
612 /// Returns OpenCL access qual.
613 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
614     return D->getAttr<OpenCLAccessAttr>();
615 }
616 
617 /// Returns true if pipe element type is different from the pointer.
618 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
619   const Expr *Arg0 = Call->getArg(0);
620   // First argument type should always be pipe.
621   if (!Arg0->getType()->isPipeType()) {
622     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
623         << Call->getDirectCallee() << Arg0->getSourceRange();
624     return true;
625   }
626   OpenCLAccessAttr *AccessQual =
627       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
628   // Validates the access qualifier is compatible with the call.
629   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
630   // read_only and write_only, and assumed to be read_only if no qualifier is
631   // specified.
632   switch (Call->getDirectCallee()->getBuiltinID()) {
633   case Builtin::BIread_pipe:
634   case Builtin::BIreserve_read_pipe:
635   case Builtin::BIcommit_read_pipe:
636   case Builtin::BIwork_group_reserve_read_pipe:
637   case Builtin::BIsub_group_reserve_read_pipe:
638   case Builtin::BIwork_group_commit_read_pipe:
639   case Builtin::BIsub_group_commit_read_pipe:
640     if (!(!AccessQual || AccessQual->isReadOnly())) {
641       S.Diag(Arg0->getLocStart(),
642              diag::err_opencl_builtin_pipe_invalid_access_modifier)
643           << "read_only" << Arg0->getSourceRange();
644       return true;
645     }
646     break;
647   case Builtin::BIwrite_pipe:
648   case Builtin::BIreserve_write_pipe:
649   case Builtin::BIcommit_write_pipe:
650   case Builtin::BIwork_group_reserve_write_pipe:
651   case Builtin::BIsub_group_reserve_write_pipe:
652   case Builtin::BIwork_group_commit_write_pipe:
653   case Builtin::BIsub_group_commit_write_pipe:
654     if (!(AccessQual && AccessQual->isWriteOnly())) {
655       S.Diag(Arg0->getLocStart(),
656              diag::err_opencl_builtin_pipe_invalid_access_modifier)
657           << "write_only" << Arg0->getSourceRange();
658       return true;
659     }
660     break;
661   default:
662     break;
663   }
664   return false;
665 }
666 
667 /// Returns true if pipe element type is different from the pointer.
668 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
669   const Expr *Arg0 = Call->getArg(0);
670   const Expr *ArgIdx = Call->getArg(Idx);
671   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
672   const QualType EltTy = PipeTy->getElementType();
673   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
674   // The Idx argument should be a pointer and the type of the pointer and
675   // the type of pipe element should also be the same.
676   if (!ArgTy ||
677       !S.Context.hasSameType(
678           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
679     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
680         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
681         << ArgIdx->getType() << ArgIdx->getSourceRange();
682     return true;
683   }
684   return false;
685 }
686 
687 // Performs semantic analysis for the read/write_pipe call.
688 // \param S Reference to the semantic analyzer.
689 // \param Call A pointer to the builtin call.
690 // \return True if a semantic error has been found, false otherwise.
691 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
692   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
693   // functions have two forms.
694   switch (Call->getNumArgs()) {
695   case 2:
696     if (checkOpenCLPipeArg(S, Call))
697       return true;
698     // The call with 2 arguments should be
699     // read/write_pipe(pipe T, T*).
700     // Check packet type T.
701     if (checkOpenCLPipePacketType(S, Call, 1))
702       return true;
703     break;
704 
705   case 4: {
706     if (checkOpenCLPipeArg(S, Call))
707       return true;
708     // The call with 4 arguments should be
709     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
710     // Check reserve_id_t.
711     if (!Call->getArg(1)->getType()->isReserveIDT()) {
712       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
713           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
714           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
715       return true;
716     }
717 
718     // Check the index.
719     const Expr *Arg2 = Call->getArg(2);
720     if (!Arg2->getType()->isIntegerType() &&
721         !Arg2->getType()->isUnsignedIntegerType()) {
722       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
723           << Call->getDirectCallee() << S.Context.UnsignedIntTy
724           << Arg2->getType() << Arg2->getSourceRange();
725       return true;
726     }
727 
728     // Check packet type T.
729     if (checkOpenCLPipePacketType(S, Call, 3))
730       return true;
731   } break;
732   default:
733     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
734         << Call->getDirectCallee() << Call->getSourceRange();
735     return true;
736   }
737 
738   return false;
739 }
740 
741 // Performs a semantic analysis on the {work_group_/sub_group_
742 //        /_}reserve_{read/write}_pipe
743 // \param S Reference to the semantic analyzer.
744 // \param Call The call to the builtin function to be analyzed.
745 // \return True if a semantic error was found, false otherwise.
746 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
747   if (checkArgCount(S, Call, 2))
748     return true;
749 
750   if (checkOpenCLPipeArg(S, Call))
751     return true;
752 
753   // Check the reserve size.
754   if (!Call->getArg(1)->getType()->isIntegerType() &&
755       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
756     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
757         << Call->getDirectCallee() << S.Context.UnsignedIntTy
758         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
759     return true;
760   }
761 
762   // Since return type of reserve_read/write_pipe built-in function is
763   // reserve_id_t, which is not defined in the builtin def file , we used int
764   // as return type and need to override the return type of these functions.
765   Call->setType(S.Context.OCLReserveIDTy);
766 
767   return false;
768 }
769 
770 // Performs a semantic analysis on {work_group_/sub_group_
771 //        /_}commit_{read/write}_pipe
772 // \param S Reference to the semantic analyzer.
773 // \param Call The call to the builtin function to be analyzed.
774 // \return True if a semantic error was found, false otherwise.
775 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
776   if (checkArgCount(S, Call, 2))
777     return true;
778 
779   if (checkOpenCLPipeArg(S, Call))
780     return true;
781 
782   // Check reserve_id_t.
783   if (!Call->getArg(1)->getType()->isReserveIDT()) {
784     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
785         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
786         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
787     return true;
788   }
789 
790   return false;
791 }
792 
793 // Performs a semantic analysis on the call to built-in Pipe
794 //        Query Functions.
795 // \param S Reference to the semantic analyzer.
796 // \param Call The call to the builtin function to be analyzed.
797 // \return True if a semantic error was found, false otherwise.
798 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
799   if (checkArgCount(S, Call, 1))
800     return true;
801 
802   if (!Call->getArg(0)->getType()->isPipeType()) {
803     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
804         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
805     return true;
806   }
807 
808   return false;
809 }
810 
811 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
812 // Performs semantic analysis for the to_global/local/private call.
813 // \param S Reference to the semantic analyzer.
814 // \param BuiltinID ID of the builtin function.
815 // \param Call A pointer to the builtin call.
816 // \return True if a semantic error has been found, false otherwise.
817 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
818                                     CallExpr *Call) {
819   if (Call->getNumArgs() != 1) {
820     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
821         << Call->getDirectCallee() << Call->getSourceRange();
822     return true;
823   }
824 
825   auto RT = Call->getArg(0)->getType();
826   if (!RT->isPointerType() || RT->getPointeeType()
827       .getAddressSpace() == LangAS::opencl_constant) {
828     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
829         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
830     return true;
831   }
832 
833   RT = RT->getPointeeType();
834   auto Qual = RT.getQualifiers();
835   switch (BuiltinID) {
836   case Builtin::BIto_global:
837     Qual.setAddressSpace(LangAS::opencl_global);
838     break;
839   case Builtin::BIto_local:
840     Qual.setAddressSpace(LangAS::opencl_local);
841     break;
842   case Builtin::BIto_private:
843     Qual.setAddressSpace(LangAS::opencl_private);
844     break;
845   default:
846     llvm_unreachable("Invalid builtin function");
847   }
848   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
849       RT.getUnqualifiedType(), Qual)));
850 
851   return false;
852 }
853 
854 ExprResult
855 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
856                                CallExpr *TheCall) {
857   ExprResult TheCallResult(TheCall);
858 
859   // Find out if any arguments are required to be integer constant expressions.
860   unsigned ICEArguments = 0;
861   ASTContext::GetBuiltinTypeError Error;
862   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
863   if (Error != ASTContext::GE_None)
864     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
865 
866   // If any arguments are required to be ICE's, check and diagnose.
867   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
868     // Skip arguments not required to be ICE's.
869     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
870 
871     llvm::APSInt Result;
872     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
873       return true;
874     ICEArguments &= ~(1 << ArgNo);
875   }
876 
877   switch (BuiltinID) {
878   case Builtin::BI__builtin___CFStringMakeConstantString:
879     assert(TheCall->getNumArgs() == 1 &&
880            "Wrong # arguments to builtin CFStringMakeConstantString");
881     if (CheckObjCString(TheCall->getArg(0)))
882       return ExprError();
883     break;
884   case Builtin::BI__builtin_ms_va_start:
885   case Builtin::BI__builtin_stdarg_start:
886   case Builtin::BI__builtin_va_start:
887     if (SemaBuiltinVAStart(BuiltinID, TheCall))
888       return ExprError();
889     break;
890   case Builtin::BI__va_start: {
891     switch (Context.getTargetInfo().getTriple().getArch()) {
892     case llvm::Triple::arm:
893     case llvm::Triple::thumb:
894       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
895         return ExprError();
896       break;
897     default:
898       if (SemaBuiltinVAStart(BuiltinID, TheCall))
899         return ExprError();
900       break;
901     }
902     break;
903   }
904   case Builtin::BI__builtin_isgreater:
905   case Builtin::BI__builtin_isgreaterequal:
906   case Builtin::BI__builtin_isless:
907   case Builtin::BI__builtin_islessequal:
908   case Builtin::BI__builtin_islessgreater:
909   case Builtin::BI__builtin_isunordered:
910     if (SemaBuiltinUnorderedCompare(TheCall))
911       return ExprError();
912     break;
913   case Builtin::BI__builtin_fpclassify:
914     if (SemaBuiltinFPClassification(TheCall, 6))
915       return ExprError();
916     break;
917   case Builtin::BI__builtin_isfinite:
918   case Builtin::BI__builtin_isinf:
919   case Builtin::BI__builtin_isinf_sign:
920   case Builtin::BI__builtin_isnan:
921   case Builtin::BI__builtin_isnormal:
922     if (SemaBuiltinFPClassification(TheCall, 1))
923       return ExprError();
924     break;
925   case Builtin::BI__builtin_shufflevector:
926     return SemaBuiltinShuffleVector(TheCall);
927     // TheCall will be freed by the smart pointer here, but that's fine, since
928     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
929   case Builtin::BI__builtin_prefetch:
930     if (SemaBuiltinPrefetch(TheCall))
931       return ExprError();
932     break;
933   case Builtin::BI__builtin_alloca_with_align:
934     if (SemaBuiltinAllocaWithAlign(TheCall))
935       return ExprError();
936     break;
937   case Builtin::BI__assume:
938   case Builtin::BI__builtin_assume:
939     if (SemaBuiltinAssume(TheCall))
940       return ExprError();
941     break;
942   case Builtin::BI__builtin_assume_aligned:
943     if (SemaBuiltinAssumeAligned(TheCall))
944       return ExprError();
945     break;
946   case Builtin::BI__builtin_object_size:
947     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
948       return ExprError();
949     break;
950   case Builtin::BI__builtin_longjmp:
951     if (SemaBuiltinLongjmp(TheCall))
952       return ExprError();
953     break;
954   case Builtin::BI__builtin_setjmp:
955     if (SemaBuiltinSetjmp(TheCall))
956       return ExprError();
957     break;
958   case Builtin::BI_setjmp:
959   case Builtin::BI_setjmpex:
960     if (checkArgCount(*this, TheCall, 1))
961       return true;
962     break;
963   case Builtin::BI__builtin_classify_type:
964     if (checkArgCount(*this, TheCall, 1)) return true;
965     TheCall->setType(Context.IntTy);
966     break;
967   case Builtin::BI__builtin_constant_p:
968     if (checkArgCount(*this, TheCall, 1)) return true;
969     TheCall->setType(Context.IntTy);
970     break;
971   case Builtin::BI__sync_fetch_and_add:
972   case Builtin::BI__sync_fetch_and_add_1:
973   case Builtin::BI__sync_fetch_and_add_2:
974   case Builtin::BI__sync_fetch_and_add_4:
975   case Builtin::BI__sync_fetch_and_add_8:
976   case Builtin::BI__sync_fetch_and_add_16:
977   case Builtin::BI__sync_fetch_and_sub:
978   case Builtin::BI__sync_fetch_and_sub_1:
979   case Builtin::BI__sync_fetch_and_sub_2:
980   case Builtin::BI__sync_fetch_and_sub_4:
981   case Builtin::BI__sync_fetch_and_sub_8:
982   case Builtin::BI__sync_fetch_and_sub_16:
983   case Builtin::BI__sync_fetch_and_or:
984   case Builtin::BI__sync_fetch_and_or_1:
985   case Builtin::BI__sync_fetch_and_or_2:
986   case Builtin::BI__sync_fetch_and_or_4:
987   case Builtin::BI__sync_fetch_and_or_8:
988   case Builtin::BI__sync_fetch_and_or_16:
989   case Builtin::BI__sync_fetch_and_and:
990   case Builtin::BI__sync_fetch_and_and_1:
991   case Builtin::BI__sync_fetch_and_and_2:
992   case Builtin::BI__sync_fetch_and_and_4:
993   case Builtin::BI__sync_fetch_and_and_8:
994   case Builtin::BI__sync_fetch_and_and_16:
995   case Builtin::BI__sync_fetch_and_xor:
996   case Builtin::BI__sync_fetch_and_xor_1:
997   case Builtin::BI__sync_fetch_and_xor_2:
998   case Builtin::BI__sync_fetch_and_xor_4:
999   case Builtin::BI__sync_fetch_and_xor_8:
1000   case Builtin::BI__sync_fetch_and_xor_16:
1001   case Builtin::BI__sync_fetch_and_nand:
1002   case Builtin::BI__sync_fetch_and_nand_1:
1003   case Builtin::BI__sync_fetch_and_nand_2:
1004   case Builtin::BI__sync_fetch_and_nand_4:
1005   case Builtin::BI__sync_fetch_and_nand_8:
1006   case Builtin::BI__sync_fetch_and_nand_16:
1007   case Builtin::BI__sync_add_and_fetch:
1008   case Builtin::BI__sync_add_and_fetch_1:
1009   case Builtin::BI__sync_add_and_fetch_2:
1010   case Builtin::BI__sync_add_and_fetch_4:
1011   case Builtin::BI__sync_add_and_fetch_8:
1012   case Builtin::BI__sync_add_and_fetch_16:
1013   case Builtin::BI__sync_sub_and_fetch:
1014   case Builtin::BI__sync_sub_and_fetch_1:
1015   case Builtin::BI__sync_sub_and_fetch_2:
1016   case Builtin::BI__sync_sub_and_fetch_4:
1017   case Builtin::BI__sync_sub_and_fetch_8:
1018   case Builtin::BI__sync_sub_and_fetch_16:
1019   case Builtin::BI__sync_and_and_fetch:
1020   case Builtin::BI__sync_and_and_fetch_1:
1021   case Builtin::BI__sync_and_and_fetch_2:
1022   case Builtin::BI__sync_and_and_fetch_4:
1023   case Builtin::BI__sync_and_and_fetch_8:
1024   case Builtin::BI__sync_and_and_fetch_16:
1025   case Builtin::BI__sync_or_and_fetch:
1026   case Builtin::BI__sync_or_and_fetch_1:
1027   case Builtin::BI__sync_or_and_fetch_2:
1028   case Builtin::BI__sync_or_and_fetch_4:
1029   case Builtin::BI__sync_or_and_fetch_8:
1030   case Builtin::BI__sync_or_and_fetch_16:
1031   case Builtin::BI__sync_xor_and_fetch:
1032   case Builtin::BI__sync_xor_and_fetch_1:
1033   case Builtin::BI__sync_xor_and_fetch_2:
1034   case Builtin::BI__sync_xor_and_fetch_4:
1035   case Builtin::BI__sync_xor_and_fetch_8:
1036   case Builtin::BI__sync_xor_and_fetch_16:
1037   case Builtin::BI__sync_nand_and_fetch:
1038   case Builtin::BI__sync_nand_and_fetch_1:
1039   case Builtin::BI__sync_nand_and_fetch_2:
1040   case Builtin::BI__sync_nand_and_fetch_4:
1041   case Builtin::BI__sync_nand_and_fetch_8:
1042   case Builtin::BI__sync_nand_and_fetch_16:
1043   case Builtin::BI__sync_val_compare_and_swap:
1044   case Builtin::BI__sync_val_compare_and_swap_1:
1045   case Builtin::BI__sync_val_compare_and_swap_2:
1046   case Builtin::BI__sync_val_compare_and_swap_4:
1047   case Builtin::BI__sync_val_compare_and_swap_8:
1048   case Builtin::BI__sync_val_compare_and_swap_16:
1049   case Builtin::BI__sync_bool_compare_and_swap:
1050   case Builtin::BI__sync_bool_compare_and_swap_1:
1051   case Builtin::BI__sync_bool_compare_and_swap_2:
1052   case Builtin::BI__sync_bool_compare_and_swap_4:
1053   case Builtin::BI__sync_bool_compare_and_swap_8:
1054   case Builtin::BI__sync_bool_compare_and_swap_16:
1055   case Builtin::BI__sync_lock_test_and_set:
1056   case Builtin::BI__sync_lock_test_and_set_1:
1057   case Builtin::BI__sync_lock_test_and_set_2:
1058   case Builtin::BI__sync_lock_test_and_set_4:
1059   case Builtin::BI__sync_lock_test_and_set_8:
1060   case Builtin::BI__sync_lock_test_and_set_16:
1061   case Builtin::BI__sync_lock_release:
1062   case Builtin::BI__sync_lock_release_1:
1063   case Builtin::BI__sync_lock_release_2:
1064   case Builtin::BI__sync_lock_release_4:
1065   case Builtin::BI__sync_lock_release_8:
1066   case Builtin::BI__sync_lock_release_16:
1067   case Builtin::BI__sync_swap:
1068   case Builtin::BI__sync_swap_1:
1069   case Builtin::BI__sync_swap_2:
1070   case Builtin::BI__sync_swap_4:
1071   case Builtin::BI__sync_swap_8:
1072   case Builtin::BI__sync_swap_16:
1073     return SemaBuiltinAtomicOverloaded(TheCallResult);
1074   case Builtin::BI__builtin_nontemporal_load:
1075   case Builtin::BI__builtin_nontemporal_store:
1076     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1077 #define BUILTIN(ID, TYPE, ATTRS)
1078 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1079   case Builtin::BI##ID: \
1080     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1081 #include "clang/Basic/Builtins.def"
1082   case Builtin::BI__annotation:
1083     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1084       return ExprError();
1085     break;
1086   case Builtin::BI__builtin_annotation:
1087     if (SemaBuiltinAnnotation(*this, TheCall))
1088       return ExprError();
1089     break;
1090   case Builtin::BI__builtin_addressof:
1091     if (SemaBuiltinAddressof(*this, TheCall))
1092       return ExprError();
1093     break;
1094   case Builtin::BI__builtin_add_overflow:
1095   case Builtin::BI__builtin_sub_overflow:
1096   case Builtin::BI__builtin_mul_overflow:
1097     if (SemaBuiltinOverflow(*this, TheCall))
1098       return ExprError();
1099     break;
1100   case Builtin::BI__builtin_operator_new:
1101   case Builtin::BI__builtin_operator_delete: {
1102     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1103     ExprResult Res =
1104         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1105     if (Res.isInvalid())
1106       CorrectDelayedTyposInExpr(TheCallResult.get());
1107     return Res;
1108   }
1109   case Builtin::BI__builtin_dump_struct: {
1110     // We first want to ensure we are called with 2 arguments
1111     if (checkArgCount(*this, TheCall, 2))
1112       return ExprError();
1113     // Ensure that the first argument is of type 'struct XX *'
1114     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1115     const QualType PtrArgType = PtrArg->getType();
1116     if (!PtrArgType->isPointerType() ||
1117         !PtrArgType->getPointeeType()->isRecordType()) {
1118       Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1119           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1120           << "structure pointer";
1121       return ExprError();
1122     }
1123 
1124     // Ensure that the second argument is of type 'FunctionType'
1125     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1126     const QualType FnPtrArgType = FnPtrArg->getType();
1127     if (!FnPtrArgType->isPointerType()) {
1128       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1129           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1130           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1131       return ExprError();
1132     }
1133 
1134     const auto *FuncType =
1135         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1136 
1137     if (!FuncType) {
1138       Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1139           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1140           << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1141       return ExprError();
1142     }
1143 
1144     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1145       if (!FT->getNumParams()) {
1146         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1147             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1148             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1149         return ExprError();
1150       }
1151       QualType PT = FT->getParamType(0);
1152       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1153           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1154           !PT->getPointeeType().isConstQualified()) {
1155         Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1156             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1157             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1158         return ExprError();
1159       }
1160     }
1161 
1162     TheCall->setType(Context.IntTy);
1163     break;
1164   }
1165 
1166   // check secure string manipulation functions where overflows
1167   // are detectable at compile time
1168   case Builtin::BI__builtin___memcpy_chk:
1169   case Builtin::BI__builtin___memmove_chk:
1170   case Builtin::BI__builtin___memset_chk:
1171   case Builtin::BI__builtin___strlcat_chk:
1172   case Builtin::BI__builtin___strlcpy_chk:
1173   case Builtin::BI__builtin___strncat_chk:
1174   case Builtin::BI__builtin___strncpy_chk:
1175   case Builtin::BI__builtin___stpncpy_chk:
1176     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1177     break;
1178   case Builtin::BI__builtin___memccpy_chk:
1179     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1180     break;
1181   case Builtin::BI__builtin___snprintf_chk:
1182   case Builtin::BI__builtin___vsnprintf_chk:
1183     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1184     break;
1185   case Builtin::BI__builtin_call_with_static_chain:
1186     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1187       return ExprError();
1188     break;
1189   case Builtin::BI__exception_code:
1190   case Builtin::BI_exception_code:
1191     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1192                                  diag::err_seh___except_block))
1193       return ExprError();
1194     break;
1195   case Builtin::BI__exception_info:
1196   case Builtin::BI_exception_info:
1197     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1198                                  diag::err_seh___except_filter))
1199       return ExprError();
1200     break;
1201   case Builtin::BI__GetExceptionInfo:
1202     if (checkArgCount(*this, TheCall, 1))
1203       return ExprError();
1204 
1205     if (CheckCXXThrowOperand(
1206             TheCall->getLocStart(),
1207             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1208             TheCall))
1209       return ExprError();
1210 
1211     TheCall->setType(Context.VoidPtrTy);
1212     break;
1213   // OpenCL v2.0, s6.13.16 - Pipe functions
1214   case Builtin::BIread_pipe:
1215   case Builtin::BIwrite_pipe:
1216     // Since those two functions are declared with var args, we need a semantic
1217     // check for the argument.
1218     if (SemaBuiltinRWPipe(*this, TheCall))
1219       return ExprError();
1220     TheCall->setType(Context.IntTy);
1221     break;
1222   case Builtin::BIreserve_read_pipe:
1223   case Builtin::BIreserve_write_pipe:
1224   case Builtin::BIwork_group_reserve_read_pipe:
1225   case Builtin::BIwork_group_reserve_write_pipe:
1226     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1227       return ExprError();
1228     break;
1229   case Builtin::BIsub_group_reserve_read_pipe:
1230   case Builtin::BIsub_group_reserve_write_pipe:
1231     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1232         SemaBuiltinReserveRWPipe(*this, TheCall))
1233       return ExprError();
1234     break;
1235   case Builtin::BIcommit_read_pipe:
1236   case Builtin::BIcommit_write_pipe:
1237   case Builtin::BIwork_group_commit_read_pipe:
1238   case Builtin::BIwork_group_commit_write_pipe:
1239     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1240       return ExprError();
1241     break;
1242   case Builtin::BIsub_group_commit_read_pipe:
1243   case Builtin::BIsub_group_commit_write_pipe:
1244     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1245         SemaBuiltinCommitRWPipe(*this, TheCall))
1246       return ExprError();
1247     break;
1248   case Builtin::BIget_pipe_num_packets:
1249   case Builtin::BIget_pipe_max_packets:
1250     if (SemaBuiltinPipePackets(*this, TheCall))
1251       return ExprError();
1252     TheCall->setType(Context.UnsignedIntTy);
1253     break;
1254   case Builtin::BIto_global:
1255   case Builtin::BIto_local:
1256   case Builtin::BIto_private:
1257     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1258       return ExprError();
1259     break;
1260   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1261   case Builtin::BIenqueue_kernel:
1262     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1263       return ExprError();
1264     break;
1265   case Builtin::BIget_kernel_work_group_size:
1266   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1267     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1268       return ExprError();
1269     break;
1270   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1271   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1272     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1273       return ExprError();
1274     break;
1275   case Builtin::BI__builtin_os_log_format:
1276   case Builtin::BI__builtin_os_log_format_buffer_size:
1277     if (SemaBuiltinOSLogFormat(TheCall))
1278       return ExprError();
1279     break;
1280   }
1281 
1282   // Since the target specific builtins for each arch overlap, only check those
1283   // of the arch we are compiling for.
1284   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1285     switch (Context.getTargetInfo().getTriple().getArch()) {
1286       case llvm::Triple::arm:
1287       case llvm::Triple::armeb:
1288       case llvm::Triple::thumb:
1289       case llvm::Triple::thumbeb:
1290         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1291           return ExprError();
1292         break;
1293       case llvm::Triple::aarch64:
1294       case llvm::Triple::aarch64_be:
1295         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1296           return ExprError();
1297         break;
1298       case llvm::Triple::hexagon:
1299         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1300           return ExprError();
1301         break;
1302       case llvm::Triple::mips:
1303       case llvm::Triple::mipsel:
1304       case llvm::Triple::mips64:
1305       case llvm::Triple::mips64el:
1306         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1307           return ExprError();
1308         break;
1309       case llvm::Triple::systemz:
1310         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1311           return ExprError();
1312         break;
1313       case llvm::Triple::x86:
1314       case llvm::Triple::x86_64:
1315         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1316           return ExprError();
1317         break;
1318       case llvm::Triple::ppc:
1319       case llvm::Triple::ppc64:
1320       case llvm::Triple::ppc64le:
1321         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1322           return ExprError();
1323         break;
1324       default:
1325         break;
1326     }
1327   }
1328 
1329   return TheCallResult;
1330 }
1331 
1332 // Get the valid immediate range for the specified NEON type code.
1333 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1334   NeonTypeFlags Type(t);
1335   int IsQuad = ForceQuad ? true : Type.isQuad();
1336   switch (Type.getEltType()) {
1337   case NeonTypeFlags::Int8:
1338   case NeonTypeFlags::Poly8:
1339     return shift ? 7 : (8 << IsQuad) - 1;
1340   case NeonTypeFlags::Int16:
1341   case NeonTypeFlags::Poly16:
1342     return shift ? 15 : (4 << IsQuad) - 1;
1343   case NeonTypeFlags::Int32:
1344     return shift ? 31 : (2 << IsQuad) - 1;
1345   case NeonTypeFlags::Int64:
1346   case NeonTypeFlags::Poly64:
1347     return shift ? 63 : (1 << IsQuad) - 1;
1348   case NeonTypeFlags::Poly128:
1349     return shift ? 127 : (1 << IsQuad) - 1;
1350   case NeonTypeFlags::Float16:
1351     assert(!shift && "cannot shift float types!");
1352     return (4 << IsQuad) - 1;
1353   case NeonTypeFlags::Float32:
1354     assert(!shift && "cannot shift float types!");
1355     return (2 << IsQuad) - 1;
1356   case NeonTypeFlags::Float64:
1357     assert(!shift && "cannot shift float types!");
1358     return (1 << IsQuad) - 1;
1359   }
1360   llvm_unreachable("Invalid NeonTypeFlag!");
1361 }
1362 
1363 /// getNeonEltType - Return the QualType corresponding to the elements of
1364 /// the vector type specified by the NeonTypeFlags.  This is used to check
1365 /// the pointer arguments for Neon load/store intrinsics.
1366 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1367                                bool IsPolyUnsigned, bool IsInt64Long) {
1368   switch (Flags.getEltType()) {
1369   case NeonTypeFlags::Int8:
1370     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1371   case NeonTypeFlags::Int16:
1372     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1373   case NeonTypeFlags::Int32:
1374     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1375   case NeonTypeFlags::Int64:
1376     if (IsInt64Long)
1377       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1378     else
1379       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1380                                 : Context.LongLongTy;
1381   case NeonTypeFlags::Poly8:
1382     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1383   case NeonTypeFlags::Poly16:
1384     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1385   case NeonTypeFlags::Poly64:
1386     if (IsInt64Long)
1387       return Context.UnsignedLongTy;
1388     else
1389       return Context.UnsignedLongLongTy;
1390   case NeonTypeFlags::Poly128:
1391     break;
1392   case NeonTypeFlags::Float16:
1393     return Context.HalfTy;
1394   case NeonTypeFlags::Float32:
1395     return Context.FloatTy;
1396   case NeonTypeFlags::Float64:
1397     return Context.DoubleTy;
1398   }
1399   llvm_unreachable("Invalid NeonTypeFlag!");
1400 }
1401 
1402 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1403   llvm::APSInt Result;
1404   uint64_t mask = 0;
1405   unsigned TV = 0;
1406   int PtrArgNum = -1;
1407   bool HasConstPtr = false;
1408   switch (BuiltinID) {
1409 #define GET_NEON_OVERLOAD_CHECK
1410 #include "clang/Basic/arm_neon.inc"
1411 #include "clang/Basic/arm_fp16.inc"
1412 #undef GET_NEON_OVERLOAD_CHECK
1413   }
1414 
1415   // For NEON intrinsics which are overloaded on vector element type, validate
1416   // the immediate which specifies which variant to emit.
1417   unsigned ImmArg = TheCall->getNumArgs()-1;
1418   if (mask) {
1419     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1420       return true;
1421 
1422     TV = Result.getLimitedValue(64);
1423     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1424       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1425         << TheCall->getArg(ImmArg)->getSourceRange();
1426   }
1427 
1428   if (PtrArgNum >= 0) {
1429     // Check that pointer arguments have the specified type.
1430     Expr *Arg = TheCall->getArg(PtrArgNum);
1431     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1432       Arg = ICE->getSubExpr();
1433     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1434     QualType RHSTy = RHS.get()->getType();
1435 
1436     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1437     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1438                           Arch == llvm::Triple::aarch64_be;
1439     bool IsInt64Long =
1440         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1441     QualType EltTy =
1442         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1443     if (HasConstPtr)
1444       EltTy = EltTy.withConst();
1445     QualType LHSTy = Context.getPointerType(EltTy);
1446     AssignConvertType ConvTy;
1447     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1448     if (RHS.isInvalid())
1449       return true;
1450     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1451                                  RHS.get(), AA_Assigning))
1452       return true;
1453   }
1454 
1455   // For NEON intrinsics which take an immediate value as part of the
1456   // instruction, range check them here.
1457   unsigned i = 0, l = 0, u = 0;
1458   switch (BuiltinID) {
1459   default:
1460     return false;
1461 #define GET_NEON_IMMEDIATE_CHECK
1462 #include "clang/Basic/arm_neon.inc"
1463 #include "clang/Basic/arm_fp16.inc"
1464 #undef GET_NEON_IMMEDIATE_CHECK
1465   }
1466 
1467   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1468 }
1469 
1470 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1471                                         unsigned MaxWidth) {
1472   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1473           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1474           BuiltinID == ARM::BI__builtin_arm_strex ||
1475           BuiltinID == ARM::BI__builtin_arm_stlex ||
1476           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1477           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1478           BuiltinID == AArch64::BI__builtin_arm_strex ||
1479           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1480          "unexpected ARM builtin");
1481   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1482                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1483                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1484                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1485 
1486   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1487 
1488   // Ensure that we have the proper number of arguments.
1489   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1490     return true;
1491 
1492   // Inspect the pointer argument of the atomic builtin.  This should always be
1493   // a pointer type, whose element is an integral scalar or pointer type.
1494   // Because it is a pointer type, we don't have to worry about any implicit
1495   // casts here.
1496   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1497   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1498   if (PointerArgRes.isInvalid())
1499     return true;
1500   PointerArg = PointerArgRes.get();
1501 
1502   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1503   if (!pointerType) {
1504     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1505       << PointerArg->getType() << PointerArg->getSourceRange();
1506     return true;
1507   }
1508 
1509   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1510   // task is to insert the appropriate casts into the AST. First work out just
1511   // what the appropriate type is.
1512   QualType ValType = pointerType->getPointeeType();
1513   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1514   if (IsLdrex)
1515     AddrType.addConst();
1516 
1517   // Issue a warning if the cast is dodgy.
1518   CastKind CastNeeded = CK_NoOp;
1519   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1520     CastNeeded = CK_BitCast;
1521     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1522       << PointerArg->getType()
1523       << Context.getPointerType(AddrType)
1524       << AA_Passing << PointerArg->getSourceRange();
1525   }
1526 
1527   // Finally, do the cast and replace the argument with the corrected version.
1528   AddrType = Context.getPointerType(AddrType);
1529   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1530   if (PointerArgRes.isInvalid())
1531     return true;
1532   PointerArg = PointerArgRes.get();
1533 
1534   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1535 
1536   // In general, we allow ints, floats and pointers to be loaded and stored.
1537   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1538       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1539     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1540       << PointerArg->getType() << PointerArg->getSourceRange();
1541     return true;
1542   }
1543 
1544   // But ARM doesn't have instructions to deal with 128-bit versions.
1545   if (Context.getTypeSize(ValType) > MaxWidth) {
1546     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1547     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1548       << PointerArg->getType() << PointerArg->getSourceRange();
1549     return true;
1550   }
1551 
1552   switch (ValType.getObjCLifetime()) {
1553   case Qualifiers::OCL_None:
1554   case Qualifiers::OCL_ExplicitNone:
1555     // okay
1556     break;
1557 
1558   case Qualifiers::OCL_Weak:
1559   case Qualifiers::OCL_Strong:
1560   case Qualifiers::OCL_Autoreleasing:
1561     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1562       << ValType << PointerArg->getSourceRange();
1563     return true;
1564   }
1565 
1566   if (IsLdrex) {
1567     TheCall->setType(ValType);
1568     return false;
1569   }
1570 
1571   // Initialize the argument to be stored.
1572   ExprResult ValArg = TheCall->getArg(0);
1573   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1574       Context, ValType, /*consume*/ false);
1575   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1576   if (ValArg.isInvalid())
1577     return true;
1578   TheCall->setArg(0, ValArg.get());
1579 
1580   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1581   // but the custom checker bypasses all default analysis.
1582   TheCall->setType(Context.IntTy);
1583   return false;
1584 }
1585 
1586 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1587   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1588       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1589       BuiltinID == ARM::BI__builtin_arm_strex ||
1590       BuiltinID == ARM::BI__builtin_arm_stlex) {
1591     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1592   }
1593 
1594   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1595     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1596       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1597   }
1598 
1599   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1600       BuiltinID == ARM::BI__builtin_arm_wsr64)
1601     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1602 
1603   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1604       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1605       BuiltinID == ARM::BI__builtin_arm_wsr ||
1606       BuiltinID == ARM::BI__builtin_arm_wsrp)
1607     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1608 
1609   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1610     return true;
1611 
1612   // For intrinsics which take an immediate value as part of the instruction,
1613   // range check them here.
1614   // FIXME: VFP Intrinsics should error if VFP not present.
1615   switch (BuiltinID) {
1616   default: return false;
1617   case ARM::BI__builtin_arm_ssat:
1618     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1619   case ARM::BI__builtin_arm_usat:
1620     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1621   case ARM::BI__builtin_arm_ssat16:
1622     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1623   case ARM::BI__builtin_arm_usat16:
1624     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1625   case ARM::BI__builtin_arm_vcvtr_f:
1626   case ARM::BI__builtin_arm_vcvtr_d:
1627     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1628   case ARM::BI__builtin_arm_dmb:
1629   case ARM::BI__builtin_arm_dsb:
1630   case ARM::BI__builtin_arm_isb:
1631   case ARM::BI__builtin_arm_dbg:
1632     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1633   }
1634 }
1635 
1636 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1637                                          CallExpr *TheCall) {
1638   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1639       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1640       BuiltinID == AArch64::BI__builtin_arm_strex ||
1641       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1642     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1643   }
1644 
1645   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1646     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1647       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1648       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1649       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1650   }
1651 
1652   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1653       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1654     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1655 
1656   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1657       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1658       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1659       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1660     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1661 
1662   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1663     return true;
1664 
1665   // For intrinsics which take an immediate value as part of the instruction,
1666   // range check them here.
1667   unsigned i = 0, l = 0, u = 0;
1668   switch (BuiltinID) {
1669   default: return false;
1670   case AArch64::BI__builtin_arm_dmb:
1671   case AArch64::BI__builtin_arm_dsb:
1672   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1673   }
1674 
1675   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1676 }
1677 
1678 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1679                                            CallExpr *TheCall) {
1680   struct ArgInfo {
1681     ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1682       : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1683     unsigned OpNum = 0;
1684     bool IsSigned = false;
1685     unsigned BitWidth = 0;
1686     unsigned Align = 0;
1687   };
1688 
1689   static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1690     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
1691     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
1692     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
1693     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
1694     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
1695     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
1696     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
1697     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
1698     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
1699     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
1700     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
1701 
1702     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
1703     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
1704     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
1705     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
1706     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
1707     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
1708     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
1709     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
1710     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
1711     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
1712     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
1713 
1714     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
1715     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
1716     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
1717     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
1718     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
1719     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
1720     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
1721     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
1722     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
1723     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
1724     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
1725     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
1726     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
1727     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
1728     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
1729     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
1730     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
1731     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
1732     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
1733     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
1734     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
1735     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
1736     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
1737     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
1738     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
1739     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
1740     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
1741     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
1742     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
1743     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
1744     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
1745     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
1746     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
1747     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
1748     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
1749     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
1750     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
1751     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
1752     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
1753     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
1754     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
1755     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
1756     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
1757     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
1758     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
1759     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
1760     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
1761     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
1762     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
1763     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
1764     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
1765     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1766                                                       {{ 1, false, 6,  0 }} },
1767     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
1768     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
1769     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
1770     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
1771     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
1772     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
1773     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1774                                                       {{ 1, false, 5,  0 }} },
1775     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
1776     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
1777     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
1778     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
1779     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
1780     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
1781                                                        { 2, false, 5,  0 }} },
1782     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
1783                                                        { 2, false, 6,  0 }} },
1784     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
1785                                                        { 3, false, 5,  0 }} },
1786     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
1787                                                        { 3, false, 6,  0 }} },
1788     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
1789     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
1790     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
1791     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
1792     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
1793     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
1794     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
1795     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
1796     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
1797     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
1798     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
1799     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
1800     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
1801     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
1802     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
1803     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1804                                                       {{ 2, false, 4,  0 },
1805                                                        { 3, false, 5,  0 }} },
1806     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1807                                                       {{ 2, false, 4,  0 },
1808                                                        { 3, false, 5,  0 }} },
1809     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1810                                                       {{ 2, false, 4,  0 },
1811                                                        { 3, false, 5,  0 }} },
1812     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1813                                                       {{ 2, false, 4,  0 },
1814                                                        { 3, false, 5,  0 }} },
1815     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
1816     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
1817     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
1818     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
1819     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
1820     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
1821     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
1822     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
1823     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
1824     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
1825     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
1826                                                        { 2, false, 5,  0 }} },
1827     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
1828                                                        { 2, false, 6,  0 }} },
1829     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
1830     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
1831     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
1832     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
1833     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
1834     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
1835     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
1836     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
1837     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1838                                                       {{ 1, false, 4,  0 }} },
1839     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
1840     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1841                                                       {{ 1, false, 4,  0 }} },
1842     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
1843     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
1844     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
1845     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
1846     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
1847     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
1848     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
1849     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
1850     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
1851     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
1852     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
1853     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
1854     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
1855     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
1856     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
1857     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
1858     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
1859     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
1860     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
1861     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1862                                                       {{ 3, false, 1,  0 }} },
1863     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
1864     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
1865     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
1866     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1867                                                       {{ 3, false, 1,  0 }} },
1868     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
1869     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
1870     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
1871     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1872                                                       {{ 3, false, 1,  0 }} },
1873   };
1874 
1875   auto F = Infos.find(BuiltinID);
1876   if (F == Infos.end())
1877     return false;
1878 
1879   bool Error = false;
1880 
1881   for (const ArgInfo &A : F->second) {
1882     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1883     int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1884     if (!A.Align) {
1885       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1886     } else {
1887       unsigned M = 1 << A.Align;
1888       Min *= M;
1889       Max *= M;
1890       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1891                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1892     }
1893   }
1894   return Error;
1895 }
1896 
1897 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1898 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1899 // ordering for DSP is unspecified. MSA is ordered by the data format used
1900 // by the underlying instruction i.e., df/m, df/n and then by size.
1901 //
1902 // FIXME: The size tests here should instead be tablegen'd along with the
1903 //        definitions from include/clang/Basic/BuiltinsMips.def.
1904 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1905 //        be too.
1906 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1907   unsigned i = 0, l = 0, u = 0, m = 0;
1908   switch (BuiltinID) {
1909   default: return false;
1910   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1911   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1912   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1913   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1914   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1915   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1916   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1917   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1918   // df/m field.
1919   // These intrinsics take an unsigned 3 bit immediate.
1920   case Mips::BI__builtin_msa_bclri_b:
1921   case Mips::BI__builtin_msa_bnegi_b:
1922   case Mips::BI__builtin_msa_bseti_b:
1923   case Mips::BI__builtin_msa_sat_s_b:
1924   case Mips::BI__builtin_msa_sat_u_b:
1925   case Mips::BI__builtin_msa_slli_b:
1926   case Mips::BI__builtin_msa_srai_b:
1927   case Mips::BI__builtin_msa_srari_b:
1928   case Mips::BI__builtin_msa_srli_b:
1929   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1930   case Mips::BI__builtin_msa_binsli_b:
1931   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1932   // These intrinsics take an unsigned 4 bit immediate.
1933   case Mips::BI__builtin_msa_bclri_h:
1934   case Mips::BI__builtin_msa_bnegi_h:
1935   case Mips::BI__builtin_msa_bseti_h:
1936   case Mips::BI__builtin_msa_sat_s_h:
1937   case Mips::BI__builtin_msa_sat_u_h:
1938   case Mips::BI__builtin_msa_slli_h:
1939   case Mips::BI__builtin_msa_srai_h:
1940   case Mips::BI__builtin_msa_srari_h:
1941   case Mips::BI__builtin_msa_srli_h:
1942   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1943   case Mips::BI__builtin_msa_binsli_h:
1944   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1945   // These intrinsics take an unsigned 5 bit immediate.
1946   // The first block of intrinsics actually have an unsigned 5 bit field,
1947   // not a df/n field.
1948   case Mips::BI__builtin_msa_clei_u_b:
1949   case Mips::BI__builtin_msa_clei_u_h:
1950   case Mips::BI__builtin_msa_clei_u_w:
1951   case Mips::BI__builtin_msa_clei_u_d:
1952   case Mips::BI__builtin_msa_clti_u_b:
1953   case Mips::BI__builtin_msa_clti_u_h:
1954   case Mips::BI__builtin_msa_clti_u_w:
1955   case Mips::BI__builtin_msa_clti_u_d:
1956   case Mips::BI__builtin_msa_maxi_u_b:
1957   case Mips::BI__builtin_msa_maxi_u_h:
1958   case Mips::BI__builtin_msa_maxi_u_w:
1959   case Mips::BI__builtin_msa_maxi_u_d:
1960   case Mips::BI__builtin_msa_mini_u_b:
1961   case Mips::BI__builtin_msa_mini_u_h:
1962   case Mips::BI__builtin_msa_mini_u_w:
1963   case Mips::BI__builtin_msa_mini_u_d:
1964   case Mips::BI__builtin_msa_addvi_b:
1965   case Mips::BI__builtin_msa_addvi_h:
1966   case Mips::BI__builtin_msa_addvi_w:
1967   case Mips::BI__builtin_msa_addvi_d:
1968   case Mips::BI__builtin_msa_bclri_w:
1969   case Mips::BI__builtin_msa_bnegi_w:
1970   case Mips::BI__builtin_msa_bseti_w:
1971   case Mips::BI__builtin_msa_sat_s_w:
1972   case Mips::BI__builtin_msa_sat_u_w:
1973   case Mips::BI__builtin_msa_slli_w:
1974   case Mips::BI__builtin_msa_srai_w:
1975   case Mips::BI__builtin_msa_srari_w:
1976   case Mips::BI__builtin_msa_srli_w:
1977   case Mips::BI__builtin_msa_srlri_w:
1978   case Mips::BI__builtin_msa_subvi_b:
1979   case Mips::BI__builtin_msa_subvi_h:
1980   case Mips::BI__builtin_msa_subvi_w:
1981   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1982   case Mips::BI__builtin_msa_binsli_w:
1983   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1984   // These intrinsics take an unsigned 6 bit immediate.
1985   case Mips::BI__builtin_msa_bclri_d:
1986   case Mips::BI__builtin_msa_bnegi_d:
1987   case Mips::BI__builtin_msa_bseti_d:
1988   case Mips::BI__builtin_msa_sat_s_d:
1989   case Mips::BI__builtin_msa_sat_u_d:
1990   case Mips::BI__builtin_msa_slli_d:
1991   case Mips::BI__builtin_msa_srai_d:
1992   case Mips::BI__builtin_msa_srari_d:
1993   case Mips::BI__builtin_msa_srli_d:
1994   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1995   case Mips::BI__builtin_msa_binsli_d:
1996   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1997   // These intrinsics take a signed 5 bit immediate.
1998   case Mips::BI__builtin_msa_ceqi_b:
1999   case Mips::BI__builtin_msa_ceqi_h:
2000   case Mips::BI__builtin_msa_ceqi_w:
2001   case Mips::BI__builtin_msa_ceqi_d:
2002   case Mips::BI__builtin_msa_clti_s_b:
2003   case Mips::BI__builtin_msa_clti_s_h:
2004   case Mips::BI__builtin_msa_clti_s_w:
2005   case Mips::BI__builtin_msa_clti_s_d:
2006   case Mips::BI__builtin_msa_clei_s_b:
2007   case Mips::BI__builtin_msa_clei_s_h:
2008   case Mips::BI__builtin_msa_clei_s_w:
2009   case Mips::BI__builtin_msa_clei_s_d:
2010   case Mips::BI__builtin_msa_maxi_s_b:
2011   case Mips::BI__builtin_msa_maxi_s_h:
2012   case Mips::BI__builtin_msa_maxi_s_w:
2013   case Mips::BI__builtin_msa_maxi_s_d:
2014   case Mips::BI__builtin_msa_mini_s_b:
2015   case Mips::BI__builtin_msa_mini_s_h:
2016   case Mips::BI__builtin_msa_mini_s_w:
2017   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2018   // These intrinsics take an unsigned 8 bit immediate.
2019   case Mips::BI__builtin_msa_andi_b:
2020   case Mips::BI__builtin_msa_nori_b:
2021   case Mips::BI__builtin_msa_ori_b:
2022   case Mips::BI__builtin_msa_shf_b:
2023   case Mips::BI__builtin_msa_shf_h:
2024   case Mips::BI__builtin_msa_shf_w:
2025   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2026   case Mips::BI__builtin_msa_bseli_b:
2027   case Mips::BI__builtin_msa_bmnzi_b:
2028   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2029   // df/n format
2030   // These intrinsics take an unsigned 4 bit immediate.
2031   case Mips::BI__builtin_msa_copy_s_b:
2032   case Mips::BI__builtin_msa_copy_u_b:
2033   case Mips::BI__builtin_msa_insve_b:
2034   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2035   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2036   // These intrinsics take an unsigned 3 bit immediate.
2037   case Mips::BI__builtin_msa_copy_s_h:
2038   case Mips::BI__builtin_msa_copy_u_h:
2039   case Mips::BI__builtin_msa_insve_h:
2040   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2041   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2042   // These intrinsics take an unsigned 2 bit immediate.
2043   case Mips::BI__builtin_msa_copy_s_w:
2044   case Mips::BI__builtin_msa_copy_u_w:
2045   case Mips::BI__builtin_msa_insve_w:
2046   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2047   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2048   // These intrinsics take an unsigned 1 bit immediate.
2049   case Mips::BI__builtin_msa_copy_s_d:
2050   case Mips::BI__builtin_msa_copy_u_d:
2051   case Mips::BI__builtin_msa_insve_d:
2052   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2053   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2054   // Memory offsets and immediate loads.
2055   // These intrinsics take a signed 10 bit immediate.
2056   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2057   case Mips::BI__builtin_msa_ldi_h:
2058   case Mips::BI__builtin_msa_ldi_w:
2059   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2060   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2061   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2062   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2063   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2064   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2065   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2066   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2067   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
2068   }
2069 
2070   if (!m)
2071     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2072 
2073   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2074          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2075 }
2076 
2077 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2078   unsigned i = 0, l = 0, u = 0;
2079   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2080                       BuiltinID == PPC::BI__builtin_divdeu ||
2081                       BuiltinID == PPC::BI__builtin_bpermd;
2082   bool IsTarget64Bit = Context.getTargetInfo()
2083                               .getTypeWidth(Context
2084                                             .getTargetInfo()
2085                                             .getIntPtrType()) == 64;
2086   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2087                        BuiltinID == PPC::BI__builtin_divweu ||
2088                        BuiltinID == PPC::BI__builtin_divde ||
2089                        BuiltinID == PPC::BI__builtin_divdeu;
2090 
2091   if (Is64BitBltin && !IsTarget64Bit)
2092       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2093              << TheCall->getSourceRange();
2094 
2095   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2096       (BuiltinID == PPC::BI__builtin_bpermd &&
2097        !Context.getTargetInfo().hasFeature("bpermd")))
2098     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2099            << TheCall->getSourceRange();
2100 
2101   switch (BuiltinID) {
2102   default: return false;
2103   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2104   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2105     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2106            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2107   case PPC::BI__builtin_tbegin:
2108   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2109   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2110   case PPC::BI__builtin_tabortwc:
2111   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2112   case PPC::BI__builtin_tabortwci:
2113   case PPC::BI__builtin_tabortdci:
2114     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2115            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
2116   case PPC::BI__builtin_vsx_xxpermdi:
2117   case PPC::BI__builtin_vsx_xxsldwi:
2118     return SemaBuiltinVSX(TheCall);
2119   }
2120   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2121 }
2122 
2123 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2124                                            CallExpr *TheCall) {
2125   if (BuiltinID == SystemZ::BI__builtin_tabort) {
2126     Expr *Arg = TheCall->getArg(0);
2127     llvm::APSInt AbortCode(32);
2128     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2129         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2130       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2131              << Arg->getSourceRange();
2132   }
2133 
2134   // For intrinsics which take an immediate value as part of the instruction,
2135   // range check them here.
2136   unsigned i = 0, l = 0, u = 0;
2137   switch (BuiltinID) {
2138   default: return false;
2139   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2140   case SystemZ::BI__builtin_s390_verimb:
2141   case SystemZ::BI__builtin_s390_verimh:
2142   case SystemZ::BI__builtin_s390_verimf:
2143   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2144   case SystemZ::BI__builtin_s390_vfaeb:
2145   case SystemZ::BI__builtin_s390_vfaeh:
2146   case SystemZ::BI__builtin_s390_vfaef:
2147   case SystemZ::BI__builtin_s390_vfaebs:
2148   case SystemZ::BI__builtin_s390_vfaehs:
2149   case SystemZ::BI__builtin_s390_vfaefs:
2150   case SystemZ::BI__builtin_s390_vfaezb:
2151   case SystemZ::BI__builtin_s390_vfaezh:
2152   case SystemZ::BI__builtin_s390_vfaezf:
2153   case SystemZ::BI__builtin_s390_vfaezbs:
2154   case SystemZ::BI__builtin_s390_vfaezhs:
2155   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
2156   case SystemZ::BI__builtin_s390_vfisb:
2157   case SystemZ::BI__builtin_s390_vfidb:
2158     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2159            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2160   case SystemZ::BI__builtin_s390_vftcisb:
2161   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2162   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2163   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2164   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2165   case SystemZ::BI__builtin_s390_vstrcb:
2166   case SystemZ::BI__builtin_s390_vstrch:
2167   case SystemZ::BI__builtin_s390_vstrcf:
2168   case SystemZ::BI__builtin_s390_vstrczb:
2169   case SystemZ::BI__builtin_s390_vstrczh:
2170   case SystemZ::BI__builtin_s390_vstrczf:
2171   case SystemZ::BI__builtin_s390_vstrcbs:
2172   case SystemZ::BI__builtin_s390_vstrchs:
2173   case SystemZ::BI__builtin_s390_vstrcfs:
2174   case SystemZ::BI__builtin_s390_vstrczbs:
2175   case SystemZ::BI__builtin_s390_vstrczhs:
2176   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
2177   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2178   case SystemZ::BI__builtin_s390_vfminsb:
2179   case SystemZ::BI__builtin_s390_vfmaxsb:
2180   case SystemZ::BI__builtin_s390_vfmindb:
2181   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
2182   }
2183   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2184 }
2185 
2186 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2187 /// This checks that the target supports __builtin_cpu_supports and
2188 /// that the string argument is constant and valid.
2189 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2190   Expr *Arg = TheCall->getArg(0);
2191 
2192   // Check if the argument is a string literal.
2193   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2194     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2195            << Arg->getSourceRange();
2196 
2197   // Check the contents of the string.
2198   StringRef Feature =
2199       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2200   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2201     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2202            << Arg->getSourceRange();
2203   return false;
2204 }
2205 
2206 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2207 /// This checks that the target supports __builtin_cpu_is and
2208 /// that the string argument is constant and valid.
2209 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2210   Expr *Arg = TheCall->getArg(0);
2211 
2212   // Check if the argument is a string literal.
2213   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2214     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2215            << Arg->getSourceRange();
2216 
2217   // Check the contents of the string.
2218   StringRef Feature =
2219       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2220   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2221     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2222            << Arg->getSourceRange();
2223   return false;
2224 }
2225 
2226 // Check if the rounding mode is legal.
2227 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2228   // Indicates if this instruction has rounding control or just SAE.
2229   bool HasRC = false;
2230 
2231   unsigned ArgNum = 0;
2232   switch (BuiltinID) {
2233   default:
2234     return false;
2235   case X86::BI__builtin_ia32_vcvttsd2si32:
2236   case X86::BI__builtin_ia32_vcvttsd2si64:
2237   case X86::BI__builtin_ia32_vcvttsd2usi32:
2238   case X86::BI__builtin_ia32_vcvttsd2usi64:
2239   case X86::BI__builtin_ia32_vcvttss2si32:
2240   case X86::BI__builtin_ia32_vcvttss2si64:
2241   case X86::BI__builtin_ia32_vcvttss2usi32:
2242   case X86::BI__builtin_ia32_vcvttss2usi64:
2243     ArgNum = 1;
2244     break;
2245   case X86::BI__builtin_ia32_cvtps2pd512_mask:
2246   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2247   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2248   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2249   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2250   case X86::BI__builtin_ia32_cvttps2dq512_mask:
2251   case X86::BI__builtin_ia32_cvttps2qq512_mask:
2252   case X86::BI__builtin_ia32_cvttps2udq512_mask:
2253   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2254   case X86::BI__builtin_ia32_exp2pd_mask:
2255   case X86::BI__builtin_ia32_exp2ps_mask:
2256   case X86::BI__builtin_ia32_getexppd512_mask:
2257   case X86::BI__builtin_ia32_getexpps512_mask:
2258   case X86::BI__builtin_ia32_rcp28pd_mask:
2259   case X86::BI__builtin_ia32_rcp28ps_mask:
2260   case X86::BI__builtin_ia32_rsqrt28pd_mask:
2261   case X86::BI__builtin_ia32_rsqrt28ps_mask:
2262   case X86::BI__builtin_ia32_vcomisd:
2263   case X86::BI__builtin_ia32_vcomiss:
2264   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2265     ArgNum = 3;
2266     break;
2267   case X86::BI__builtin_ia32_cmppd512_mask:
2268   case X86::BI__builtin_ia32_cmpps512_mask:
2269   case X86::BI__builtin_ia32_cmpsd_mask:
2270   case X86::BI__builtin_ia32_cmpss_mask:
2271   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
2272   case X86::BI__builtin_ia32_getexpsd128_round_mask:
2273   case X86::BI__builtin_ia32_getexpss128_round_mask:
2274   case X86::BI__builtin_ia32_maxpd512_mask:
2275   case X86::BI__builtin_ia32_maxps512_mask:
2276   case X86::BI__builtin_ia32_maxsd_round_mask:
2277   case X86::BI__builtin_ia32_maxss_round_mask:
2278   case X86::BI__builtin_ia32_minpd512_mask:
2279   case X86::BI__builtin_ia32_minps512_mask:
2280   case X86::BI__builtin_ia32_minsd_round_mask:
2281   case X86::BI__builtin_ia32_minss_round_mask:
2282   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2283   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2284   case X86::BI__builtin_ia32_reducepd512_mask:
2285   case X86::BI__builtin_ia32_reduceps512_mask:
2286   case X86::BI__builtin_ia32_rndscalepd_mask:
2287   case X86::BI__builtin_ia32_rndscaleps_mask:
2288   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2289   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2290     ArgNum = 4;
2291     break;
2292   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2293   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2294   case X86::BI__builtin_ia32_fixupimmps512_mask:
2295   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2296   case X86::BI__builtin_ia32_fixupimmsd_mask:
2297   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2298   case X86::BI__builtin_ia32_fixupimmss_mask:
2299   case X86::BI__builtin_ia32_fixupimmss_maskz:
2300   case X86::BI__builtin_ia32_rangepd512_mask:
2301   case X86::BI__builtin_ia32_rangeps512_mask:
2302   case X86::BI__builtin_ia32_rangesd128_round_mask:
2303   case X86::BI__builtin_ia32_rangess128_round_mask:
2304   case X86::BI__builtin_ia32_reducesd_mask:
2305   case X86::BI__builtin_ia32_reducess_mask:
2306   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2307   case X86::BI__builtin_ia32_rndscaless_round_mask:
2308     ArgNum = 5;
2309     break;
2310   case X86::BI__builtin_ia32_vcvtsd2si64:
2311   case X86::BI__builtin_ia32_vcvtsd2si32:
2312   case X86::BI__builtin_ia32_vcvtsd2usi32:
2313   case X86::BI__builtin_ia32_vcvtsd2usi64:
2314   case X86::BI__builtin_ia32_vcvtss2si32:
2315   case X86::BI__builtin_ia32_vcvtss2si64:
2316   case X86::BI__builtin_ia32_vcvtss2usi32:
2317   case X86::BI__builtin_ia32_vcvtss2usi64:
2318     ArgNum = 1;
2319     HasRC = true;
2320     break;
2321   case X86::BI__builtin_ia32_cvtsi2sd64:
2322   case X86::BI__builtin_ia32_cvtsi2ss32:
2323   case X86::BI__builtin_ia32_cvtsi2ss64:
2324   case X86::BI__builtin_ia32_cvtusi2sd64:
2325   case X86::BI__builtin_ia32_cvtusi2ss32:
2326   case X86::BI__builtin_ia32_cvtusi2ss64:
2327     ArgNum = 2;
2328     HasRC = true;
2329     break;
2330   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2331   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2332   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2333   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2334   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2335   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2336   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2337   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2338   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2339   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2340   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2341   case X86::BI__builtin_ia32_sqrtpd512_mask:
2342   case X86::BI__builtin_ia32_sqrtps512_mask:
2343     ArgNum = 3;
2344     HasRC = true;
2345     break;
2346   case X86::BI__builtin_ia32_addpd512_mask:
2347   case X86::BI__builtin_ia32_addps512_mask:
2348   case X86::BI__builtin_ia32_divpd512_mask:
2349   case X86::BI__builtin_ia32_divps512_mask:
2350   case X86::BI__builtin_ia32_mulpd512_mask:
2351   case X86::BI__builtin_ia32_mulps512_mask:
2352   case X86::BI__builtin_ia32_subpd512_mask:
2353   case X86::BI__builtin_ia32_subps512_mask:
2354   case X86::BI__builtin_ia32_addss_round_mask:
2355   case X86::BI__builtin_ia32_addsd_round_mask:
2356   case X86::BI__builtin_ia32_divss_round_mask:
2357   case X86::BI__builtin_ia32_divsd_round_mask:
2358   case X86::BI__builtin_ia32_mulss_round_mask:
2359   case X86::BI__builtin_ia32_mulsd_round_mask:
2360   case X86::BI__builtin_ia32_subss_round_mask:
2361   case X86::BI__builtin_ia32_subsd_round_mask:
2362   case X86::BI__builtin_ia32_scalefpd512_mask:
2363   case X86::BI__builtin_ia32_scalefps512_mask:
2364   case X86::BI__builtin_ia32_scalefsd_round_mask:
2365   case X86::BI__builtin_ia32_scalefss_round_mask:
2366   case X86::BI__builtin_ia32_getmantpd512_mask:
2367   case X86::BI__builtin_ia32_getmantps512_mask:
2368   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2369   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2370   case X86::BI__builtin_ia32_sqrtss_round_mask:
2371   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2372   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2373   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2374   case X86::BI__builtin_ia32_vfmaddps512_mask:
2375   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2376   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2377   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2378   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2379   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2380   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2381   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2382   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2383   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2384   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2385   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2386   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2387   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2388   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2389   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2390   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2391   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2392   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2393   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2394   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2395   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2396   case X86::BI__builtin_ia32_vfmaddss3_mask:
2397   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2398   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2399     ArgNum = 4;
2400     HasRC = true;
2401     break;
2402   case X86::BI__builtin_ia32_getmantsd_round_mask:
2403   case X86::BI__builtin_ia32_getmantss_round_mask:
2404     ArgNum = 5;
2405     HasRC = true;
2406     break;
2407   }
2408 
2409   llvm::APSInt Result;
2410 
2411   // We can't check the value of a dependent argument.
2412   Expr *Arg = TheCall->getArg(ArgNum);
2413   if (Arg->isTypeDependent() || Arg->isValueDependent())
2414     return false;
2415 
2416   // Check constant-ness first.
2417   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2418     return true;
2419 
2420   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2421   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2422   // combined with ROUND_NO_EXC.
2423   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2424       Result == 8/*ROUND_NO_EXC*/ ||
2425       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2426     return false;
2427 
2428   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2429     << Arg->getSourceRange();
2430 }
2431 
2432 // Check if the gather/scatter scale is legal.
2433 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2434                                              CallExpr *TheCall) {
2435   unsigned ArgNum = 0;
2436   switch (BuiltinID) {
2437   default:
2438     return false;
2439   case X86::BI__builtin_ia32_gatherpfdpd:
2440   case X86::BI__builtin_ia32_gatherpfdps:
2441   case X86::BI__builtin_ia32_gatherpfqpd:
2442   case X86::BI__builtin_ia32_gatherpfqps:
2443   case X86::BI__builtin_ia32_scatterpfdpd:
2444   case X86::BI__builtin_ia32_scatterpfdps:
2445   case X86::BI__builtin_ia32_scatterpfqpd:
2446   case X86::BI__builtin_ia32_scatterpfqps:
2447     ArgNum = 3;
2448     break;
2449   case X86::BI__builtin_ia32_gatherd_pd:
2450   case X86::BI__builtin_ia32_gatherd_pd256:
2451   case X86::BI__builtin_ia32_gatherq_pd:
2452   case X86::BI__builtin_ia32_gatherq_pd256:
2453   case X86::BI__builtin_ia32_gatherd_ps:
2454   case X86::BI__builtin_ia32_gatherd_ps256:
2455   case X86::BI__builtin_ia32_gatherq_ps:
2456   case X86::BI__builtin_ia32_gatherq_ps256:
2457   case X86::BI__builtin_ia32_gatherd_q:
2458   case X86::BI__builtin_ia32_gatherd_q256:
2459   case X86::BI__builtin_ia32_gatherq_q:
2460   case X86::BI__builtin_ia32_gatherq_q256:
2461   case X86::BI__builtin_ia32_gatherd_d:
2462   case X86::BI__builtin_ia32_gatherd_d256:
2463   case X86::BI__builtin_ia32_gatherq_d:
2464   case X86::BI__builtin_ia32_gatherq_d256:
2465   case X86::BI__builtin_ia32_gather3div2df:
2466   case X86::BI__builtin_ia32_gather3div2di:
2467   case X86::BI__builtin_ia32_gather3div4df:
2468   case X86::BI__builtin_ia32_gather3div4di:
2469   case X86::BI__builtin_ia32_gather3div4sf:
2470   case X86::BI__builtin_ia32_gather3div4si:
2471   case X86::BI__builtin_ia32_gather3div8sf:
2472   case X86::BI__builtin_ia32_gather3div8si:
2473   case X86::BI__builtin_ia32_gather3siv2df:
2474   case X86::BI__builtin_ia32_gather3siv2di:
2475   case X86::BI__builtin_ia32_gather3siv4df:
2476   case X86::BI__builtin_ia32_gather3siv4di:
2477   case X86::BI__builtin_ia32_gather3siv4sf:
2478   case X86::BI__builtin_ia32_gather3siv4si:
2479   case X86::BI__builtin_ia32_gather3siv8sf:
2480   case X86::BI__builtin_ia32_gather3siv8si:
2481   case X86::BI__builtin_ia32_gathersiv8df:
2482   case X86::BI__builtin_ia32_gathersiv16sf:
2483   case X86::BI__builtin_ia32_gatherdiv8df:
2484   case X86::BI__builtin_ia32_gatherdiv16sf:
2485   case X86::BI__builtin_ia32_gathersiv8di:
2486   case X86::BI__builtin_ia32_gathersiv16si:
2487   case X86::BI__builtin_ia32_gatherdiv8di:
2488   case X86::BI__builtin_ia32_gatherdiv16si:
2489   case X86::BI__builtin_ia32_scatterdiv2df:
2490   case X86::BI__builtin_ia32_scatterdiv2di:
2491   case X86::BI__builtin_ia32_scatterdiv4df:
2492   case X86::BI__builtin_ia32_scatterdiv4di:
2493   case X86::BI__builtin_ia32_scatterdiv4sf:
2494   case X86::BI__builtin_ia32_scatterdiv4si:
2495   case X86::BI__builtin_ia32_scatterdiv8sf:
2496   case X86::BI__builtin_ia32_scatterdiv8si:
2497   case X86::BI__builtin_ia32_scattersiv2df:
2498   case X86::BI__builtin_ia32_scattersiv2di:
2499   case X86::BI__builtin_ia32_scattersiv4df:
2500   case X86::BI__builtin_ia32_scattersiv4di:
2501   case X86::BI__builtin_ia32_scattersiv4sf:
2502   case X86::BI__builtin_ia32_scattersiv4si:
2503   case X86::BI__builtin_ia32_scattersiv8sf:
2504   case X86::BI__builtin_ia32_scattersiv8si:
2505   case X86::BI__builtin_ia32_scattersiv8df:
2506   case X86::BI__builtin_ia32_scattersiv16sf:
2507   case X86::BI__builtin_ia32_scatterdiv8df:
2508   case X86::BI__builtin_ia32_scatterdiv16sf:
2509   case X86::BI__builtin_ia32_scattersiv8di:
2510   case X86::BI__builtin_ia32_scattersiv16si:
2511   case X86::BI__builtin_ia32_scatterdiv8di:
2512   case X86::BI__builtin_ia32_scatterdiv16si:
2513     ArgNum = 4;
2514     break;
2515   }
2516 
2517   llvm::APSInt Result;
2518 
2519   // We can't check the value of a dependent argument.
2520   Expr *Arg = TheCall->getArg(ArgNum);
2521   if (Arg->isTypeDependent() || Arg->isValueDependent())
2522     return false;
2523 
2524   // Check constant-ness first.
2525   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2526     return true;
2527 
2528   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2529     return false;
2530 
2531   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2532     << Arg->getSourceRange();
2533 }
2534 
2535 static bool isX86_32Builtin(unsigned BuiltinID) {
2536   // These builtins only work on x86-32 targets.
2537   switch (BuiltinID) {
2538   case X86::BI__builtin_ia32_readeflags_u32:
2539   case X86::BI__builtin_ia32_writeeflags_u32:
2540     return true;
2541   }
2542 
2543   return false;
2544 }
2545 
2546 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2547   if (BuiltinID == X86::BI__builtin_cpu_supports)
2548     return SemaBuiltinCpuSupports(*this, TheCall);
2549 
2550   if (BuiltinID == X86::BI__builtin_cpu_is)
2551     return SemaBuiltinCpuIs(*this, TheCall);
2552 
2553   // Check for 32-bit only builtins on a 64-bit target.
2554   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2555   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2556     return Diag(TheCall->getCallee()->getLocStart(),
2557                 diag::err_32_bit_builtin_64_bit_tgt);
2558 
2559   // If the intrinsic has rounding or SAE make sure its valid.
2560   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2561     return true;
2562 
2563   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2564   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2565     return true;
2566 
2567   // For intrinsics which take an immediate value as part of the instruction,
2568   // range check them here.
2569   int i = 0, l = 0, u = 0;
2570   switch (BuiltinID) {
2571   default:
2572     return false;
2573   case X86::BI_mm_prefetch:
2574     i = 1; l = 0; u = 7;
2575     break;
2576   case X86::BI__builtin_ia32_sha1rnds4:
2577   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2578   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2579   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2580   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2581     i = 2; l = 0; u = 3;
2582     break;
2583   case X86::BI__builtin_ia32_vpermil2pd:
2584   case X86::BI__builtin_ia32_vpermil2pd256:
2585   case X86::BI__builtin_ia32_vpermil2ps:
2586   case X86::BI__builtin_ia32_vpermil2ps256:
2587     i = 3; l = 0; u = 3;
2588     break;
2589   case X86::BI__builtin_ia32_cmpb128_mask:
2590   case X86::BI__builtin_ia32_cmpw128_mask:
2591   case X86::BI__builtin_ia32_cmpd128_mask:
2592   case X86::BI__builtin_ia32_cmpq128_mask:
2593   case X86::BI__builtin_ia32_cmpb256_mask:
2594   case X86::BI__builtin_ia32_cmpw256_mask:
2595   case X86::BI__builtin_ia32_cmpd256_mask:
2596   case X86::BI__builtin_ia32_cmpq256_mask:
2597   case X86::BI__builtin_ia32_cmpb512_mask:
2598   case X86::BI__builtin_ia32_cmpw512_mask:
2599   case X86::BI__builtin_ia32_cmpd512_mask:
2600   case X86::BI__builtin_ia32_cmpq512_mask:
2601   case X86::BI__builtin_ia32_ucmpb128_mask:
2602   case X86::BI__builtin_ia32_ucmpw128_mask:
2603   case X86::BI__builtin_ia32_ucmpd128_mask:
2604   case X86::BI__builtin_ia32_ucmpq128_mask:
2605   case X86::BI__builtin_ia32_ucmpb256_mask:
2606   case X86::BI__builtin_ia32_ucmpw256_mask:
2607   case X86::BI__builtin_ia32_ucmpd256_mask:
2608   case X86::BI__builtin_ia32_ucmpq256_mask:
2609   case X86::BI__builtin_ia32_ucmpb512_mask:
2610   case X86::BI__builtin_ia32_ucmpw512_mask:
2611   case X86::BI__builtin_ia32_ucmpd512_mask:
2612   case X86::BI__builtin_ia32_ucmpq512_mask:
2613   case X86::BI__builtin_ia32_vpcomub:
2614   case X86::BI__builtin_ia32_vpcomuw:
2615   case X86::BI__builtin_ia32_vpcomud:
2616   case X86::BI__builtin_ia32_vpcomuq:
2617   case X86::BI__builtin_ia32_vpcomb:
2618   case X86::BI__builtin_ia32_vpcomw:
2619   case X86::BI__builtin_ia32_vpcomd:
2620   case X86::BI__builtin_ia32_vpcomq:
2621     i = 2; l = 0; u = 7;
2622     break;
2623   case X86::BI__builtin_ia32_roundps:
2624   case X86::BI__builtin_ia32_roundpd:
2625   case X86::BI__builtin_ia32_roundps256:
2626   case X86::BI__builtin_ia32_roundpd256:
2627     i = 1; l = 0; u = 15;
2628     break;
2629   case X86::BI__builtin_ia32_roundss:
2630   case X86::BI__builtin_ia32_roundsd:
2631   case X86::BI__builtin_ia32_rangepd128_mask:
2632   case X86::BI__builtin_ia32_rangepd256_mask:
2633   case X86::BI__builtin_ia32_rangepd512_mask:
2634   case X86::BI__builtin_ia32_rangeps128_mask:
2635   case X86::BI__builtin_ia32_rangeps256_mask:
2636   case X86::BI__builtin_ia32_rangeps512_mask:
2637   case X86::BI__builtin_ia32_getmantsd_round_mask:
2638   case X86::BI__builtin_ia32_getmantss_round_mask:
2639     i = 2; l = 0; u = 15;
2640     break;
2641   case X86::BI__builtin_ia32_cmpps:
2642   case X86::BI__builtin_ia32_cmpss:
2643   case X86::BI__builtin_ia32_cmppd:
2644   case X86::BI__builtin_ia32_cmpsd:
2645   case X86::BI__builtin_ia32_cmpps256:
2646   case X86::BI__builtin_ia32_cmppd256:
2647   case X86::BI__builtin_ia32_cmpps128_mask:
2648   case X86::BI__builtin_ia32_cmppd128_mask:
2649   case X86::BI__builtin_ia32_cmpps256_mask:
2650   case X86::BI__builtin_ia32_cmppd256_mask:
2651   case X86::BI__builtin_ia32_cmpps512_mask:
2652   case X86::BI__builtin_ia32_cmppd512_mask:
2653   case X86::BI__builtin_ia32_cmpsd_mask:
2654   case X86::BI__builtin_ia32_cmpss_mask:
2655     i = 2; l = 0; u = 31;
2656     break;
2657   case X86::BI__builtin_ia32_vcvtps2ph:
2658   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2659   case X86::BI__builtin_ia32_vcvtps2ph256:
2660   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2661   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2662   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2663   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2664   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2665   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2666   case X86::BI__builtin_ia32_rndscaleps_mask:
2667   case X86::BI__builtin_ia32_rndscalepd_mask:
2668   case X86::BI__builtin_ia32_reducepd128_mask:
2669   case X86::BI__builtin_ia32_reducepd256_mask:
2670   case X86::BI__builtin_ia32_reducepd512_mask:
2671   case X86::BI__builtin_ia32_reduceps128_mask:
2672   case X86::BI__builtin_ia32_reduceps256_mask:
2673   case X86::BI__builtin_ia32_reduceps512_mask:
2674   case X86::BI__builtin_ia32_prold512_mask:
2675   case X86::BI__builtin_ia32_prolq512_mask:
2676   case X86::BI__builtin_ia32_prold128_mask:
2677   case X86::BI__builtin_ia32_prold256_mask:
2678   case X86::BI__builtin_ia32_prolq128_mask:
2679   case X86::BI__builtin_ia32_prolq256_mask:
2680   case X86::BI__builtin_ia32_prord128_mask:
2681   case X86::BI__builtin_ia32_prord256_mask:
2682   case X86::BI__builtin_ia32_prorq128_mask:
2683   case X86::BI__builtin_ia32_prorq256_mask:
2684   case X86::BI__builtin_ia32_fpclasspd128_mask:
2685   case X86::BI__builtin_ia32_fpclasspd256_mask:
2686   case X86::BI__builtin_ia32_fpclassps128_mask:
2687   case X86::BI__builtin_ia32_fpclassps256_mask:
2688   case X86::BI__builtin_ia32_fpclassps512_mask:
2689   case X86::BI__builtin_ia32_fpclasspd512_mask:
2690   case X86::BI__builtin_ia32_fpclasssd_mask:
2691   case X86::BI__builtin_ia32_fpclassss_mask:
2692     i = 1; l = 0; u = 255;
2693     break;
2694   case X86::BI__builtin_ia32_palignr128:
2695   case X86::BI__builtin_ia32_palignr256:
2696   case X86::BI__builtin_ia32_palignr512_mask:
2697   case X86::BI__builtin_ia32_vcomisd:
2698   case X86::BI__builtin_ia32_vcomiss:
2699   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2700   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2701   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2702   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2703   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2704   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2705   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2706   case X86::BI__builtin_ia32_vpshldd128_mask:
2707   case X86::BI__builtin_ia32_vpshldd256_mask:
2708   case X86::BI__builtin_ia32_vpshldd512_mask:
2709   case X86::BI__builtin_ia32_vpshldq128_mask:
2710   case X86::BI__builtin_ia32_vpshldq256_mask:
2711   case X86::BI__builtin_ia32_vpshldq512_mask:
2712   case X86::BI__builtin_ia32_vpshldw128_mask:
2713   case X86::BI__builtin_ia32_vpshldw256_mask:
2714   case X86::BI__builtin_ia32_vpshldw512_mask:
2715   case X86::BI__builtin_ia32_vpshrdd128_mask:
2716   case X86::BI__builtin_ia32_vpshrdd256_mask:
2717   case X86::BI__builtin_ia32_vpshrdd512_mask:
2718   case X86::BI__builtin_ia32_vpshrdq128_mask:
2719   case X86::BI__builtin_ia32_vpshrdq256_mask:
2720   case X86::BI__builtin_ia32_vpshrdq512_mask:
2721   case X86::BI__builtin_ia32_vpshrdw128_mask:
2722   case X86::BI__builtin_ia32_vpshrdw256_mask:
2723   case X86::BI__builtin_ia32_vpshrdw512_mask:
2724     i = 2; l = 0; u = 255;
2725     break;
2726   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2727   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2728   case X86::BI__builtin_ia32_fixupimmps512_mask:
2729   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2730   case X86::BI__builtin_ia32_fixupimmsd_mask:
2731   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2732   case X86::BI__builtin_ia32_fixupimmss_mask:
2733   case X86::BI__builtin_ia32_fixupimmss_maskz:
2734   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2735   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2736   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2737   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2738   case X86::BI__builtin_ia32_fixupimmps128_mask:
2739   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2740   case X86::BI__builtin_ia32_fixupimmps256_mask:
2741   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2742   case X86::BI__builtin_ia32_pternlogd512_mask:
2743   case X86::BI__builtin_ia32_pternlogd512_maskz:
2744   case X86::BI__builtin_ia32_pternlogq512_mask:
2745   case X86::BI__builtin_ia32_pternlogq512_maskz:
2746   case X86::BI__builtin_ia32_pternlogd128_mask:
2747   case X86::BI__builtin_ia32_pternlogd128_maskz:
2748   case X86::BI__builtin_ia32_pternlogd256_mask:
2749   case X86::BI__builtin_ia32_pternlogd256_maskz:
2750   case X86::BI__builtin_ia32_pternlogq128_mask:
2751   case X86::BI__builtin_ia32_pternlogq128_maskz:
2752   case X86::BI__builtin_ia32_pternlogq256_mask:
2753   case X86::BI__builtin_ia32_pternlogq256_maskz:
2754     i = 3; l = 0; u = 255;
2755     break;
2756   case X86::BI__builtin_ia32_gatherpfdpd:
2757   case X86::BI__builtin_ia32_gatherpfdps:
2758   case X86::BI__builtin_ia32_gatherpfqpd:
2759   case X86::BI__builtin_ia32_gatherpfqps:
2760   case X86::BI__builtin_ia32_scatterpfdpd:
2761   case X86::BI__builtin_ia32_scatterpfdps:
2762   case X86::BI__builtin_ia32_scatterpfqpd:
2763   case X86::BI__builtin_ia32_scatterpfqps:
2764     i = 4; l = 2; u = 3;
2765     break;
2766   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2767   case X86::BI__builtin_ia32_rndscaless_round_mask:
2768     i = 4; l = 0; u = 255;
2769     break;
2770   }
2771   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2772 }
2773 
2774 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2775 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2776 /// Returns true when the format fits the function and the FormatStringInfo has
2777 /// been populated.
2778 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2779                                FormatStringInfo *FSI) {
2780   FSI->HasVAListArg = Format->getFirstArg() == 0;
2781   FSI->FormatIdx = Format->getFormatIdx() - 1;
2782   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2783 
2784   // The way the format attribute works in GCC, the implicit this argument
2785   // of member functions is counted. However, it doesn't appear in our own
2786   // lists, so decrement format_idx in that case.
2787   if (IsCXXMember) {
2788     if(FSI->FormatIdx == 0)
2789       return false;
2790     --FSI->FormatIdx;
2791     if (FSI->FirstDataArg != 0)
2792       --FSI->FirstDataArg;
2793   }
2794   return true;
2795 }
2796 
2797 /// Checks if a the given expression evaluates to null.
2798 ///
2799 /// Returns true if the value evaluates to null.
2800 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2801   // If the expression has non-null type, it doesn't evaluate to null.
2802   if (auto nullability
2803         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2804     if (*nullability == NullabilityKind::NonNull)
2805       return false;
2806   }
2807 
2808   // As a special case, transparent unions initialized with zero are
2809   // considered null for the purposes of the nonnull attribute.
2810   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2811     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2812       if (const CompoundLiteralExpr *CLE =
2813           dyn_cast<CompoundLiteralExpr>(Expr))
2814         if (const InitListExpr *ILE =
2815             dyn_cast<InitListExpr>(CLE->getInitializer()))
2816           Expr = ILE->getInit(0);
2817   }
2818 
2819   bool Result;
2820   return (!Expr->isValueDependent() &&
2821           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2822           !Result);
2823 }
2824 
2825 static void CheckNonNullArgument(Sema &S,
2826                                  const Expr *ArgExpr,
2827                                  SourceLocation CallSiteLoc) {
2828   if (CheckNonNullExpr(S, ArgExpr))
2829     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2830            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2831 }
2832 
2833 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2834   FormatStringInfo FSI;
2835   if ((GetFormatStringType(Format) == FST_NSString) &&
2836       getFormatStringInfo(Format, false, &FSI)) {
2837     Idx = FSI.FormatIdx;
2838     return true;
2839   }
2840   return false;
2841 }
2842 
2843 /// Diagnose use of %s directive in an NSString which is being passed
2844 /// as formatting string to formatting method.
2845 static void
2846 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2847                                         const NamedDecl *FDecl,
2848                                         Expr **Args,
2849                                         unsigned NumArgs) {
2850   unsigned Idx = 0;
2851   bool Format = false;
2852   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2853   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2854     Idx = 2;
2855     Format = true;
2856   }
2857   else
2858     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2859       if (S.GetFormatNSStringIdx(I, Idx)) {
2860         Format = true;
2861         break;
2862       }
2863     }
2864   if (!Format || NumArgs <= Idx)
2865     return;
2866   const Expr *FormatExpr = Args[Idx];
2867   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2868     FormatExpr = CSCE->getSubExpr();
2869   const StringLiteral *FormatString;
2870   if (const ObjCStringLiteral *OSL =
2871       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2872     FormatString = OSL->getString();
2873   else
2874     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2875   if (!FormatString)
2876     return;
2877   if (S.FormatStringHasSArg(FormatString)) {
2878     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2879       << "%s" << 1 << 1;
2880     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2881       << FDecl->getDeclName();
2882   }
2883 }
2884 
2885 /// Determine whether the given type has a non-null nullability annotation.
2886 static bool isNonNullType(ASTContext &ctx, QualType type) {
2887   if (auto nullability = type->getNullability(ctx))
2888     return *nullability == NullabilityKind::NonNull;
2889 
2890   return false;
2891 }
2892 
2893 static void CheckNonNullArguments(Sema &S,
2894                                   const NamedDecl *FDecl,
2895                                   const FunctionProtoType *Proto,
2896                                   ArrayRef<const Expr *> Args,
2897                                   SourceLocation CallSiteLoc) {
2898   assert((FDecl || Proto) && "Need a function declaration or prototype");
2899 
2900   // Check the attributes attached to the method/function itself.
2901   llvm::SmallBitVector NonNullArgs;
2902   if (FDecl) {
2903     // Handle the nonnull attribute on the function/method declaration itself.
2904     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2905       if (!NonNull->args_size()) {
2906         // Easy case: all pointer arguments are nonnull.
2907         for (const auto *Arg : Args)
2908           if (S.isValidPointerAttrType(Arg->getType()))
2909             CheckNonNullArgument(S, Arg, CallSiteLoc);
2910         return;
2911       }
2912 
2913       for (const ParamIdx &Idx : NonNull->args()) {
2914         unsigned IdxAST = Idx.getASTIndex();
2915         if (IdxAST >= Args.size())
2916           continue;
2917         if (NonNullArgs.empty())
2918           NonNullArgs.resize(Args.size());
2919         NonNullArgs.set(IdxAST);
2920       }
2921     }
2922   }
2923 
2924   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2925     // Handle the nonnull attribute on the parameters of the
2926     // function/method.
2927     ArrayRef<ParmVarDecl*> parms;
2928     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2929       parms = FD->parameters();
2930     else
2931       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2932 
2933     unsigned ParamIndex = 0;
2934     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2935          I != E; ++I, ++ParamIndex) {
2936       const ParmVarDecl *PVD = *I;
2937       if (PVD->hasAttr<NonNullAttr>() ||
2938           isNonNullType(S.Context, PVD->getType())) {
2939         if (NonNullArgs.empty())
2940           NonNullArgs.resize(Args.size());
2941 
2942         NonNullArgs.set(ParamIndex);
2943       }
2944     }
2945   } else {
2946     // If we have a non-function, non-method declaration but no
2947     // function prototype, try to dig out the function prototype.
2948     if (!Proto) {
2949       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2950         QualType type = VD->getType().getNonReferenceType();
2951         if (auto pointerType = type->getAs<PointerType>())
2952           type = pointerType->getPointeeType();
2953         else if (auto blockType = type->getAs<BlockPointerType>())
2954           type = blockType->getPointeeType();
2955         // FIXME: data member pointers?
2956 
2957         // Dig out the function prototype, if there is one.
2958         Proto = type->getAs<FunctionProtoType>();
2959       }
2960     }
2961 
2962     // Fill in non-null argument information from the nullability
2963     // information on the parameter types (if we have them).
2964     if (Proto) {
2965       unsigned Index = 0;
2966       for (auto paramType : Proto->getParamTypes()) {
2967         if (isNonNullType(S.Context, paramType)) {
2968           if (NonNullArgs.empty())
2969             NonNullArgs.resize(Args.size());
2970 
2971           NonNullArgs.set(Index);
2972         }
2973 
2974         ++Index;
2975       }
2976     }
2977   }
2978 
2979   // Check for non-null arguments.
2980   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2981        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2982     if (NonNullArgs[ArgIndex])
2983       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2984   }
2985 }
2986 
2987 /// Handles the checks for format strings, non-POD arguments to vararg
2988 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2989 /// attributes.
2990 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2991                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2992                      bool IsMemberFunction, SourceLocation Loc,
2993                      SourceRange Range, VariadicCallType CallType) {
2994   // FIXME: We should check as much as we can in the template definition.
2995   if (CurContext->isDependentContext())
2996     return;
2997 
2998   // Printf and scanf checking.
2999   llvm::SmallBitVector CheckedVarArgs;
3000   if (FDecl) {
3001     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3002       // Only create vector if there are format attributes.
3003       CheckedVarArgs.resize(Args.size());
3004 
3005       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3006                            CheckedVarArgs);
3007     }
3008   }
3009 
3010   // Refuse POD arguments that weren't caught by the format string
3011   // checks above.
3012   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3013   if (CallType != VariadicDoesNotApply &&
3014       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3015     unsigned NumParams = Proto ? Proto->getNumParams()
3016                        : FDecl && isa<FunctionDecl>(FDecl)
3017                            ? cast<FunctionDecl>(FDecl)->getNumParams()
3018                        : FDecl && isa<ObjCMethodDecl>(FDecl)
3019                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
3020                        : 0;
3021 
3022     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3023       // Args[ArgIdx] can be null in malformed code.
3024       if (const Expr *Arg = Args[ArgIdx]) {
3025         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3026           checkVariadicArgument(Arg, CallType);
3027       }
3028     }
3029   }
3030 
3031   if (FDecl || Proto) {
3032     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3033 
3034     // Type safety checking.
3035     if (FDecl) {
3036       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3037         CheckArgumentWithTypeTag(I, Args, Loc);
3038     }
3039   }
3040 
3041   if (FD)
3042     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
3043 }
3044 
3045 /// CheckConstructorCall - Check a constructor call for correctness and safety
3046 /// properties not enforced by the C type system.
3047 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3048                                 ArrayRef<const Expr *> Args,
3049                                 const FunctionProtoType *Proto,
3050                                 SourceLocation Loc) {
3051   VariadicCallType CallType =
3052     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3053   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3054             Loc, SourceRange(), CallType);
3055 }
3056 
3057 /// CheckFunctionCall - Check a direct function call for various correctness
3058 /// and safety properties not strictly enforced by the C type system.
3059 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3060                              const FunctionProtoType *Proto) {
3061   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3062                               isa<CXXMethodDecl>(FDecl);
3063   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3064                           IsMemberOperatorCall;
3065   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3066                                                   TheCall->getCallee());
3067   Expr** Args = TheCall->getArgs();
3068   unsigned NumArgs = TheCall->getNumArgs();
3069 
3070   Expr *ImplicitThis = nullptr;
3071   if (IsMemberOperatorCall) {
3072     // If this is a call to a member operator, hide the first argument
3073     // from checkCall.
3074     // FIXME: Our choice of AST representation here is less than ideal.
3075     ImplicitThis = Args[0];
3076     ++Args;
3077     --NumArgs;
3078   } else if (IsMemberFunction)
3079     ImplicitThis =
3080         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3081 
3082   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
3083             IsMemberFunction, TheCall->getRParenLoc(),
3084             TheCall->getCallee()->getSourceRange(), CallType);
3085 
3086   IdentifierInfo *FnInfo = FDecl->getIdentifier();
3087   // None of the checks below are needed for functions that don't have
3088   // simple names (e.g., C++ conversion functions).
3089   if (!FnInfo)
3090     return false;
3091 
3092   CheckAbsoluteValueFunction(TheCall, FDecl);
3093   CheckMaxUnsignedZero(TheCall, FDecl);
3094 
3095   if (getLangOpts().ObjC1)
3096     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
3097 
3098   unsigned CMId = FDecl->getMemoryFunctionKind();
3099   if (CMId == 0)
3100     return false;
3101 
3102   // Handle memory setting and copying functions.
3103   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
3104     CheckStrlcpycatArguments(TheCall, FnInfo);
3105   else if (CMId == Builtin::BIstrncat)
3106     CheckStrncatArguments(TheCall, FnInfo);
3107   else
3108     CheckMemaccessArguments(TheCall, CMId, FnInfo);
3109 
3110   return false;
3111 }
3112 
3113 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
3114                                ArrayRef<const Expr *> Args) {
3115   VariadicCallType CallType =
3116       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
3117 
3118   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3119             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
3120             CallType);
3121 
3122   return false;
3123 }
3124 
3125 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3126                             const FunctionProtoType *Proto) {
3127   QualType Ty;
3128   if (const auto *V = dyn_cast<VarDecl>(NDecl))
3129     Ty = V->getType().getNonReferenceType();
3130   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
3131     Ty = F->getType().getNonReferenceType();
3132   else
3133     return false;
3134 
3135   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3136       !Ty->isFunctionProtoType())
3137     return false;
3138 
3139   VariadicCallType CallType;
3140   if (!Proto || !Proto->isVariadic()) {
3141     CallType = VariadicDoesNotApply;
3142   } else if (Ty->isBlockPointerType()) {
3143     CallType = VariadicBlock;
3144   } else { // Ty->isFunctionPointerType()
3145     CallType = VariadicFunction;
3146   }
3147 
3148   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
3149             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3150             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3151             TheCall->getCallee()->getSourceRange(), CallType);
3152 
3153   return false;
3154 }
3155 
3156 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3157 /// such as function pointers returned from functions.
3158 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
3159   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
3160                                                   TheCall->getCallee());
3161   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
3162             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3163             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
3164             TheCall->getCallee()->getSourceRange(), CallType);
3165 
3166   return false;
3167 }
3168 
3169 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
3170   if (!llvm::isValidAtomicOrderingCABI(Ordering))
3171     return false;
3172 
3173   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
3174   switch (Op) {
3175   case AtomicExpr::AO__c11_atomic_init:
3176   case AtomicExpr::AO__opencl_atomic_init:
3177     llvm_unreachable("There is no ordering argument for an init");
3178 
3179   case AtomicExpr::AO__c11_atomic_load:
3180   case AtomicExpr::AO__opencl_atomic_load:
3181   case AtomicExpr::AO__atomic_load_n:
3182   case AtomicExpr::AO__atomic_load:
3183     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3184            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3185 
3186   case AtomicExpr::AO__c11_atomic_store:
3187   case AtomicExpr::AO__opencl_atomic_store:
3188   case AtomicExpr::AO__atomic_store:
3189   case AtomicExpr::AO__atomic_store_n:
3190     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3191            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3192            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
3193 
3194   default:
3195     return true;
3196   }
3197 }
3198 
3199 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3200                                          AtomicExpr::AtomicOp Op) {
3201   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3202   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3203 
3204   // All the non-OpenCL operations take one of the following forms.
3205   // The OpenCL operations take the __c11 forms with one extra argument for
3206   // synchronization scope.
3207   enum {
3208     // C    __c11_atomic_init(A *, C)
3209     Init,
3210 
3211     // C    __c11_atomic_load(A *, int)
3212     Load,
3213 
3214     // void __atomic_load(A *, CP, int)
3215     LoadCopy,
3216 
3217     // void __atomic_store(A *, CP, int)
3218     Copy,
3219 
3220     // C    __c11_atomic_add(A *, M, int)
3221     Arithmetic,
3222 
3223     // C    __atomic_exchange_n(A *, CP, int)
3224     Xchg,
3225 
3226     // void __atomic_exchange(A *, C *, CP, int)
3227     GNUXchg,
3228 
3229     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3230     C11CmpXchg,
3231 
3232     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3233     GNUCmpXchg
3234   } Form = Init;
3235 
3236   const unsigned NumForm = GNUCmpXchg + 1;
3237   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3238   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
3239   // where:
3240   //   C is an appropriate type,
3241   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3242   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3243   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3244   //   the int parameters are for orderings.
3245 
3246   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3247       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3248       "need to update code for modified forms");
3249   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3250                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3251                         AtomicExpr::AO__atomic_load,
3252                 "need to update code for modified C11 atomics");
3253   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3254                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3255   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3256                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3257                IsOpenCL;
3258   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3259              Op == AtomicExpr::AO__atomic_store_n ||
3260              Op == AtomicExpr::AO__atomic_exchange_n ||
3261              Op == AtomicExpr::AO__atomic_compare_exchange_n;
3262   bool IsAddSub = false;
3263   bool IsMinMax = false;
3264 
3265   switch (Op) {
3266   case AtomicExpr::AO__c11_atomic_init:
3267   case AtomicExpr::AO__opencl_atomic_init:
3268     Form = Init;
3269     break;
3270 
3271   case AtomicExpr::AO__c11_atomic_load:
3272   case AtomicExpr::AO__opencl_atomic_load:
3273   case AtomicExpr::AO__atomic_load_n:
3274     Form = Load;
3275     break;
3276 
3277   case AtomicExpr::AO__atomic_load:
3278     Form = LoadCopy;
3279     break;
3280 
3281   case AtomicExpr::AO__c11_atomic_store:
3282   case AtomicExpr::AO__opencl_atomic_store:
3283   case AtomicExpr::AO__atomic_store:
3284   case AtomicExpr::AO__atomic_store_n:
3285     Form = Copy;
3286     break;
3287 
3288   case AtomicExpr::AO__c11_atomic_fetch_add:
3289   case AtomicExpr::AO__c11_atomic_fetch_sub:
3290   case AtomicExpr::AO__opencl_atomic_fetch_add:
3291   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3292   case AtomicExpr::AO__opencl_atomic_fetch_min:
3293   case AtomicExpr::AO__opencl_atomic_fetch_max:
3294   case AtomicExpr::AO__atomic_fetch_add:
3295   case AtomicExpr::AO__atomic_fetch_sub:
3296   case AtomicExpr::AO__atomic_add_fetch:
3297   case AtomicExpr::AO__atomic_sub_fetch:
3298     IsAddSub = true;
3299     LLVM_FALLTHROUGH;
3300   case AtomicExpr::AO__c11_atomic_fetch_and:
3301   case AtomicExpr::AO__c11_atomic_fetch_or:
3302   case AtomicExpr::AO__c11_atomic_fetch_xor:
3303   case AtomicExpr::AO__opencl_atomic_fetch_and:
3304   case AtomicExpr::AO__opencl_atomic_fetch_or:
3305   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3306   case AtomicExpr::AO__atomic_fetch_and:
3307   case AtomicExpr::AO__atomic_fetch_or:
3308   case AtomicExpr::AO__atomic_fetch_xor:
3309   case AtomicExpr::AO__atomic_fetch_nand:
3310   case AtomicExpr::AO__atomic_and_fetch:
3311   case AtomicExpr::AO__atomic_or_fetch:
3312   case AtomicExpr::AO__atomic_xor_fetch:
3313   case AtomicExpr::AO__atomic_nand_fetch:
3314     Form = Arithmetic;
3315     break;
3316 
3317   case AtomicExpr::AO__atomic_fetch_min:
3318   case AtomicExpr::AO__atomic_fetch_max:
3319     IsMinMax = true;
3320     Form = Arithmetic;
3321     break;
3322 
3323   case AtomicExpr::AO__c11_atomic_exchange:
3324   case AtomicExpr::AO__opencl_atomic_exchange:
3325   case AtomicExpr::AO__atomic_exchange_n:
3326     Form = Xchg;
3327     break;
3328 
3329   case AtomicExpr::AO__atomic_exchange:
3330     Form = GNUXchg;
3331     break;
3332 
3333   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3334   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3335   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3336   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3337     Form = C11CmpXchg;
3338     break;
3339 
3340   case AtomicExpr::AO__atomic_compare_exchange:
3341   case AtomicExpr::AO__atomic_compare_exchange_n:
3342     Form = GNUCmpXchg;
3343     break;
3344   }
3345 
3346   unsigned AdjustedNumArgs = NumArgs[Form];
3347   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3348     ++AdjustedNumArgs;
3349   // Check we have the right number of arguments.
3350   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3351     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3352       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3353       << TheCall->getCallee()->getSourceRange();
3354     return ExprError();
3355   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3356     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3357          diag::err_typecheck_call_too_many_args)
3358       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3359       << TheCall->getCallee()->getSourceRange();
3360     return ExprError();
3361   }
3362 
3363   // Inspect the first argument of the atomic operation.
3364   Expr *Ptr = TheCall->getArg(0);
3365   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3366   if (ConvertedPtr.isInvalid())
3367     return ExprError();
3368 
3369   Ptr = ConvertedPtr.get();
3370   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3371   if (!pointerType) {
3372     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3373       << Ptr->getType() << Ptr->getSourceRange();
3374     return ExprError();
3375   }
3376 
3377   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3378   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3379   QualType ValType = AtomTy; // 'C'
3380   if (IsC11) {
3381     if (!AtomTy->isAtomicType()) {
3382       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3383         << Ptr->getType() << Ptr->getSourceRange();
3384       return ExprError();
3385     }
3386     if (AtomTy.isConstQualified() ||
3387         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3388       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3389           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3390           << Ptr->getSourceRange();
3391       return ExprError();
3392     }
3393     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3394   } else if (Form != Load && Form != LoadCopy) {
3395     if (ValType.isConstQualified()) {
3396       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3397         << Ptr->getType() << Ptr->getSourceRange();
3398       return ExprError();
3399     }
3400   }
3401 
3402   // For an arithmetic operation, the implied arithmetic must be well-formed.
3403   if (Form == Arithmetic) {
3404     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3405     if (IsAddSub && !ValType->isIntegerType()
3406         && !ValType->isPointerType()) {
3407       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3408         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3409       return ExprError();
3410     }
3411     if (IsMinMax) {
3412       const BuiltinType *BT = ValType->getAs<BuiltinType>();
3413       if (!BT || (BT->getKind() != BuiltinType::Int &&
3414                   BT->getKind() != BuiltinType::UInt)) {
3415         Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3416         return ExprError();
3417       }
3418     }
3419     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
3420       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3421         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3422       return ExprError();
3423     }
3424     if (IsC11 && ValType->isPointerType() &&
3425         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3426                             diag::err_incomplete_type)) {
3427       return ExprError();
3428     }
3429   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3430     // For __atomic_*_n operations, the value type must be a scalar integral or
3431     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3432     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3433       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3434     return ExprError();
3435   }
3436 
3437   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3438       !AtomTy->isScalarType()) {
3439     // For GNU atomics, require a trivially-copyable type. This is not part of
3440     // the GNU atomics specification, but we enforce it for sanity.
3441     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3442       << Ptr->getType() << Ptr->getSourceRange();
3443     return ExprError();
3444   }
3445 
3446   switch (ValType.getObjCLifetime()) {
3447   case Qualifiers::OCL_None:
3448   case Qualifiers::OCL_ExplicitNone:
3449     // okay
3450     break;
3451 
3452   case Qualifiers::OCL_Weak:
3453   case Qualifiers::OCL_Strong:
3454   case Qualifiers::OCL_Autoreleasing:
3455     // FIXME: Can this happen? By this point, ValType should be known
3456     // to be trivially copyable.
3457     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3458       << ValType << Ptr->getSourceRange();
3459     return ExprError();
3460   }
3461 
3462   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3463   // volatile-ness of the pointee-type inject itself into the result or the
3464   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3465   ValType.removeLocalVolatile();
3466   ValType.removeLocalConst();
3467   QualType ResultType = ValType;
3468   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3469       Form == Init)
3470     ResultType = Context.VoidTy;
3471   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3472     ResultType = Context.BoolTy;
3473 
3474   // The type of a parameter passed 'by value'. In the GNU atomics, such
3475   // arguments are actually passed as pointers.
3476   QualType ByValType = ValType; // 'CP'
3477   if (!IsC11 && !IsN)
3478     ByValType = Ptr->getType();
3479 
3480   // The first argument --- the pointer --- has a fixed type; we
3481   // deduce the types of the rest of the arguments accordingly.  Walk
3482   // the remaining arguments, converting them to the deduced value type.
3483   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3484     QualType Ty;
3485     if (i < NumVals[Form] + 1) {
3486       switch (i) {
3487       case 1:
3488         // The second argument is the non-atomic operand. For arithmetic, this
3489         // is always passed by value, and for a compare_exchange it is always
3490         // passed by address. For the rest, GNU uses by-address and C11 uses
3491         // by-value.
3492         assert(Form != Load);
3493         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3494           Ty = ValType;
3495         else if (Form == Copy || Form == Xchg)
3496           Ty = ByValType;
3497         else if (Form == Arithmetic)
3498           Ty = Context.getPointerDiffType();
3499         else {
3500           Expr *ValArg = TheCall->getArg(i);
3501           // Treat this argument as _Nonnull as we want to show a warning if
3502           // NULL is passed into it.
3503           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3504           LangAS AS = LangAS::Default;
3505           // Keep address space of non-atomic pointer type.
3506           if (const PointerType *PtrTy =
3507                   ValArg->getType()->getAs<PointerType>()) {
3508             AS = PtrTy->getPointeeType().getAddressSpace();
3509           }
3510           Ty = Context.getPointerType(
3511               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3512         }
3513         break;
3514       case 2:
3515         // The third argument to compare_exchange / GNU exchange is a
3516         // (pointer to a) desired value.
3517         Ty = ByValType;
3518         break;
3519       case 3:
3520         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3521         Ty = Context.BoolTy;
3522         break;
3523       }
3524     } else {
3525       // The order(s) and scope are always converted to int.
3526       Ty = Context.IntTy;
3527     }
3528 
3529     InitializedEntity Entity =
3530         InitializedEntity::InitializeParameter(Context, Ty, false);
3531     ExprResult Arg = TheCall->getArg(i);
3532     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3533     if (Arg.isInvalid())
3534       return true;
3535     TheCall->setArg(i, Arg.get());
3536   }
3537 
3538   // Permute the arguments into a 'consistent' order.
3539   SmallVector<Expr*, 5> SubExprs;
3540   SubExprs.push_back(Ptr);
3541   switch (Form) {
3542   case Init:
3543     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3544     SubExprs.push_back(TheCall->getArg(1)); // Val1
3545     break;
3546   case Load:
3547     SubExprs.push_back(TheCall->getArg(1)); // Order
3548     break;
3549   case LoadCopy:
3550   case Copy:
3551   case Arithmetic:
3552   case Xchg:
3553     SubExprs.push_back(TheCall->getArg(2)); // Order
3554     SubExprs.push_back(TheCall->getArg(1)); // Val1
3555     break;
3556   case GNUXchg:
3557     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3558     SubExprs.push_back(TheCall->getArg(3)); // Order
3559     SubExprs.push_back(TheCall->getArg(1)); // Val1
3560     SubExprs.push_back(TheCall->getArg(2)); // Val2
3561     break;
3562   case C11CmpXchg:
3563     SubExprs.push_back(TheCall->getArg(3)); // Order
3564     SubExprs.push_back(TheCall->getArg(1)); // Val1
3565     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3566     SubExprs.push_back(TheCall->getArg(2)); // Val2
3567     break;
3568   case GNUCmpXchg:
3569     SubExprs.push_back(TheCall->getArg(4)); // Order
3570     SubExprs.push_back(TheCall->getArg(1)); // Val1
3571     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3572     SubExprs.push_back(TheCall->getArg(2)); // Val2
3573     SubExprs.push_back(TheCall->getArg(3)); // Weak
3574     break;
3575   }
3576 
3577   if (SubExprs.size() >= 2 && Form != Init) {
3578     llvm::APSInt Result(32);
3579     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3580         !isValidOrderingForOp(Result.getSExtValue(), Op))
3581       Diag(SubExprs[1]->getLocStart(),
3582            diag::warn_atomic_op_has_invalid_memory_order)
3583           << SubExprs[1]->getSourceRange();
3584   }
3585 
3586   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3587     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3588     llvm::APSInt Result(32);
3589     if (Scope->isIntegerConstantExpr(Result, Context) &&
3590         !ScopeModel->isValid(Result.getZExtValue())) {
3591       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3592           << Scope->getSourceRange();
3593     }
3594     SubExprs.push_back(Scope);
3595   }
3596 
3597   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3598                                             SubExprs, ResultType, Op,
3599                                             TheCall->getRParenLoc());
3600 
3601   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3602        Op == AtomicExpr::AO__c11_atomic_store ||
3603        Op == AtomicExpr::AO__opencl_atomic_load ||
3604        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3605       Context.AtomicUsesUnsupportedLibcall(AE))
3606     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3607         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3608             Op == AtomicExpr::AO__opencl_atomic_load)
3609                 ? 0 : 1);
3610 
3611   return AE;
3612 }
3613 
3614 /// checkBuiltinArgument - Given a call to a builtin function, perform
3615 /// normal type-checking on the given argument, updating the call in
3616 /// place.  This is useful when a builtin function requires custom
3617 /// type-checking for some of its arguments but not necessarily all of
3618 /// them.
3619 ///
3620 /// Returns true on error.
3621 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3622   FunctionDecl *Fn = E->getDirectCallee();
3623   assert(Fn && "builtin call without direct callee!");
3624 
3625   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3626   InitializedEntity Entity =
3627     InitializedEntity::InitializeParameter(S.Context, Param);
3628 
3629   ExprResult Arg = E->getArg(0);
3630   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3631   if (Arg.isInvalid())
3632     return true;
3633 
3634   E->setArg(ArgIndex, Arg.get());
3635   return false;
3636 }
3637 
3638 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3639 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3640 /// type of its first argument.  The main ActOnCallExpr routines have already
3641 /// promoted the types of arguments because all of these calls are prototyped as
3642 /// void(...).
3643 ///
3644 /// This function goes through and does final semantic checking for these
3645 /// builtins,
3646 ExprResult
3647 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3648   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3649   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3650   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3651 
3652   // Ensure that we have at least one argument to do type inference from.
3653   if (TheCall->getNumArgs() < 1) {
3654     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3655       << 0 << 1 << TheCall->getNumArgs()
3656       << TheCall->getCallee()->getSourceRange();
3657     return ExprError();
3658   }
3659 
3660   // Inspect the first argument of the atomic builtin.  This should always be
3661   // a pointer type, whose element is an integral scalar or pointer type.
3662   // Because it is a pointer type, we don't have to worry about any implicit
3663   // casts here.
3664   // FIXME: We don't allow floating point scalars as input.
3665   Expr *FirstArg = TheCall->getArg(0);
3666   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3667   if (FirstArgResult.isInvalid())
3668     return ExprError();
3669   FirstArg = FirstArgResult.get();
3670   TheCall->setArg(0, FirstArg);
3671 
3672   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3673   if (!pointerType) {
3674     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3675       << FirstArg->getType() << FirstArg->getSourceRange();
3676     return ExprError();
3677   }
3678 
3679   QualType ValType = pointerType->getPointeeType();
3680   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3681       !ValType->isBlockPointerType()) {
3682     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3683       << FirstArg->getType() << FirstArg->getSourceRange();
3684     return ExprError();
3685   }
3686 
3687   if (ValType.isConstQualified()) {
3688     Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3689         << FirstArg->getType() << FirstArg->getSourceRange();
3690     return ExprError();
3691   }
3692 
3693   switch (ValType.getObjCLifetime()) {
3694   case Qualifiers::OCL_None:
3695   case Qualifiers::OCL_ExplicitNone:
3696     // okay
3697     break;
3698 
3699   case Qualifiers::OCL_Weak:
3700   case Qualifiers::OCL_Strong:
3701   case Qualifiers::OCL_Autoreleasing:
3702     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3703       << ValType << FirstArg->getSourceRange();
3704     return ExprError();
3705   }
3706 
3707   // Strip any qualifiers off ValType.
3708   ValType = ValType.getUnqualifiedType();
3709 
3710   // The majority of builtins return a value, but a few have special return
3711   // types, so allow them to override appropriately below.
3712   QualType ResultType = ValType;
3713 
3714   // We need to figure out which concrete builtin this maps onto.  For example,
3715   // __sync_fetch_and_add with a 2 byte object turns into
3716   // __sync_fetch_and_add_2.
3717 #define BUILTIN_ROW(x) \
3718   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3719     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3720 
3721   static const unsigned BuiltinIndices[][5] = {
3722     BUILTIN_ROW(__sync_fetch_and_add),
3723     BUILTIN_ROW(__sync_fetch_and_sub),
3724     BUILTIN_ROW(__sync_fetch_and_or),
3725     BUILTIN_ROW(__sync_fetch_and_and),
3726     BUILTIN_ROW(__sync_fetch_and_xor),
3727     BUILTIN_ROW(__sync_fetch_and_nand),
3728 
3729     BUILTIN_ROW(__sync_add_and_fetch),
3730     BUILTIN_ROW(__sync_sub_and_fetch),
3731     BUILTIN_ROW(__sync_and_and_fetch),
3732     BUILTIN_ROW(__sync_or_and_fetch),
3733     BUILTIN_ROW(__sync_xor_and_fetch),
3734     BUILTIN_ROW(__sync_nand_and_fetch),
3735 
3736     BUILTIN_ROW(__sync_val_compare_and_swap),
3737     BUILTIN_ROW(__sync_bool_compare_and_swap),
3738     BUILTIN_ROW(__sync_lock_test_and_set),
3739     BUILTIN_ROW(__sync_lock_release),
3740     BUILTIN_ROW(__sync_swap)
3741   };
3742 #undef BUILTIN_ROW
3743 
3744   // Determine the index of the size.
3745   unsigned SizeIndex;
3746   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3747   case 1: SizeIndex = 0; break;
3748   case 2: SizeIndex = 1; break;
3749   case 4: SizeIndex = 2; break;
3750   case 8: SizeIndex = 3; break;
3751   case 16: SizeIndex = 4; break;
3752   default:
3753     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3754       << FirstArg->getType() << FirstArg->getSourceRange();
3755     return ExprError();
3756   }
3757 
3758   // Each of these builtins has one pointer argument, followed by some number of
3759   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3760   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3761   // as the number of fixed args.
3762   unsigned BuiltinID = FDecl->getBuiltinID();
3763   unsigned BuiltinIndex, NumFixed = 1;
3764   bool WarnAboutSemanticsChange = false;
3765   switch (BuiltinID) {
3766   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3767   case Builtin::BI__sync_fetch_and_add:
3768   case Builtin::BI__sync_fetch_and_add_1:
3769   case Builtin::BI__sync_fetch_and_add_2:
3770   case Builtin::BI__sync_fetch_and_add_4:
3771   case Builtin::BI__sync_fetch_and_add_8:
3772   case Builtin::BI__sync_fetch_and_add_16:
3773     BuiltinIndex = 0;
3774     break;
3775 
3776   case Builtin::BI__sync_fetch_and_sub:
3777   case Builtin::BI__sync_fetch_and_sub_1:
3778   case Builtin::BI__sync_fetch_and_sub_2:
3779   case Builtin::BI__sync_fetch_and_sub_4:
3780   case Builtin::BI__sync_fetch_and_sub_8:
3781   case Builtin::BI__sync_fetch_and_sub_16:
3782     BuiltinIndex = 1;
3783     break;
3784 
3785   case Builtin::BI__sync_fetch_and_or:
3786   case Builtin::BI__sync_fetch_and_or_1:
3787   case Builtin::BI__sync_fetch_and_or_2:
3788   case Builtin::BI__sync_fetch_and_or_4:
3789   case Builtin::BI__sync_fetch_and_or_8:
3790   case Builtin::BI__sync_fetch_and_or_16:
3791     BuiltinIndex = 2;
3792     break;
3793 
3794   case Builtin::BI__sync_fetch_and_and:
3795   case Builtin::BI__sync_fetch_and_and_1:
3796   case Builtin::BI__sync_fetch_and_and_2:
3797   case Builtin::BI__sync_fetch_and_and_4:
3798   case Builtin::BI__sync_fetch_and_and_8:
3799   case Builtin::BI__sync_fetch_and_and_16:
3800     BuiltinIndex = 3;
3801     break;
3802 
3803   case Builtin::BI__sync_fetch_and_xor:
3804   case Builtin::BI__sync_fetch_and_xor_1:
3805   case Builtin::BI__sync_fetch_and_xor_2:
3806   case Builtin::BI__sync_fetch_and_xor_4:
3807   case Builtin::BI__sync_fetch_and_xor_8:
3808   case Builtin::BI__sync_fetch_and_xor_16:
3809     BuiltinIndex = 4;
3810     break;
3811 
3812   case Builtin::BI__sync_fetch_and_nand:
3813   case Builtin::BI__sync_fetch_and_nand_1:
3814   case Builtin::BI__sync_fetch_and_nand_2:
3815   case Builtin::BI__sync_fetch_and_nand_4:
3816   case Builtin::BI__sync_fetch_and_nand_8:
3817   case Builtin::BI__sync_fetch_and_nand_16:
3818     BuiltinIndex = 5;
3819     WarnAboutSemanticsChange = true;
3820     break;
3821 
3822   case Builtin::BI__sync_add_and_fetch:
3823   case Builtin::BI__sync_add_and_fetch_1:
3824   case Builtin::BI__sync_add_and_fetch_2:
3825   case Builtin::BI__sync_add_and_fetch_4:
3826   case Builtin::BI__sync_add_and_fetch_8:
3827   case Builtin::BI__sync_add_and_fetch_16:
3828     BuiltinIndex = 6;
3829     break;
3830 
3831   case Builtin::BI__sync_sub_and_fetch:
3832   case Builtin::BI__sync_sub_and_fetch_1:
3833   case Builtin::BI__sync_sub_and_fetch_2:
3834   case Builtin::BI__sync_sub_and_fetch_4:
3835   case Builtin::BI__sync_sub_and_fetch_8:
3836   case Builtin::BI__sync_sub_and_fetch_16:
3837     BuiltinIndex = 7;
3838     break;
3839 
3840   case Builtin::BI__sync_and_and_fetch:
3841   case Builtin::BI__sync_and_and_fetch_1:
3842   case Builtin::BI__sync_and_and_fetch_2:
3843   case Builtin::BI__sync_and_and_fetch_4:
3844   case Builtin::BI__sync_and_and_fetch_8:
3845   case Builtin::BI__sync_and_and_fetch_16:
3846     BuiltinIndex = 8;
3847     break;
3848 
3849   case Builtin::BI__sync_or_and_fetch:
3850   case Builtin::BI__sync_or_and_fetch_1:
3851   case Builtin::BI__sync_or_and_fetch_2:
3852   case Builtin::BI__sync_or_and_fetch_4:
3853   case Builtin::BI__sync_or_and_fetch_8:
3854   case Builtin::BI__sync_or_and_fetch_16:
3855     BuiltinIndex = 9;
3856     break;
3857 
3858   case Builtin::BI__sync_xor_and_fetch:
3859   case Builtin::BI__sync_xor_and_fetch_1:
3860   case Builtin::BI__sync_xor_and_fetch_2:
3861   case Builtin::BI__sync_xor_and_fetch_4:
3862   case Builtin::BI__sync_xor_and_fetch_8:
3863   case Builtin::BI__sync_xor_and_fetch_16:
3864     BuiltinIndex = 10;
3865     break;
3866 
3867   case Builtin::BI__sync_nand_and_fetch:
3868   case Builtin::BI__sync_nand_and_fetch_1:
3869   case Builtin::BI__sync_nand_and_fetch_2:
3870   case Builtin::BI__sync_nand_and_fetch_4:
3871   case Builtin::BI__sync_nand_and_fetch_8:
3872   case Builtin::BI__sync_nand_and_fetch_16:
3873     BuiltinIndex = 11;
3874     WarnAboutSemanticsChange = true;
3875     break;
3876 
3877   case Builtin::BI__sync_val_compare_and_swap:
3878   case Builtin::BI__sync_val_compare_and_swap_1:
3879   case Builtin::BI__sync_val_compare_and_swap_2:
3880   case Builtin::BI__sync_val_compare_and_swap_4:
3881   case Builtin::BI__sync_val_compare_and_swap_8:
3882   case Builtin::BI__sync_val_compare_and_swap_16:
3883     BuiltinIndex = 12;
3884     NumFixed = 2;
3885     break;
3886 
3887   case Builtin::BI__sync_bool_compare_and_swap:
3888   case Builtin::BI__sync_bool_compare_and_swap_1:
3889   case Builtin::BI__sync_bool_compare_and_swap_2:
3890   case Builtin::BI__sync_bool_compare_and_swap_4:
3891   case Builtin::BI__sync_bool_compare_and_swap_8:
3892   case Builtin::BI__sync_bool_compare_and_swap_16:
3893     BuiltinIndex = 13;
3894     NumFixed = 2;
3895     ResultType = Context.BoolTy;
3896     break;
3897 
3898   case Builtin::BI__sync_lock_test_and_set:
3899   case Builtin::BI__sync_lock_test_and_set_1:
3900   case Builtin::BI__sync_lock_test_and_set_2:
3901   case Builtin::BI__sync_lock_test_and_set_4:
3902   case Builtin::BI__sync_lock_test_and_set_8:
3903   case Builtin::BI__sync_lock_test_and_set_16:
3904     BuiltinIndex = 14;
3905     break;
3906 
3907   case Builtin::BI__sync_lock_release:
3908   case Builtin::BI__sync_lock_release_1:
3909   case Builtin::BI__sync_lock_release_2:
3910   case Builtin::BI__sync_lock_release_4:
3911   case Builtin::BI__sync_lock_release_8:
3912   case Builtin::BI__sync_lock_release_16:
3913     BuiltinIndex = 15;
3914     NumFixed = 0;
3915     ResultType = Context.VoidTy;
3916     break;
3917 
3918   case Builtin::BI__sync_swap:
3919   case Builtin::BI__sync_swap_1:
3920   case Builtin::BI__sync_swap_2:
3921   case Builtin::BI__sync_swap_4:
3922   case Builtin::BI__sync_swap_8:
3923   case Builtin::BI__sync_swap_16:
3924     BuiltinIndex = 16;
3925     break;
3926   }
3927 
3928   // Now that we know how many fixed arguments we expect, first check that we
3929   // have at least that many.
3930   if (TheCall->getNumArgs() < 1+NumFixed) {
3931     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3932       << 0 << 1+NumFixed << TheCall->getNumArgs()
3933       << TheCall->getCallee()->getSourceRange();
3934     return ExprError();
3935   }
3936 
3937   if (WarnAboutSemanticsChange) {
3938     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3939       << TheCall->getCallee()->getSourceRange();
3940   }
3941 
3942   // Get the decl for the concrete builtin from this, we can tell what the
3943   // concrete integer type we should convert to is.
3944   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3945   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3946   FunctionDecl *NewBuiltinDecl;
3947   if (NewBuiltinID == BuiltinID)
3948     NewBuiltinDecl = FDecl;
3949   else {
3950     // Perform builtin lookup to avoid redeclaring it.
3951     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3952     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3953     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3954     assert(Res.getFoundDecl());
3955     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3956     if (!NewBuiltinDecl)
3957       return ExprError();
3958   }
3959 
3960   // The first argument --- the pointer --- has a fixed type; we
3961   // deduce the types of the rest of the arguments accordingly.  Walk
3962   // the remaining arguments, converting them to the deduced value type.
3963   for (unsigned i = 0; i != NumFixed; ++i) {
3964     ExprResult Arg = TheCall->getArg(i+1);
3965 
3966     // GCC does an implicit conversion to the pointer or integer ValType.  This
3967     // can fail in some cases (1i -> int**), check for this error case now.
3968     // Initialize the argument.
3969     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3970                                                    ValType, /*consume*/ false);
3971     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3972     if (Arg.isInvalid())
3973       return ExprError();
3974 
3975     // Okay, we have something that *can* be converted to the right type.  Check
3976     // to see if there is a potentially weird extension going on here.  This can
3977     // happen when you do an atomic operation on something like an char* and
3978     // pass in 42.  The 42 gets converted to char.  This is even more strange
3979     // for things like 45.123 -> char, etc.
3980     // FIXME: Do this check.
3981     TheCall->setArg(i+1, Arg.get());
3982   }
3983 
3984   ASTContext& Context = this->getASTContext();
3985 
3986   // Create a new DeclRefExpr to refer to the new decl.
3987   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3988       Context,
3989       DRE->getQualifierLoc(),
3990       SourceLocation(),
3991       NewBuiltinDecl,
3992       /*enclosing*/ false,
3993       DRE->getLocation(),
3994       Context.BuiltinFnTy,
3995       DRE->getValueKind());
3996 
3997   // Set the callee in the CallExpr.
3998   // FIXME: This loses syntactic information.
3999   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4000   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4001                                               CK_BuiltinFnToFnPtr);
4002   TheCall->setCallee(PromotedCall.get());
4003 
4004   // Change the result type of the call to match the original value type. This
4005   // is arbitrary, but the codegen for these builtins ins design to handle it
4006   // gracefully.
4007   TheCall->setType(ResultType);
4008 
4009   return TheCallResult;
4010 }
4011 
4012 /// SemaBuiltinNontemporalOverloaded - We have a call to
4013 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4014 /// overloaded function based on the pointer type of its last argument.
4015 ///
4016 /// This function goes through and does final semantic checking for these
4017 /// builtins.
4018 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4019   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4020   DeclRefExpr *DRE =
4021       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4022   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4023   unsigned BuiltinID = FDecl->getBuiltinID();
4024   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4025           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4026          "Unexpected nontemporal load/store builtin!");
4027   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4028   unsigned numArgs = isStore ? 2 : 1;
4029 
4030   // Ensure that we have the proper number of arguments.
4031   if (checkArgCount(*this, TheCall, numArgs))
4032     return ExprError();
4033 
4034   // Inspect the last argument of the nontemporal builtin.  This should always
4035   // be a pointer type, from which we imply the type of the memory access.
4036   // Because it is a pointer type, we don't have to worry about any implicit
4037   // casts here.
4038   Expr *PointerArg = TheCall->getArg(numArgs - 1);
4039   ExprResult PointerArgResult =
4040       DefaultFunctionArrayLvalueConversion(PointerArg);
4041 
4042   if (PointerArgResult.isInvalid())
4043     return ExprError();
4044   PointerArg = PointerArgResult.get();
4045   TheCall->setArg(numArgs - 1, PointerArg);
4046 
4047   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4048   if (!pointerType) {
4049     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4050         << PointerArg->getType() << PointerArg->getSourceRange();
4051     return ExprError();
4052   }
4053 
4054   QualType ValType = pointerType->getPointeeType();
4055 
4056   // Strip any qualifiers off ValType.
4057   ValType = ValType.getUnqualifiedType();
4058   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4059       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4060       !ValType->isVectorType()) {
4061     Diag(DRE->getLocStart(),
4062          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4063         << PointerArg->getType() << PointerArg->getSourceRange();
4064     return ExprError();
4065   }
4066 
4067   if (!isStore) {
4068     TheCall->setType(ValType);
4069     return TheCallResult;
4070   }
4071 
4072   ExprResult ValArg = TheCall->getArg(0);
4073   InitializedEntity Entity = InitializedEntity::InitializeParameter(
4074       Context, ValType, /*consume*/ false);
4075   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4076   if (ValArg.isInvalid())
4077     return ExprError();
4078 
4079   TheCall->setArg(0, ValArg.get());
4080   TheCall->setType(Context.VoidTy);
4081   return TheCallResult;
4082 }
4083 
4084 /// CheckObjCString - Checks that the argument to the builtin
4085 /// CFString constructor is correct
4086 /// Note: It might also make sense to do the UTF-16 conversion here (would
4087 /// simplify the backend).
4088 bool Sema::CheckObjCString(Expr *Arg) {
4089   Arg = Arg->IgnoreParenCasts();
4090   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4091 
4092   if (!Literal || !Literal->isAscii()) {
4093     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4094       << Arg->getSourceRange();
4095     return true;
4096   }
4097 
4098   if (Literal->containsNonAsciiOrNull()) {
4099     StringRef String = Literal->getString();
4100     unsigned NumBytes = String.size();
4101     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4102     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4103     llvm::UTF16 *ToPtr = &ToBuf[0];
4104 
4105     llvm::ConversionResult Result =
4106         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4107                                  ToPtr + NumBytes, llvm::strictConversion);
4108     // Check for conversion failure.
4109     if (Result != llvm::conversionOK)
4110       Diag(Arg->getLocStart(),
4111            diag::warn_cfstring_truncated) << Arg->getSourceRange();
4112   }
4113   return false;
4114 }
4115 
4116 /// CheckObjCString - Checks that the format string argument to the os_log()
4117 /// and os_trace() functions is correct, and converts it to const char *.
4118 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4119   Arg = Arg->IgnoreParenCasts();
4120   auto *Literal = dyn_cast<StringLiteral>(Arg);
4121   if (!Literal) {
4122     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4123       Literal = ObjcLiteral->getString();
4124     }
4125   }
4126 
4127   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4128     return ExprError(
4129         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4130         << Arg->getSourceRange());
4131   }
4132 
4133   ExprResult Result(Literal);
4134   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4135   InitializedEntity Entity =
4136       InitializedEntity::InitializeParameter(Context, ResultTy, false);
4137   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4138   return Result;
4139 }
4140 
4141 /// Check that the user is calling the appropriate va_start builtin for the
4142 /// target and calling convention.
4143 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4144   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4145   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
4146   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
4147   bool IsWindows = TT.isOSWindows();
4148   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4149   if (IsX64 || IsAArch64) {
4150     CallingConv CC = CC_C;
4151     if (const FunctionDecl *FD = S.getCurFunctionDecl())
4152       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4153     if (IsMSVAStart) {
4154       // Don't allow this in System V ABI functions.
4155       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
4156         return S.Diag(Fn->getLocStart(),
4157                       diag::err_ms_va_start_used_in_sysv_function);
4158     } else {
4159       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
4160       // On x64 Windows, don't allow this in System V ABI functions.
4161       // (Yes, that means there's no corresponding way to support variadic
4162       // System V ABI functions on Windows.)
4163       if ((IsWindows && CC == CC_X86_64SysV) ||
4164           (!IsWindows && CC == CC_Win64))
4165         return S.Diag(Fn->getLocStart(),
4166                       diag::err_va_start_used_in_wrong_abi_function)
4167                << !IsWindows;
4168     }
4169     return false;
4170   }
4171 
4172   if (IsMSVAStart)
4173     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
4174   return false;
4175 }
4176 
4177 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4178                                              ParmVarDecl **LastParam = nullptr) {
4179   // Determine whether the current function, block, or obj-c method is variadic
4180   // and get its parameter list.
4181   bool IsVariadic = false;
4182   ArrayRef<ParmVarDecl *> Params;
4183   DeclContext *Caller = S.CurContext;
4184   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4185     IsVariadic = Block->isVariadic();
4186     Params = Block->parameters();
4187   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
4188     IsVariadic = FD->isVariadic();
4189     Params = FD->parameters();
4190   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
4191     IsVariadic = MD->isVariadic();
4192     // FIXME: This isn't correct for methods (results in bogus warning).
4193     Params = MD->parameters();
4194   } else if (isa<CapturedDecl>(Caller)) {
4195     // We don't support va_start in a CapturedDecl.
4196     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4197     return true;
4198   } else {
4199     // This must be some other declcontext that parses exprs.
4200     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4201     return true;
4202   }
4203 
4204   if (!IsVariadic) {
4205     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
4206     return true;
4207   }
4208 
4209   if (LastParam)
4210     *LastParam = Params.empty() ? nullptr : Params.back();
4211 
4212   return false;
4213 }
4214 
4215 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4216 /// for validity.  Emit an error and return true on failure; return false
4217 /// on success.
4218 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4219   Expr *Fn = TheCall->getCallee();
4220 
4221   if (checkVAStartABI(*this, BuiltinID, Fn))
4222     return true;
4223 
4224   if (TheCall->getNumArgs() > 2) {
4225     Diag(TheCall->getArg(2)->getLocStart(),
4226          diag::err_typecheck_call_too_many_args)
4227       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4228       << Fn->getSourceRange()
4229       << SourceRange(TheCall->getArg(2)->getLocStart(),
4230                      (*(TheCall->arg_end()-1))->getLocEnd());
4231     return true;
4232   }
4233 
4234   if (TheCall->getNumArgs() < 2) {
4235     return Diag(TheCall->getLocEnd(),
4236       diag::err_typecheck_call_too_few_args_at_least)
4237       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
4238   }
4239 
4240   // Type-check the first argument normally.
4241   if (checkBuiltinArgument(*this, TheCall, 0))
4242     return true;
4243 
4244   // Check that the current function is variadic, and get its last parameter.
4245   ParmVarDecl *LastParam;
4246   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4247     return true;
4248 
4249   // Verify that the second argument to the builtin is the last argument of the
4250   // current function or method.
4251   bool SecondArgIsLastNamedArgument = false;
4252   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4253 
4254   // These are valid if SecondArgIsLastNamedArgument is false after the next
4255   // block.
4256   QualType Type;
4257   SourceLocation ParamLoc;
4258   bool IsCRegister = false;
4259 
4260   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4261     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4262       SecondArgIsLastNamedArgument = PV == LastParam;
4263 
4264       Type = PV->getType();
4265       ParamLoc = PV->getLocation();
4266       IsCRegister =
4267           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4268     }
4269   }
4270 
4271   if (!SecondArgIsLastNamedArgument)
4272     Diag(TheCall->getArg(1)->getLocStart(),
4273          diag::warn_second_arg_of_va_start_not_last_named_param);
4274   else if (IsCRegister || Type->isReferenceType() ||
4275            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4276              // Promotable integers are UB, but enumerations need a bit of
4277              // extra checking to see what their promotable type actually is.
4278              if (!Type->isPromotableIntegerType())
4279                return false;
4280              if (!Type->isEnumeralType())
4281                return true;
4282              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4283              return !(ED &&
4284                       Context.typesAreCompatible(ED->getPromotionType(), Type));
4285            }()) {
4286     unsigned Reason = 0;
4287     if (Type->isReferenceType())  Reason = 1;
4288     else if (IsCRegister)         Reason = 2;
4289     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4290     Diag(ParamLoc, diag::note_parameter_type) << Type;
4291   }
4292 
4293   TheCall->setType(Context.VoidTy);
4294   return false;
4295 }
4296 
4297 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4298   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4299   //                 const char *named_addr);
4300 
4301   Expr *Func = Call->getCallee();
4302 
4303   if (Call->getNumArgs() < 3)
4304     return Diag(Call->getLocEnd(),
4305                 diag::err_typecheck_call_too_few_args_at_least)
4306            << 0 /*function call*/ << 3 << Call->getNumArgs();
4307 
4308   // Type-check the first argument normally.
4309   if (checkBuiltinArgument(*this, Call, 0))
4310     return true;
4311 
4312   // Check that the current function is variadic.
4313   if (checkVAStartIsInVariadicFunction(*this, Func))
4314     return true;
4315 
4316   // __va_start on Windows does not validate the parameter qualifiers
4317 
4318   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4319   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4320 
4321   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4322   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4323 
4324   const QualType &ConstCharPtrTy =
4325       Context.getPointerType(Context.CharTy.withConst());
4326   if (!Arg1Ty->isPointerType() ||
4327       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4328     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4329         << Arg1->getType() << ConstCharPtrTy
4330         << 1 /* different class */
4331         << 0 /* qualifier difference */
4332         << 3 /* parameter mismatch */
4333         << 2 << Arg1->getType() << ConstCharPtrTy;
4334 
4335   const QualType SizeTy = Context.getSizeType();
4336   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4337     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4338         << Arg2->getType() << SizeTy
4339         << 1 /* different class */
4340         << 0 /* qualifier difference */
4341         << 3 /* parameter mismatch */
4342         << 3 << Arg2->getType() << SizeTy;
4343 
4344   return false;
4345 }
4346 
4347 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4348 /// friends.  This is declared to take (...), so we have to check everything.
4349 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4350   if (TheCall->getNumArgs() < 2)
4351     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4352       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4353   if (TheCall->getNumArgs() > 2)
4354     return Diag(TheCall->getArg(2)->getLocStart(),
4355                 diag::err_typecheck_call_too_many_args)
4356       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4357       << SourceRange(TheCall->getArg(2)->getLocStart(),
4358                      (*(TheCall->arg_end()-1))->getLocEnd());
4359 
4360   ExprResult OrigArg0 = TheCall->getArg(0);
4361   ExprResult OrigArg1 = TheCall->getArg(1);
4362 
4363   // Do standard promotions between the two arguments, returning their common
4364   // type.
4365   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4366   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4367     return true;
4368 
4369   // Make sure any conversions are pushed back into the call; this is
4370   // type safe since unordered compare builtins are declared as "_Bool
4371   // foo(...)".
4372   TheCall->setArg(0, OrigArg0.get());
4373   TheCall->setArg(1, OrigArg1.get());
4374 
4375   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4376     return false;
4377 
4378   // If the common type isn't a real floating type, then the arguments were
4379   // invalid for this operation.
4380   if (Res.isNull() || !Res->isRealFloatingType())
4381     return Diag(OrigArg0.get()->getLocStart(),
4382                 diag::err_typecheck_call_invalid_ordered_compare)
4383       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4384       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4385 
4386   return false;
4387 }
4388 
4389 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4390 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4391 /// to check everything. We expect the last argument to be a floating point
4392 /// value.
4393 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4394   if (TheCall->getNumArgs() < NumArgs)
4395     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4396       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4397   if (TheCall->getNumArgs() > NumArgs)
4398     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4399                 diag::err_typecheck_call_too_many_args)
4400       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4401       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4402                      (*(TheCall->arg_end()-1))->getLocEnd());
4403 
4404   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4405 
4406   if (OrigArg->isTypeDependent())
4407     return false;
4408 
4409   // This operation requires a non-_Complex floating-point number.
4410   if (!OrigArg->getType()->isRealFloatingType())
4411     return Diag(OrigArg->getLocStart(),
4412                 diag::err_typecheck_call_invalid_unary_fp)
4413       << OrigArg->getType() << OrigArg->getSourceRange();
4414 
4415   // If this is an implicit conversion from float -> float or double, remove it.
4416   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4417     // Only remove standard FloatCasts, leaving other casts inplace
4418     if (Cast->getCastKind() == CK_FloatingCast) {
4419       Expr *CastArg = Cast->getSubExpr();
4420       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4421           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4422                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4423                "promotion from float to either float or double is the only expected cast here");
4424         Cast->setSubExpr(nullptr);
4425         TheCall->setArg(NumArgs-1, CastArg);
4426       }
4427     }
4428   }
4429 
4430   return false;
4431 }
4432 
4433 // Customized Sema Checking for VSX builtins that have the following signature:
4434 // vector [...] builtinName(vector [...], vector [...], const int);
4435 // Which takes the same type of vectors (any legal vector type) for the first
4436 // two arguments and takes compile time constant for the third argument.
4437 // Example builtins are :
4438 // vector double vec_xxpermdi(vector double, vector double, int);
4439 // vector short vec_xxsldwi(vector short, vector short, int);
4440 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4441   unsigned ExpectedNumArgs = 3;
4442   if (TheCall->getNumArgs() < ExpectedNumArgs)
4443     return Diag(TheCall->getLocEnd(),
4444                 diag::err_typecheck_call_too_few_args_at_least)
4445            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4446            << TheCall->getSourceRange();
4447 
4448   if (TheCall->getNumArgs() > ExpectedNumArgs)
4449     return Diag(TheCall->getLocEnd(),
4450                 diag::err_typecheck_call_too_many_args_at_most)
4451            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4452            << TheCall->getSourceRange();
4453 
4454   // Check the third argument is a compile time constant
4455   llvm::APSInt Value;
4456   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4457     return Diag(TheCall->getLocStart(),
4458                 diag::err_vsx_builtin_nonconstant_argument)
4459            << 3 /* argument index */ << TheCall->getDirectCallee()
4460            << SourceRange(TheCall->getArg(2)->getLocStart(),
4461                           TheCall->getArg(2)->getLocEnd());
4462 
4463   QualType Arg1Ty = TheCall->getArg(0)->getType();
4464   QualType Arg2Ty = TheCall->getArg(1)->getType();
4465 
4466   // Check the type of argument 1 and argument 2 are vectors.
4467   SourceLocation BuiltinLoc = TheCall->getLocStart();
4468   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4469       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4470     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4471            << TheCall->getDirectCallee()
4472            << SourceRange(TheCall->getArg(0)->getLocStart(),
4473                           TheCall->getArg(1)->getLocEnd());
4474   }
4475 
4476   // Check the first two arguments are the same type.
4477   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4478     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4479            << TheCall->getDirectCallee()
4480            << SourceRange(TheCall->getArg(0)->getLocStart(),
4481                           TheCall->getArg(1)->getLocEnd());
4482   }
4483 
4484   // When default clang type checking is turned off and the customized type
4485   // checking is used, the returning type of the function must be explicitly
4486   // set. Otherwise it is _Bool by default.
4487   TheCall->setType(Arg1Ty);
4488 
4489   return false;
4490 }
4491 
4492 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4493 // This is declared to take (...), so we have to check everything.
4494 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4495   if (TheCall->getNumArgs() < 2)
4496     return ExprError(Diag(TheCall->getLocEnd(),
4497                           diag::err_typecheck_call_too_few_args_at_least)
4498                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4499                      << TheCall->getSourceRange());
4500 
4501   // Determine which of the following types of shufflevector we're checking:
4502   // 1) unary, vector mask: (lhs, mask)
4503   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4504   QualType resType = TheCall->getArg(0)->getType();
4505   unsigned numElements = 0;
4506 
4507   if (!TheCall->getArg(0)->isTypeDependent() &&
4508       !TheCall->getArg(1)->isTypeDependent()) {
4509     QualType LHSType = TheCall->getArg(0)->getType();
4510     QualType RHSType = TheCall->getArg(1)->getType();
4511 
4512     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4513       return ExprError(Diag(TheCall->getLocStart(),
4514                             diag::err_vec_builtin_non_vector)
4515                        << TheCall->getDirectCallee()
4516                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4517                                       TheCall->getArg(1)->getLocEnd()));
4518 
4519     numElements = LHSType->getAs<VectorType>()->getNumElements();
4520     unsigned numResElements = TheCall->getNumArgs() - 2;
4521 
4522     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4523     // with mask.  If so, verify that RHS is an integer vector type with the
4524     // same number of elts as lhs.
4525     if (TheCall->getNumArgs() == 2) {
4526       if (!RHSType->hasIntegerRepresentation() ||
4527           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4528         return ExprError(Diag(TheCall->getLocStart(),
4529                               diag::err_vec_builtin_incompatible_vector)
4530                          << TheCall->getDirectCallee()
4531                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4532                                         TheCall->getArg(1)->getLocEnd()));
4533     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4534       return ExprError(Diag(TheCall->getLocStart(),
4535                             diag::err_vec_builtin_incompatible_vector)
4536                        << TheCall->getDirectCallee()
4537                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4538                                       TheCall->getArg(1)->getLocEnd()));
4539     } else if (numElements != numResElements) {
4540       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4541       resType = Context.getVectorType(eltType, numResElements,
4542                                       VectorType::GenericVector);
4543     }
4544   }
4545 
4546   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4547     if (TheCall->getArg(i)->isTypeDependent() ||
4548         TheCall->getArg(i)->isValueDependent())
4549       continue;
4550 
4551     llvm::APSInt Result(32);
4552     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4553       return ExprError(Diag(TheCall->getLocStart(),
4554                             diag::err_shufflevector_nonconstant_argument)
4555                        << TheCall->getArg(i)->getSourceRange());
4556 
4557     // Allow -1 which will be translated to undef in the IR.
4558     if (Result.isSigned() && Result.isAllOnesValue())
4559       continue;
4560 
4561     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4562       return ExprError(Diag(TheCall->getLocStart(),
4563                             diag::err_shufflevector_argument_too_large)
4564                        << TheCall->getArg(i)->getSourceRange());
4565   }
4566 
4567   SmallVector<Expr*, 32> exprs;
4568 
4569   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4570     exprs.push_back(TheCall->getArg(i));
4571     TheCall->setArg(i, nullptr);
4572   }
4573 
4574   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4575                                          TheCall->getCallee()->getLocStart(),
4576                                          TheCall->getRParenLoc());
4577 }
4578 
4579 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4580 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4581                                        SourceLocation BuiltinLoc,
4582                                        SourceLocation RParenLoc) {
4583   ExprValueKind VK = VK_RValue;
4584   ExprObjectKind OK = OK_Ordinary;
4585   QualType DstTy = TInfo->getType();
4586   QualType SrcTy = E->getType();
4587 
4588   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4589     return ExprError(Diag(BuiltinLoc,
4590                           diag::err_convertvector_non_vector)
4591                      << E->getSourceRange());
4592   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4593     return ExprError(Diag(BuiltinLoc,
4594                           diag::err_convertvector_non_vector_type));
4595 
4596   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4597     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4598     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4599     if (SrcElts != DstElts)
4600       return ExprError(Diag(BuiltinLoc,
4601                             diag::err_convertvector_incompatible_vector)
4602                        << E->getSourceRange());
4603   }
4604 
4605   return new (Context)
4606       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4607 }
4608 
4609 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4610 // This is declared to take (const void*, ...) and can take two
4611 // optional constant int args.
4612 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4613   unsigned NumArgs = TheCall->getNumArgs();
4614 
4615   if (NumArgs > 3)
4616     return Diag(TheCall->getLocEnd(),
4617              diag::err_typecheck_call_too_many_args_at_most)
4618              << 0 /*function call*/ << 3 << NumArgs
4619              << TheCall->getSourceRange();
4620 
4621   // Argument 0 is checked for us and the remaining arguments must be
4622   // constant integers.
4623   for (unsigned i = 1; i != NumArgs; ++i)
4624     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4625       return true;
4626 
4627   return false;
4628 }
4629 
4630 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4631 // __assume does not evaluate its arguments, and should warn if its argument
4632 // has side effects.
4633 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4634   Expr *Arg = TheCall->getArg(0);
4635   if (Arg->isInstantiationDependent()) return false;
4636 
4637   if (Arg->HasSideEffects(Context))
4638     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4639       << Arg->getSourceRange()
4640       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4641 
4642   return false;
4643 }
4644 
4645 /// Handle __builtin_alloca_with_align. This is declared
4646 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4647 /// than 8.
4648 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4649   // The alignment must be a constant integer.
4650   Expr *Arg = TheCall->getArg(1);
4651 
4652   // We can't check the value of a dependent argument.
4653   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4654     if (const auto *UE =
4655             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4656       if (UE->getKind() == UETT_AlignOf)
4657         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4658           << Arg->getSourceRange();
4659 
4660     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4661 
4662     if (!Result.isPowerOf2())
4663       return Diag(TheCall->getLocStart(),
4664                   diag::err_alignment_not_power_of_two)
4665            << Arg->getSourceRange();
4666 
4667     if (Result < Context.getCharWidth())
4668       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4669            << (unsigned)Context.getCharWidth()
4670            << Arg->getSourceRange();
4671 
4672     if (Result > std::numeric_limits<int32_t>::max())
4673       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4674            << std::numeric_limits<int32_t>::max()
4675            << Arg->getSourceRange();
4676   }
4677 
4678   return false;
4679 }
4680 
4681 /// Handle __builtin_assume_aligned. This is declared
4682 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4683 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4684   unsigned NumArgs = TheCall->getNumArgs();
4685 
4686   if (NumArgs > 3)
4687     return Diag(TheCall->getLocEnd(),
4688              diag::err_typecheck_call_too_many_args_at_most)
4689              << 0 /*function call*/ << 3 << NumArgs
4690              << TheCall->getSourceRange();
4691 
4692   // The alignment must be a constant integer.
4693   Expr *Arg = TheCall->getArg(1);
4694 
4695   // We can't check the value of a dependent argument.
4696   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4697     llvm::APSInt Result;
4698     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4699       return true;
4700 
4701     if (!Result.isPowerOf2())
4702       return Diag(TheCall->getLocStart(),
4703                   diag::err_alignment_not_power_of_two)
4704            << Arg->getSourceRange();
4705   }
4706 
4707   if (NumArgs > 2) {
4708     ExprResult Arg(TheCall->getArg(2));
4709     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4710       Context.getSizeType(), false);
4711     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4712     if (Arg.isInvalid()) return true;
4713     TheCall->setArg(2, Arg.get());
4714   }
4715 
4716   return false;
4717 }
4718 
4719 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4720   unsigned BuiltinID =
4721       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4722   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4723 
4724   unsigned NumArgs = TheCall->getNumArgs();
4725   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4726   if (NumArgs < NumRequiredArgs) {
4727     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4728            << 0 /* function call */ << NumRequiredArgs << NumArgs
4729            << TheCall->getSourceRange();
4730   }
4731   if (NumArgs >= NumRequiredArgs + 0x100) {
4732     return Diag(TheCall->getLocEnd(),
4733                 diag::err_typecheck_call_too_many_args_at_most)
4734            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4735            << TheCall->getSourceRange();
4736   }
4737   unsigned i = 0;
4738 
4739   // For formatting call, check buffer arg.
4740   if (!IsSizeCall) {
4741     ExprResult Arg(TheCall->getArg(i));
4742     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4743         Context, Context.VoidPtrTy, false);
4744     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4745     if (Arg.isInvalid())
4746       return true;
4747     TheCall->setArg(i, Arg.get());
4748     i++;
4749   }
4750 
4751   // Check string literal arg.
4752   unsigned FormatIdx = i;
4753   {
4754     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4755     if (Arg.isInvalid())
4756       return true;
4757     TheCall->setArg(i, Arg.get());
4758     i++;
4759   }
4760 
4761   // Make sure variadic args are scalar.
4762   unsigned FirstDataArg = i;
4763   while (i < NumArgs) {
4764     ExprResult Arg = DefaultVariadicArgumentPromotion(
4765         TheCall->getArg(i), VariadicFunction, nullptr);
4766     if (Arg.isInvalid())
4767       return true;
4768     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4769     if (ArgSize.getQuantity() >= 0x100) {
4770       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4771              << i << (int)ArgSize.getQuantity() << 0xff
4772              << TheCall->getSourceRange();
4773     }
4774     TheCall->setArg(i, Arg.get());
4775     i++;
4776   }
4777 
4778   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4779   // call to avoid duplicate diagnostics.
4780   if (!IsSizeCall) {
4781     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4782     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4783     bool Success = CheckFormatArguments(
4784         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4785         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4786         CheckedVarArgs);
4787     if (!Success)
4788       return true;
4789   }
4790 
4791   if (IsSizeCall) {
4792     TheCall->setType(Context.getSizeType());
4793   } else {
4794     TheCall->setType(Context.VoidPtrTy);
4795   }
4796   return false;
4797 }
4798 
4799 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4800 /// TheCall is a constant expression.
4801 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4802                                   llvm::APSInt &Result) {
4803   Expr *Arg = TheCall->getArg(ArgNum);
4804   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4805   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4806 
4807   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4808 
4809   if (!Arg->isIntegerConstantExpr(Result, Context))
4810     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4811                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4812 
4813   return false;
4814 }
4815 
4816 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4817 /// TheCall is a constant expression in the range [Low, High].
4818 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4819                                        int Low, int High) {
4820   llvm::APSInt Result;
4821 
4822   // We can't check the value of a dependent argument.
4823   Expr *Arg = TheCall->getArg(ArgNum);
4824   if (Arg->isTypeDependent() || Arg->isValueDependent())
4825     return false;
4826 
4827   // Check constant-ness first.
4828   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4829     return true;
4830 
4831   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4832     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4833       << Low << High << Arg->getSourceRange();
4834 
4835   return false;
4836 }
4837 
4838 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4839 /// TheCall is a constant expression is a multiple of Num..
4840 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4841                                           unsigned Num) {
4842   llvm::APSInt Result;
4843 
4844   // We can't check the value of a dependent argument.
4845   Expr *Arg = TheCall->getArg(ArgNum);
4846   if (Arg->isTypeDependent() || Arg->isValueDependent())
4847     return false;
4848 
4849   // Check constant-ness first.
4850   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4851     return true;
4852 
4853   if (Result.getSExtValue() % Num != 0)
4854     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4855       << Num << Arg->getSourceRange();
4856 
4857   return false;
4858 }
4859 
4860 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4861 /// TheCall is an ARM/AArch64 special register string literal.
4862 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4863                                     int ArgNum, unsigned ExpectedFieldNum,
4864                                     bool AllowName) {
4865   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4866                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4867                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4868                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4869                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4870                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4871   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4872                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4873                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4874                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4875                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4876                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4877   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4878 
4879   // We can't check the value of a dependent argument.
4880   Expr *Arg = TheCall->getArg(ArgNum);
4881   if (Arg->isTypeDependent() || Arg->isValueDependent())
4882     return false;
4883 
4884   // Check if the argument is a string literal.
4885   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4886     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4887            << Arg->getSourceRange();
4888 
4889   // Check the type of special register given.
4890   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4891   SmallVector<StringRef, 6> Fields;
4892   Reg.split(Fields, ":");
4893 
4894   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4895     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4896            << Arg->getSourceRange();
4897 
4898   // If the string is the name of a register then we cannot check that it is
4899   // valid here but if the string is of one the forms described in ACLE then we
4900   // can check that the supplied fields are integers and within the valid
4901   // ranges.
4902   if (Fields.size() > 1) {
4903     bool FiveFields = Fields.size() == 5;
4904 
4905     bool ValidString = true;
4906     if (IsARMBuiltin) {
4907       ValidString &= Fields[0].startswith_lower("cp") ||
4908                      Fields[0].startswith_lower("p");
4909       if (ValidString)
4910         Fields[0] =
4911           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4912 
4913       ValidString &= Fields[2].startswith_lower("c");
4914       if (ValidString)
4915         Fields[2] = Fields[2].drop_front(1);
4916 
4917       if (FiveFields) {
4918         ValidString &= Fields[3].startswith_lower("c");
4919         if (ValidString)
4920           Fields[3] = Fields[3].drop_front(1);
4921       }
4922     }
4923 
4924     SmallVector<int, 5> Ranges;
4925     if (FiveFields)
4926       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4927     else
4928       Ranges.append({15, 7, 15});
4929 
4930     for (unsigned i=0; i<Fields.size(); ++i) {
4931       int IntField;
4932       ValidString &= !Fields[i].getAsInteger(10, IntField);
4933       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4934     }
4935 
4936     if (!ValidString)
4937       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4938              << Arg->getSourceRange();
4939   } else if (IsAArch64Builtin && Fields.size() == 1) {
4940     // If the register name is one of those that appear in the condition below
4941     // and the special register builtin being used is one of the write builtins,
4942     // then we require that the argument provided for writing to the register
4943     // is an integer constant expression. This is because it will be lowered to
4944     // an MSR (immediate) instruction, so we need to know the immediate at
4945     // compile time.
4946     if (TheCall->getNumArgs() != 2)
4947       return false;
4948 
4949     std::string RegLower = Reg.lower();
4950     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4951         RegLower != "pan" && RegLower != "uao")
4952       return false;
4953 
4954     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4955   }
4956 
4957   return false;
4958 }
4959 
4960 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4961 /// This checks that the target supports __builtin_longjmp and
4962 /// that val is a constant 1.
4963 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4964   if (!Context.getTargetInfo().hasSjLjLowering())
4965     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4966              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4967 
4968   Expr *Arg = TheCall->getArg(1);
4969   llvm::APSInt Result;
4970 
4971   // TODO: This is less than ideal. Overload this to take a value.
4972   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4973     return true;
4974 
4975   if (Result != 1)
4976     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4977              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4978 
4979   return false;
4980 }
4981 
4982 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4983 /// This checks that the target supports __builtin_setjmp.
4984 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4985   if (!Context.getTargetInfo().hasSjLjLowering())
4986     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4987              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4988   return false;
4989 }
4990 
4991 namespace {
4992 
4993 class UncoveredArgHandler {
4994   enum { Unknown = -1, AllCovered = -2 };
4995 
4996   signed FirstUncoveredArg = Unknown;
4997   SmallVector<const Expr *, 4> DiagnosticExprs;
4998 
4999 public:
5000   UncoveredArgHandler() = default;
5001 
5002   bool hasUncoveredArg() const {
5003     return (FirstUncoveredArg >= 0);
5004   }
5005 
5006   unsigned getUncoveredArg() const {
5007     assert(hasUncoveredArg() && "no uncovered argument");
5008     return FirstUncoveredArg;
5009   }
5010 
5011   void setAllCovered() {
5012     // A string has been found with all arguments covered, so clear out
5013     // the diagnostics.
5014     DiagnosticExprs.clear();
5015     FirstUncoveredArg = AllCovered;
5016   }
5017 
5018   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5019     assert(NewFirstUncoveredArg >= 0 && "Outside range");
5020 
5021     // Don't update if a previous string covers all arguments.
5022     if (FirstUncoveredArg == AllCovered)
5023       return;
5024 
5025     // UncoveredArgHandler tracks the highest uncovered argument index
5026     // and with it all the strings that match this index.
5027     if (NewFirstUncoveredArg == FirstUncoveredArg)
5028       DiagnosticExprs.push_back(StrExpr);
5029     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5030       DiagnosticExprs.clear();
5031       DiagnosticExprs.push_back(StrExpr);
5032       FirstUncoveredArg = NewFirstUncoveredArg;
5033     }
5034   }
5035 
5036   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5037 };
5038 
5039 enum StringLiteralCheckType {
5040   SLCT_NotALiteral,
5041   SLCT_UncheckedLiteral,
5042   SLCT_CheckedLiteral
5043 };
5044 
5045 } // namespace
5046 
5047 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5048                                      BinaryOperatorKind BinOpKind,
5049                                      bool AddendIsRight) {
5050   unsigned BitWidth = Offset.getBitWidth();
5051   unsigned AddendBitWidth = Addend.getBitWidth();
5052   // There might be negative interim results.
5053   if (Addend.isUnsigned()) {
5054     Addend = Addend.zext(++AddendBitWidth);
5055     Addend.setIsSigned(true);
5056   }
5057   // Adjust the bit width of the APSInts.
5058   if (AddendBitWidth > BitWidth) {
5059     Offset = Offset.sext(AddendBitWidth);
5060     BitWidth = AddendBitWidth;
5061   } else if (BitWidth > AddendBitWidth) {
5062     Addend = Addend.sext(BitWidth);
5063   }
5064 
5065   bool Ov = false;
5066   llvm::APSInt ResOffset = Offset;
5067   if (BinOpKind == BO_Add)
5068     ResOffset = Offset.sadd_ov(Addend, Ov);
5069   else {
5070     assert(AddendIsRight && BinOpKind == BO_Sub &&
5071            "operator must be add or sub with addend on the right");
5072     ResOffset = Offset.ssub_ov(Addend, Ov);
5073   }
5074 
5075   // We add an offset to a pointer here so we should support an offset as big as
5076   // possible.
5077   if (Ov) {
5078     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5079            "index (intermediate) result too big");
5080     Offset = Offset.sext(2 * BitWidth);
5081     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5082     return;
5083   }
5084 
5085   Offset = ResOffset;
5086 }
5087 
5088 namespace {
5089 
5090 // This is a wrapper class around StringLiteral to support offsetted string
5091 // literals as format strings. It takes the offset into account when returning
5092 // the string and its length or the source locations to display notes correctly.
5093 class FormatStringLiteral {
5094   const StringLiteral *FExpr;
5095   int64_t Offset;
5096 
5097  public:
5098   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5099       : FExpr(fexpr), Offset(Offset) {}
5100 
5101   StringRef getString() const {
5102     return FExpr->getString().drop_front(Offset);
5103   }
5104 
5105   unsigned getByteLength() const {
5106     return FExpr->getByteLength() - getCharByteWidth() * Offset;
5107   }
5108 
5109   unsigned getLength() const { return FExpr->getLength() - Offset; }
5110   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5111 
5112   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5113 
5114   QualType getType() const { return FExpr->getType(); }
5115 
5116   bool isAscii() const { return FExpr->isAscii(); }
5117   bool isWide() const { return FExpr->isWide(); }
5118   bool isUTF8() const { return FExpr->isUTF8(); }
5119   bool isUTF16() const { return FExpr->isUTF16(); }
5120   bool isUTF32() const { return FExpr->isUTF32(); }
5121   bool isPascal() const { return FExpr->isPascal(); }
5122 
5123   SourceLocation getLocationOfByte(
5124       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5125       const TargetInfo &Target, unsigned *StartToken = nullptr,
5126       unsigned *StartTokenByteOffset = nullptr) const {
5127     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5128                                     StartToken, StartTokenByteOffset);
5129   }
5130 
5131   SourceLocation getLocStart() const LLVM_READONLY {
5132     return FExpr->getLocStart().getLocWithOffset(Offset);
5133   }
5134 
5135   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5136 };
5137 
5138 }  // namespace
5139 
5140 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
5141                               const Expr *OrigFormatExpr,
5142                               ArrayRef<const Expr *> Args,
5143                               bool HasVAListArg, unsigned format_idx,
5144                               unsigned firstDataArg,
5145                               Sema::FormatStringType Type,
5146                               bool inFunctionCall,
5147                               Sema::VariadicCallType CallType,
5148                               llvm::SmallBitVector &CheckedVarArgs,
5149                               UncoveredArgHandler &UncoveredArg);
5150 
5151 // Determine if an expression is a string literal or constant string.
5152 // If this function returns false on the arguments to a function expecting a
5153 // format string, we will usually need to emit a warning.
5154 // True string literals are then checked by CheckFormatString.
5155 static StringLiteralCheckType
5156 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5157                       bool HasVAListArg, unsigned format_idx,
5158                       unsigned firstDataArg, Sema::FormatStringType Type,
5159                       Sema::VariadicCallType CallType, bool InFunctionCall,
5160                       llvm::SmallBitVector &CheckedVarArgs,
5161                       UncoveredArgHandler &UncoveredArg,
5162                       llvm::APSInt Offset) {
5163  tryAgain:
5164   assert(Offset.isSigned() && "invalid offset");
5165 
5166   if (E->isTypeDependent() || E->isValueDependent())
5167     return SLCT_NotALiteral;
5168 
5169   E = E->IgnoreParenCasts();
5170 
5171   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
5172     // Technically -Wformat-nonliteral does not warn about this case.
5173     // The behavior of printf and friends in this case is implementation
5174     // dependent.  Ideally if the format string cannot be null then
5175     // it should have a 'nonnull' attribute in the function prototype.
5176     return SLCT_UncheckedLiteral;
5177 
5178   switch (E->getStmtClass()) {
5179   case Stmt::BinaryConditionalOperatorClass:
5180   case Stmt::ConditionalOperatorClass: {
5181     // The expression is a literal if both sub-expressions were, and it was
5182     // completely checked only if both sub-expressions were checked.
5183     const AbstractConditionalOperator *C =
5184         cast<AbstractConditionalOperator>(E);
5185 
5186     // Determine whether it is necessary to check both sub-expressions, for
5187     // example, because the condition expression is a constant that can be
5188     // evaluated at compile time.
5189     bool CheckLeft = true, CheckRight = true;
5190 
5191     bool Cond;
5192     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5193       if (Cond)
5194         CheckRight = false;
5195       else
5196         CheckLeft = false;
5197     }
5198 
5199     // We need to maintain the offsets for the right and the left hand side
5200     // separately to check if every possible indexed expression is a valid
5201     // string literal. They might have different offsets for different string
5202     // literals in the end.
5203     StringLiteralCheckType Left;
5204     if (!CheckLeft)
5205       Left = SLCT_UncheckedLiteral;
5206     else {
5207       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5208                                    HasVAListArg, format_idx, firstDataArg,
5209                                    Type, CallType, InFunctionCall,
5210                                    CheckedVarArgs, UncoveredArg, Offset);
5211       if (Left == SLCT_NotALiteral || !CheckRight) {
5212         return Left;
5213       }
5214     }
5215 
5216     StringLiteralCheckType Right =
5217         checkFormatStringExpr(S, C->getFalseExpr(), Args,
5218                               HasVAListArg, format_idx, firstDataArg,
5219                               Type, CallType, InFunctionCall, CheckedVarArgs,
5220                               UncoveredArg, Offset);
5221 
5222     return (CheckLeft && Left < Right) ? Left : Right;
5223   }
5224 
5225   case Stmt::ImplicitCastExprClass:
5226     E = cast<ImplicitCastExpr>(E)->getSubExpr();
5227     goto tryAgain;
5228 
5229   case Stmt::OpaqueValueExprClass:
5230     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5231       E = src;
5232       goto tryAgain;
5233     }
5234     return SLCT_NotALiteral;
5235 
5236   case Stmt::PredefinedExprClass:
5237     // While __func__, etc., are technically not string literals, they
5238     // cannot contain format specifiers and thus are not a security
5239     // liability.
5240     return SLCT_UncheckedLiteral;
5241 
5242   case Stmt::DeclRefExprClass: {
5243     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
5244 
5245     // As an exception, do not flag errors for variables binding to
5246     // const string literals.
5247     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5248       bool isConstant = false;
5249       QualType T = DR->getType();
5250 
5251       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5252         isConstant = AT->getElementType().isConstant(S.Context);
5253       } else if (const PointerType *PT = T->getAs<PointerType>()) {
5254         isConstant = T.isConstant(S.Context) &&
5255                      PT->getPointeeType().isConstant(S.Context);
5256       } else if (T->isObjCObjectPointerType()) {
5257         // In ObjC, there is usually no "const ObjectPointer" type,
5258         // so don't check if the pointee type is constant.
5259         isConstant = T.isConstant(S.Context);
5260       }
5261 
5262       if (isConstant) {
5263         if (const Expr *Init = VD->getAnyInitializer()) {
5264           // Look through initializers like const char c[] = { "foo" }
5265           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5266             if (InitList->isStringLiteralInit())
5267               Init = InitList->getInit(0)->IgnoreParenImpCasts();
5268           }
5269           return checkFormatStringExpr(S, Init, Args,
5270                                        HasVAListArg, format_idx,
5271                                        firstDataArg, Type, CallType,
5272                                        /*InFunctionCall*/ false, CheckedVarArgs,
5273                                        UncoveredArg, Offset);
5274         }
5275       }
5276 
5277       // For vprintf* functions (i.e., HasVAListArg==true), we add a
5278       // special check to see if the format string is a function parameter
5279       // of the function calling the printf function.  If the function
5280       // has an attribute indicating it is a printf-like function, then we
5281       // should suppress warnings concerning non-literals being used in a call
5282       // to a vprintf function.  For example:
5283       //
5284       // void
5285       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5286       //      va_list ap;
5287       //      va_start(ap, fmt);
5288       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
5289       //      ...
5290       // }
5291       if (HasVAListArg) {
5292         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5293           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5294             int PVIndex = PV->getFunctionScopeIndex() + 1;
5295             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
5296               // adjust for implicit parameter
5297               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5298                 if (MD->isInstance())
5299                   ++PVIndex;
5300               // We also check if the formats are compatible.
5301               // We can't pass a 'scanf' string to a 'printf' function.
5302               if (PVIndex == PVFormat->getFormatIdx() &&
5303                   Type == S.GetFormatStringType(PVFormat))
5304                 return SLCT_UncheckedLiteral;
5305             }
5306           }
5307         }
5308       }
5309     }
5310 
5311     return SLCT_NotALiteral;
5312   }
5313 
5314   case Stmt::CallExprClass:
5315   case Stmt::CXXMemberCallExprClass: {
5316     const CallExpr *CE = cast<CallExpr>(E);
5317     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5318       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5319         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5320         return checkFormatStringExpr(S, Arg, Args,
5321                                      HasVAListArg, format_idx, firstDataArg,
5322                                      Type, CallType, InFunctionCall,
5323                                      CheckedVarArgs, UncoveredArg, Offset);
5324       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5325         unsigned BuiltinID = FD->getBuiltinID();
5326         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5327             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5328           const Expr *Arg = CE->getArg(0);
5329           return checkFormatStringExpr(S, Arg, Args,
5330                                        HasVAListArg, format_idx,
5331                                        firstDataArg, Type, CallType,
5332                                        InFunctionCall, CheckedVarArgs,
5333                                        UncoveredArg, Offset);
5334         }
5335       }
5336     }
5337 
5338     return SLCT_NotALiteral;
5339   }
5340   case Stmt::ObjCMessageExprClass: {
5341     const auto *ME = cast<ObjCMessageExpr>(E);
5342     if (const auto *ND = ME->getMethodDecl()) {
5343       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5344         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5345         return checkFormatStringExpr(
5346             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5347             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5348       }
5349     }
5350 
5351     return SLCT_NotALiteral;
5352   }
5353   case Stmt::ObjCStringLiteralClass:
5354   case Stmt::StringLiteralClass: {
5355     const StringLiteral *StrE = nullptr;
5356 
5357     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5358       StrE = ObjCFExpr->getString();
5359     else
5360       StrE = cast<StringLiteral>(E);
5361 
5362     if (StrE) {
5363       if (Offset.isNegative() || Offset > StrE->getLength()) {
5364         // TODO: It would be better to have an explicit warning for out of
5365         // bounds literals.
5366         return SLCT_NotALiteral;
5367       }
5368       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5369       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5370                         firstDataArg, Type, InFunctionCall, CallType,
5371                         CheckedVarArgs, UncoveredArg);
5372       return SLCT_CheckedLiteral;
5373     }
5374 
5375     return SLCT_NotALiteral;
5376   }
5377   case Stmt::BinaryOperatorClass: {
5378     llvm::APSInt LResult;
5379     llvm::APSInt RResult;
5380 
5381     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5382 
5383     // A string literal + an int offset is still a string literal.
5384     if (BinOp->isAdditiveOp()) {
5385       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5386       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5387 
5388       if (LIsInt != RIsInt) {
5389         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5390 
5391         if (LIsInt) {
5392           if (BinOpKind == BO_Add) {
5393             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5394             E = BinOp->getRHS();
5395             goto tryAgain;
5396           }
5397         } else {
5398           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5399           E = BinOp->getLHS();
5400           goto tryAgain;
5401         }
5402       }
5403     }
5404 
5405     return SLCT_NotALiteral;
5406   }
5407   case Stmt::UnaryOperatorClass: {
5408     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5409     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5410     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5411       llvm::APSInt IndexResult;
5412       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5413         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5414         E = ASE->getBase();
5415         goto tryAgain;
5416       }
5417     }
5418 
5419     return SLCT_NotALiteral;
5420   }
5421 
5422   default:
5423     return SLCT_NotALiteral;
5424   }
5425 }
5426 
5427 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5428   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5429       .Case("scanf", FST_Scanf)
5430       .Cases("printf", "printf0", FST_Printf)
5431       .Cases("NSString", "CFString", FST_NSString)
5432       .Case("strftime", FST_Strftime)
5433       .Case("strfmon", FST_Strfmon)
5434       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5435       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5436       .Case("os_trace", FST_OSLog)
5437       .Case("os_log", FST_OSLog)
5438       .Default(FST_Unknown);
5439 }
5440 
5441 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5442 /// functions) for correct use of format strings.
5443 /// Returns true if a format string has been fully checked.
5444 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5445                                 ArrayRef<const Expr *> Args,
5446                                 bool IsCXXMember,
5447                                 VariadicCallType CallType,
5448                                 SourceLocation Loc, SourceRange Range,
5449                                 llvm::SmallBitVector &CheckedVarArgs) {
5450   FormatStringInfo FSI;
5451   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5452     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5453                                 FSI.FirstDataArg, GetFormatStringType(Format),
5454                                 CallType, Loc, Range, CheckedVarArgs);
5455   return false;
5456 }
5457 
5458 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5459                                 bool HasVAListArg, unsigned format_idx,
5460                                 unsigned firstDataArg, FormatStringType Type,
5461                                 VariadicCallType CallType,
5462                                 SourceLocation Loc, SourceRange Range,
5463                                 llvm::SmallBitVector &CheckedVarArgs) {
5464   // CHECK: printf/scanf-like function is called with no format string.
5465   if (format_idx >= Args.size()) {
5466     Diag(Loc, diag::warn_missing_format_string) << Range;
5467     return false;
5468   }
5469 
5470   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5471 
5472   // CHECK: format string is not a string literal.
5473   //
5474   // Dynamically generated format strings are difficult to
5475   // automatically vet at compile time.  Requiring that format strings
5476   // are string literals: (1) permits the checking of format strings by
5477   // the compiler and thereby (2) can practically remove the source of
5478   // many format string exploits.
5479 
5480   // Format string can be either ObjC string (e.g. @"%d") or
5481   // C string (e.g. "%d")
5482   // ObjC string uses the same format specifiers as C string, so we can use
5483   // the same format string checking logic for both ObjC and C strings.
5484   UncoveredArgHandler UncoveredArg;
5485   StringLiteralCheckType CT =
5486       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5487                             format_idx, firstDataArg, Type, CallType,
5488                             /*IsFunctionCall*/ true, CheckedVarArgs,
5489                             UncoveredArg,
5490                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5491 
5492   // Generate a diagnostic where an uncovered argument is detected.
5493   if (UncoveredArg.hasUncoveredArg()) {
5494     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5495     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5496     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5497   }
5498 
5499   if (CT != SLCT_NotALiteral)
5500     // Literal format string found, check done!
5501     return CT == SLCT_CheckedLiteral;
5502 
5503   // Strftime is particular as it always uses a single 'time' argument,
5504   // so it is safe to pass a non-literal string.
5505   if (Type == FST_Strftime)
5506     return false;
5507 
5508   // Do not emit diag when the string param is a macro expansion and the
5509   // format is either NSString or CFString. This is a hack to prevent
5510   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5511   // which are usually used in place of NS and CF string literals.
5512   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5513   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5514     return false;
5515 
5516   // If there are no arguments specified, warn with -Wformat-security, otherwise
5517   // warn only with -Wformat-nonliteral.
5518   if (Args.size() == firstDataArg) {
5519     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5520       << OrigFormatExpr->getSourceRange();
5521     switch (Type) {
5522     default:
5523       break;
5524     case FST_Kprintf:
5525     case FST_FreeBSDKPrintf:
5526     case FST_Printf:
5527       Diag(FormatLoc, diag::note_format_security_fixit)
5528         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5529       break;
5530     case FST_NSString:
5531       Diag(FormatLoc, diag::note_format_security_fixit)
5532         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5533       break;
5534     }
5535   } else {
5536     Diag(FormatLoc, diag::warn_format_nonliteral)
5537       << OrigFormatExpr->getSourceRange();
5538   }
5539   return false;
5540 }
5541 
5542 namespace {
5543 
5544 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5545 protected:
5546   Sema &S;
5547   const FormatStringLiteral *FExpr;
5548   const Expr *OrigFormatExpr;
5549   const Sema::FormatStringType FSType;
5550   const unsigned FirstDataArg;
5551   const unsigned NumDataArgs;
5552   const char *Beg; // Start of format string.
5553   const bool HasVAListArg;
5554   ArrayRef<const Expr *> Args;
5555   unsigned FormatIdx;
5556   llvm::SmallBitVector CoveredArgs;
5557   bool usesPositionalArgs = false;
5558   bool atFirstArg = true;
5559   bool inFunctionCall;
5560   Sema::VariadicCallType CallType;
5561   llvm::SmallBitVector &CheckedVarArgs;
5562   UncoveredArgHandler &UncoveredArg;
5563 
5564 public:
5565   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5566                      const Expr *origFormatExpr,
5567                      const Sema::FormatStringType type, unsigned firstDataArg,
5568                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5569                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5570                      bool inFunctionCall, Sema::VariadicCallType callType,
5571                      llvm::SmallBitVector &CheckedVarArgs,
5572                      UncoveredArgHandler &UncoveredArg)
5573       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5574         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5575         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5576         inFunctionCall(inFunctionCall), CallType(callType),
5577         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5578     CoveredArgs.resize(numDataArgs);
5579     CoveredArgs.reset();
5580   }
5581 
5582   void DoneProcessing();
5583 
5584   void HandleIncompleteSpecifier(const char *startSpecifier,
5585                                  unsigned specifierLen) override;
5586 
5587   void HandleInvalidLengthModifier(
5588                            const analyze_format_string::FormatSpecifier &FS,
5589                            const analyze_format_string::ConversionSpecifier &CS,
5590                            const char *startSpecifier, unsigned specifierLen,
5591                            unsigned DiagID);
5592 
5593   void HandleNonStandardLengthModifier(
5594                     const analyze_format_string::FormatSpecifier &FS,
5595                     const char *startSpecifier, unsigned specifierLen);
5596 
5597   void HandleNonStandardConversionSpecifier(
5598                     const analyze_format_string::ConversionSpecifier &CS,
5599                     const char *startSpecifier, unsigned specifierLen);
5600 
5601   void HandlePosition(const char *startPos, unsigned posLen) override;
5602 
5603   void HandleInvalidPosition(const char *startSpecifier,
5604                              unsigned specifierLen,
5605                              analyze_format_string::PositionContext p) override;
5606 
5607   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5608 
5609   void HandleNullChar(const char *nullCharacter) override;
5610 
5611   template <typename Range>
5612   static void
5613   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5614                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5615                        bool IsStringLocation, Range StringRange,
5616                        ArrayRef<FixItHint> Fixit = None);
5617 
5618 protected:
5619   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5620                                         const char *startSpec,
5621                                         unsigned specifierLen,
5622                                         const char *csStart, unsigned csLen);
5623 
5624   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5625                                          const char *startSpec,
5626                                          unsigned specifierLen);
5627 
5628   SourceRange getFormatStringRange();
5629   CharSourceRange getSpecifierRange(const char *startSpecifier,
5630                                     unsigned specifierLen);
5631   SourceLocation getLocationOfByte(const char *x);
5632 
5633   const Expr *getDataArg(unsigned i) const;
5634 
5635   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5636                     const analyze_format_string::ConversionSpecifier &CS,
5637                     const char *startSpecifier, unsigned specifierLen,
5638                     unsigned argIndex);
5639 
5640   template <typename Range>
5641   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5642                             bool IsStringLocation, Range StringRange,
5643                             ArrayRef<FixItHint> Fixit = None);
5644 };
5645 
5646 } // namespace
5647 
5648 SourceRange CheckFormatHandler::getFormatStringRange() {
5649   return OrigFormatExpr->getSourceRange();
5650 }
5651 
5652 CharSourceRange CheckFormatHandler::
5653 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5654   SourceLocation Start = getLocationOfByte(startSpecifier);
5655   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5656 
5657   // Advance the end SourceLocation by one due to half-open ranges.
5658   End = End.getLocWithOffset(1);
5659 
5660   return CharSourceRange::getCharRange(Start, End);
5661 }
5662 
5663 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5664   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5665                                   S.getLangOpts(), S.Context.getTargetInfo());
5666 }
5667 
5668 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5669                                                    unsigned specifierLen){
5670   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5671                        getLocationOfByte(startSpecifier),
5672                        /*IsStringLocation*/true,
5673                        getSpecifierRange(startSpecifier, specifierLen));
5674 }
5675 
5676 void CheckFormatHandler::HandleInvalidLengthModifier(
5677     const analyze_format_string::FormatSpecifier &FS,
5678     const analyze_format_string::ConversionSpecifier &CS,
5679     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5680   using namespace analyze_format_string;
5681 
5682   const LengthModifier &LM = FS.getLengthModifier();
5683   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5684 
5685   // See if we know how to fix this length modifier.
5686   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5687   if (FixedLM) {
5688     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5689                          getLocationOfByte(LM.getStart()),
5690                          /*IsStringLocation*/true,
5691                          getSpecifierRange(startSpecifier, specifierLen));
5692 
5693     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5694       << FixedLM->toString()
5695       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5696 
5697   } else {
5698     FixItHint Hint;
5699     if (DiagID == diag::warn_format_nonsensical_length)
5700       Hint = FixItHint::CreateRemoval(LMRange);
5701 
5702     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5703                          getLocationOfByte(LM.getStart()),
5704                          /*IsStringLocation*/true,
5705                          getSpecifierRange(startSpecifier, specifierLen),
5706                          Hint);
5707   }
5708 }
5709 
5710 void CheckFormatHandler::HandleNonStandardLengthModifier(
5711     const analyze_format_string::FormatSpecifier &FS,
5712     const char *startSpecifier, unsigned specifierLen) {
5713   using namespace analyze_format_string;
5714 
5715   const LengthModifier &LM = FS.getLengthModifier();
5716   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5717 
5718   // See if we know how to fix this length modifier.
5719   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5720   if (FixedLM) {
5721     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5722                            << LM.toString() << 0,
5723                          getLocationOfByte(LM.getStart()),
5724                          /*IsStringLocation*/true,
5725                          getSpecifierRange(startSpecifier, specifierLen));
5726 
5727     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5728       << FixedLM->toString()
5729       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5730 
5731   } else {
5732     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5733                            << LM.toString() << 0,
5734                          getLocationOfByte(LM.getStart()),
5735                          /*IsStringLocation*/true,
5736                          getSpecifierRange(startSpecifier, specifierLen));
5737   }
5738 }
5739 
5740 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5741     const analyze_format_string::ConversionSpecifier &CS,
5742     const char *startSpecifier, unsigned specifierLen) {
5743   using namespace analyze_format_string;
5744 
5745   // See if we know how to fix this conversion specifier.
5746   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5747   if (FixedCS) {
5748     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5749                           << CS.toString() << /*conversion specifier*/1,
5750                          getLocationOfByte(CS.getStart()),
5751                          /*IsStringLocation*/true,
5752                          getSpecifierRange(startSpecifier, specifierLen));
5753 
5754     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5755     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5756       << FixedCS->toString()
5757       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5758   } else {
5759     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5760                           << CS.toString() << /*conversion specifier*/1,
5761                          getLocationOfByte(CS.getStart()),
5762                          /*IsStringLocation*/true,
5763                          getSpecifierRange(startSpecifier, specifierLen));
5764   }
5765 }
5766 
5767 void CheckFormatHandler::HandlePosition(const char *startPos,
5768                                         unsigned posLen) {
5769   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5770                                getLocationOfByte(startPos),
5771                                /*IsStringLocation*/true,
5772                                getSpecifierRange(startPos, posLen));
5773 }
5774 
5775 void
5776 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5777                                      analyze_format_string::PositionContext p) {
5778   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5779                          << (unsigned) p,
5780                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5781                        getSpecifierRange(startPos, posLen));
5782 }
5783 
5784 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5785                                             unsigned posLen) {
5786   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5787                                getLocationOfByte(startPos),
5788                                /*IsStringLocation*/true,
5789                                getSpecifierRange(startPos, posLen));
5790 }
5791 
5792 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5793   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5794     // The presence of a null character is likely an error.
5795     EmitFormatDiagnostic(
5796       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5797       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5798       getFormatStringRange());
5799   }
5800 }
5801 
5802 // Note that this may return NULL if there was an error parsing or building
5803 // one of the argument expressions.
5804 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5805   return Args[FirstDataArg + i];
5806 }
5807 
5808 void CheckFormatHandler::DoneProcessing() {
5809   // Does the number of data arguments exceed the number of
5810   // format conversions in the format string?
5811   if (!HasVAListArg) {
5812       // Find any arguments that weren't covered.
5813     CoveredArgs.flip();
5814     signed notCoveredArg = CoveredArgs.find_first();
5815     if (notCoveredArg >= 0) {
5816       assert((unsigned)notCoveredArg < NumDataArgs);
5817       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5818     } else {
5819       UncoveredArg.setAllCovered();
5820     }
5821   }
5822 }
5823 
5824 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5825                                    const Expr *ArgExpr) {
5826   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5827          "Invalid state");
5828 
5829   if (!ArgExpr)
5830     return;
5831 
5832   SourceLocation Loc = ArgExpr->getLocStart();
5833 
5834   if (S.getSourceManager().isInSystemMacro(Loc))
5835     return;
5836 
5837   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5838   for (auto E : DiagnosticExprs)
5839     PDiag << E->getSourceRange();
5840 
5841   CheckFormatHandler::EmitFormatDiagnostic(
5842                                   S, IsFunctionCall, DiagnosticExprs[0],
5843                                   PDiag, Loc, /*IsStringLocation*/false,
5844                                   DiagnosticExprs[0]->getSourceRange());
5845 }
5846 
5847 bool
5848 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5849                                                      SourceLocation Loc,
5850                                                      const char *startSpec,
5851                                                      unsigned specifierLen,
5852                                                      const char *csStart,
5853                                                      unsigned csLen) {
5854   bool keepGoing = true;
5855   if (argIndex < NumDataArgs) {
5856     // Consider the argument coverered, even though the specifier doesn't
5857     // make sense.
5858     CoveredArgs.set(argIndex);
5859   }
5860   else {
5861     // If argIndex exceeds the number of data arguments we
5862     // don't issue a warning because that is just a cascade of warnings (and
5863     // they may have intended '%%' anyway). We don't want to continue processing
5864     // the format string after this point, however, as we will like just get
5865     // gibberish when trying to match arguments.
5866     keepGoing = false;
5867   }
5868 
5869   StringRef Specifier(csStart, csLen);
5870 
5871   // If the specifier in non-printable, it could be the first byte of a UTF-8
5872   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5873   // hex value.
5874   std::string CodePointStr;
5875   if (!llvm::sys::locale::isPrint(*csStart)) {
5876     llvm::UTF32 CodePoint;
5877     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5878     const llvm::UTF8 *E =
5879         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5880     llvm::ConversionResult Result =
5881         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5882 
5883     if (Result != llvm::conversionOK) {
5884       unsigned char FirstChar = *csStart;
5885       CodePoint = (llvm::UTF32)FirstChar;
5886     }
5887 
5888     llvm::raw_string_ostream OS(CodePointStr);
5889     if (CodePoint < 256)
5890       OS << "\\x" << llvm::format("%02x", CodePoint);
5891     else if (CodePoint <= 0xFFFF)
5892       OS << "\\u" << llvm::format("%04x", CodePoint);
5893     else
5894       OS << "\\U" << llvm::format("%08x", CodePoint);
5895     OS.flush();
5896     Specifier = CodePointStr;
5897   }
5898 
5899   EmitFormatDiagnostic(
5900       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5901       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5902 
5903   return keepGoing;
5904 }
5905 
5906 void
5907 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5908                                                       const char *startSpec,
5909                                                       unsigned specifierLen) {
5910   EmitFormatDiagnostic(
5911     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5912     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5913 }
5914 
5915 bool
5916 CheckFormatHandler::CheckNumArgs(
5917   const analyze_format_string::FormatSpecifier &FS,
5918   const analyze_format_string::ConversionSpecifier &CS,
5919   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5920 
5921   if (argIndex >= NumDataArgs) {
5922     PartialDiagnostic PDiag = FS.usesPositionalArg()
5923       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5924            << (argIndex+1) << NumDataArgs)
5925       : S.PDiag(diag::warn_printf_insufficient_data_args);
5926     EmitFormatDiagnostic(
5927       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5928       getSpecifierRange(startSpecifier, specifierLen));
5929 
5930     // Since more arguments than conversion tokens are given, by extension
5931     // all arguments are covered, so mark this as so.
5932     UncoveredArg.setAllCovered();
5933     return false;
5934   }
5935   return true;
5936 }
5937 
5938 template<typename Range>
5939 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5940                                               SourceLocation Loc,
5941                                               bool IsStringLocation,
5942                                               Range StringRange,
5943                                               ArrayRef<FixItHint> FixIt) {
5944   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5945                        Loc, IsStringLocation, StringRange, FixIt);
5946 }
5947 
5948 /// If the format string is not within the function call, emit a note
5949 /// so that the function call and string are in diagnostic messages.
5950 ///
5951 /// \param InFunctionCall if true, the format string is within the function
5952 /// call and only one diagnostic message will be produced.  Otherwise, an
5953 /// extra note will be emitted pointing to location of the format string.
5954 ///
5955 /// \param ArgumentExpr the expression that is passed as the format string
5956 /// argument in the function call.  Used for getting locations when two
5957 /// diagnostics are emitted.
5958 ///
5959 /// \param PDiag the callee should already have provided any strings for the
5960 /// diagnostic message.  This function only adds locations and fixits
5961 /// to diagnostics.
5962 ///
5963 /// \param Loc primary location for diagnostic.  If two diagnostics are
5964 /// required, one will be at Loc and a new SourceLocation will be created for
5965 /// the other one.
5966 ///
5967 /// \param IsStringLocation if true, Loc points to the format string should be
5968 /// used for the note.  Otherwise, Loc points to the argument list and will
5969 /// be used with PDiag.
5970 ///
5971 /// \param StringRange some or all of the string to highlight.  This is
5972 /// templated so it can accept either a CharSourceRange or a SourceRange.
5973 ///
5974 /// \param FixIt optional fix it hint for the format string.
5975 template <typename Range>
5976 void CheckFormatHandler::EmitFormatDiagnostic(
5977     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5978     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5979     Range StringRange, ArrayRef<FixItHint> FixIt) {
5980   if (InFunctionCall) {
5981     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5982     D << StringRange;
5983     D << FixIt;
5984   } else {
5985     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5986       << ArgumentExpr->getSourceRange();
5987 
5988     const Sema::SemaDiagnosticBuilder &Note =
5989       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5990              diag::note_format_string_defined);
5991 
5992     Note << StringRange;
5993     Note << FixIt;
5994   }
5995 }
5996 
5997 //===--- CHECK: Printf format string checking ------------------------------===//
5998 
5999 namespace {
6000 
6001 class CheckPrintfHandler : public CheckFormatHandler {
6002 public:
6003   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
6004                      const Expr *origFormatExpr,
6005                      const Sema::FormatStringType type, unsigned firstDataArg,
6006                      unsigned numDataArgs, bool isObjC, const char *beg,
6007                      bool hasVAListArg, ArrayRef<const Expr *> Args,
6008                      unsigned formatIdx, bool inFunctionCall,
6009                      Sema::VariadicCallType CallType,
6010                      llvm::SmallBitVector &CheckedVarArgs,
6011                      UncoveredArgHandler &UncoveredArg)
6012       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6013                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6014                            inFunctionCall, CallType, CheckedVarArgs,
6015                            UncoveredArg) {}
6016 
6017   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6018 
6019   /// Returns true if '%@' specifiers are allowed in the format string.
6020   bool allowsObjCArg() const {
6021     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6022            FSType == Sema::FST_OSTrace;
6023   }
6024 
6025   bool HandleInvalidPrintfConversionSpecifier(
6026                                       const analyze_printf::PrintfSpecifier &FS,
6027                                       const char *startSpecifier,
6028                                       unsigned specifierLen) override;
6029 
6030   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6031                              const char *startSpecifier,
6032                              unsigned specifierLen) override;
6033   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6034                        const char *StartSpecifier,
6035                        unsigned SpecifierLen,
6036                        const Expr *E);
6037 
6038   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6039                     const char *startSpecifier, unsigned specifierLen);
6040   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6041                            const analyze_printf::OptionalAmount &Amt,
6042                            unsigned type,
6043                            const char *startSpecifier, unsigned specifierLen);
6044   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6045                   const analyze_printf::OptionalFlag &flag,
6046                   const char *startSpecifier, unsigned specifierLen);
6047   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6048                          const analyze_printf::OptionalFlag &ignoredFlag,
6049                          const analyze_printf::OptionalFlag &flag,
6050                          const char *startSpecifier, unsigned specifierLen);
6051   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
6052                            const Expr *E);
6053 
6054   void HandleEmptyObjCModifierFlag(const char *startFlag,
6055                                    unsigned flagLen) override;
6056 
6057   void HandleInvalidObjCModifierFlag(const char *startFlag,
6058                                             unsigned flagLen) override;
6059 
6060   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6061                                            const char *flagsEnd,
6062                                            const char *conversionPosition)
6063                                              override;
6064 };
6065 
6066 } // namespace
6067 
6068 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6069                                       const analyze_printf::PrintfSpecifier &FS,
6070                                       const char *startSpecifier,
6071                                       unsigned specifierLen) {
6072   const analyze_printf::PrintfConversionSpecifier &CS =
6073     FS.getConversionSpecifier();
6074 
6075   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6076                                           getLocationOfByte(CS.getStart()),
6077                                           startSpecifier, specifierLen,
6078                                           CS.getStart(), CS.getLength());
6079 }
6080 
6081 bool CheckPrintfHandler::HandleAmount(
6082                                const analyze_format_string::OptionalAmount &Amt,
6083                                unsigned k, const char *startSpecifier,
6084                                unsigned specifierLen) {
6085   if (Amt.hasDataArgument()) {
6086     if (!HasVAListArg) {
6087       unsigned argIndex = Amt.getArgIndex();
6088       if (argIndex >= NumDataArgs) {
6089         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6090                                << k,
6091                              getLocationOfByte(Amt.getStart()),
6092                              /*IsStringLocation*/true,
6093                              getSpecifierRange(startSpecifier, specifierLen));
6094         // Don't do any more checking.  We will just emit
6095         // spurious errors.
6096         return false;
6097       }
6098 
6099       // Type check the data argument.  It should be an 'int'.
6100       // Although not in conformance with C99, we also allow the argument to be
6101       // an 'unsigned int' as that is a reasonably safe case.  GCC also
6102       // doesn't emit a warning for that case.
6103       CoveredArgs.set(argIndex);
6104       const Expr *Arg = getDataArg(argIndex);
6105       if (!Arg)
6106         return false;
6107 
6108       QualType T = Arg->getType();
6109 
6110       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6111       assert(AT.isValid());
6112 
6113       if (!AT.matchesType(S.Context, T)) {
6114         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
6115                                << k << AT.getRepresentativeTypeName(S.Context)
6116                                << T << Arg->getSourceRange(),
6117                              getLocationOfByte(Amt.getStart()),
6118                              /*IsStringLocation*/true,
6119                              getSpecifierRange(startSpecifier, specifierLen));
6120         // Don't do any more checking.  We will just emit
6121         // spurious errors.
6122         return false;
6123       }
6124     }
6125   }
6126   return true;
6127 }
6128 
6129 void CheckPrintfHandler::HandleInvalidAmount(
6130                                       const analyze_printf::PrintfSpecifier &FS,
6131                                       const analyze_printf::OptionalAmount &Amt,
6132                                       unsigned type,
6133                                       const char *startSpecifier,
6134                                       unsigned specifierLen) {
6135   const analyze_printf::PrintfConversionSpecifier &CS =
6136     FS.getConversionSpecifier();
6137 
6138   FixItHint fixit =
6139     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6140       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6141                                  Amt.getConstantLength()))
6142       : FixItHint();
6143 
6144   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6145                          << type << CS.toString(),
6146                        getLocationOfByte(Amt.getStart()),
6147                        /*IsStringLocation*/true,
6148                        getSpecifierRange(startSpecifier, specifierLen),
6149                        fixit);
6150 }
6151 
6152 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6153                                     const analyze_printf::OptionalFlag &flag,
6154                                     const char *startSpecifier,
6155                                     unsigned specifierLen) {
6156   // Warn about pointless flag with a fixit removal.
6157   const analyze_printf::PrintfConversionSpecifier &CS =
6158     FS.getConversionSpecifier();
6159   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6160                          << flag.toString() << CS.toString(),
6161                        getLocationOfByte(flag.getPosition()),
6162                        /*IsStringLocation*/true,
6163                        getSpecifierRange(startSpecifier, specifierLen),
6164                        FixItHint::CreateRemoval(
6165                          getSpecifierRange(flag.getPosition(), 1)));
6166 }
6167 
6168 void CheckPrintfHandler::HandleIgnoredFlag(
6169                                 const analyze_printf::PrintfSpecifier &FS,
6170                                 const analyze_printf::OptionalFlag &ignoredFlag,
6171                                 const analyze_printf::OptionalFlag &flag,
6172                                 const char *startSpecifier,
6173                                 unsigned specifierLen) {
6174   // Warn about ignored flag with a fixit removal.
6175   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6176                          << ignoredFlag.toString() << flag.toString(),
6177                        getLocationOfByte(ignoredFlag.getPosition()),
6178                        /*IsStringLocation*/true,
6179                        getSpecifierRange(startSpecifier, specifierLen),
6180                        FixItHint::CreateRemoval(
6181                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
6182 }
6183 
6184 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6185                                                      unsigned flagLen) {
6186   // Warn about an empty flag.
6187   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6188                        getLocationOfByte(startFlag),
6189                        /*IsStringLocation*/true,
6190                        getSpecifierRange(startFlag, flagLen));
6191 }
6192 
6193 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6194                                                        unsigned flagLen) {
6195   // Warn about an invalid flag.
6196   auto Range = getSpecifierRange(startFlag, flagLen);
6197   StringRef flag(startFlag, flagLen);
6198   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6199                       getLocationOfByte(startFlag),
6200                       /*IsStringLocation*/true,
6201                       Range, FixItHint::CreateRemoval(Range));
6202 }
6203 
6204 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6205     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6206     // Warn about using '[...]' without a '@' conversion.
6207     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6208     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6209     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6210                          getLocationOfByte(conversionPosition),
6211                          /*IsStringLocation*/true,
6212                          Range, FixItHint::CreateRemoval(Range));
6213 }
6214 
6215 // Determines if the specified is a C++ class or struct containing
6216 // a member with the specified name and kind (e.g. a CXXMethodDecl named
6217 // "c_str()").
6218 template<typename MemberKind>
6219 static llvm::SmallPtrSet<MemberKind*, 1>
6220 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6221   const RecordType *RT = Ty->getAs<RecordType>();
6222   llvm::SmallPtrSet<MemberKind*, 1> Results;
6223 
6224   if (!RT)
6225     return Results;
6226   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
6227   if (!RD || !RD->getDefinition())
6228     return Results;
6229 
6230   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
6231                  Sema::LookupMemberName);
6232   R.suppressDiagnostics();
6233 
6234   // We just need to include all members of the right kind turned up by the
6235   // filter, at this point.
6236   if (S.LookupQualifiedName(R, RT->getDecl()))
6237     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6238       NamedDecl *decl = (*I)->getUnderlyingDecl();
6239       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6240         Results.insert(FK);
6241     }
6242   return Results;
6243 }
6244 
6245 /// Check if we could call '.c_str()' on an object.
6246 ///
6247 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6248 /// allow the call, or if it would be ambiguous).
6249 bool Sema::hasCStrMethod(const Expr *E) {
6250   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6251 
6252   MethodSet Results =
6253       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6254   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6255        MI != ME; ++MI)
6256     if ((*MI)->getMinRequiredArguments() == 0)
6257       return true;
6258   return false;
6259 }
6260 
6261 // Check if a (w)string was passed when a (w)char* was needed, and offer a
6262 // better diagnostic if so. AT is assumed to be valid.
6263 // Returns true when a c_str() conversion method is found.
6264 bool CheckPrintfHandler::checkForCStrMembers(
6265     const analyze_printf::ArgType &AT, const Expr *E) {
6266   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6267 
6268   MethodSet Results =
6269       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6270 
6271   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6272        MI != ME; ++MI) {
6273     const CXXMethodDecl *Method = *MI;
6274     if (Method->getMinRequiredArguments() == 0 &&
6275         AT.matchesType(S.Context, Method->getReturnType())) {
6276       // FIXME: Suggest parens if the expression needs them.
6277       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
6278       S.Diag(E->getLocStart(), diag::note_printf_c_str)
6279           << "c_str()"
6280           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6281       return true;
6282     }
6283   }
6284 
6285   return false;
6286 }
6287 
6288 bool
6289 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
6290                                             &FS,
6291                                           const char *startSpecifier,
6292                                           unsigned specifierLen) {
6293   using namespace analyze_format_string;
6294   using namespace analyze_printf;
6295 
6296   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6297 
6298   if (FS.consumesDataArgument()) {
6299     if (atFirstArg) {
6300         atFirstArg = false;
6301         usesPositionalArgs = FS.usesPositionalArg();
6302     }
6303     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6304       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6305                                         startSpecifier, specifierLen);
6306       return false;
6307     }
6308   }
6309 
6310   // First check if the field width, precision, and conversion specifier
6311   // have matching data arguments.
6312   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6313                     startSpecifier, specifierLen)) {
6314     return false;
6315   }
6316 
6317   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6318                     startSpecifier, specifierLen)) {
6319     return false;
6320   }
6321 
6322   if (!CS.consumesDataArgument()) {
6323     // FIXME: Technically specifying a precision or field width here
6324     // makes no sense.  Worth issuing a warning at some point.
6325     return true;
6326   }
6327 
6328   // Consume the argument.
6329   unsigned argIndex = FS.getArgIndex();
6330   if (argIndex < NumDataArgs) {
6331     // The check to see if the argIndex is valid will come later.
6332     // We set the bit here because we may exit early from this
6333     // function if we encounter some other error.
6334     CoveredArgs.set(argIndex);
6335   }
6336 
6337   // FreeBSD kernel extensions.
6338   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6339       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6340     // We need at least two arguments.
6341     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6342       return false;
6343 
6344     // Claim the second argument.
6345     CoveredArgs.set(argIndex + 1);
6346 
6347     // Type check the first argument (int for %b, pointer for %D)
6348     const Expr *Ex = getDataArg(argIndex);
6349     const analyze_printf::ArgType &AT =
6350       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6351         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6352     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6353       EmitFormatDiagnostic(
6354         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6355         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6356         << false << Ex->getSourceRange(),
6357         Ex->getLocStart(), /*IsStringLocation*/false,
6358         getSpecifierRange(startSpecifier, specifierLen));
6359 
6360     // Type check the second argument (char * for both %b and %D)
6361     Ex = getDataArg(argIndex + 1);
6362     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6363     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6364       EmitFormatDiagnostic(
6365         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6366         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6367         << false << Ex->getSourceRange(),
6368         Ex->getLocStart(), /*IsStringLocation*/false,
6369         getSpecifierRange(startSpecifier, specifierLen));
6370 
6371      return true;
6372   }
6373 
6374   // Check for using an Objective-C specific conversion specifier
6375   // in a non-ObjC literal.
6376   if (!allowsObjCArg() && CS.isObjCArg()) {
6377     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6378                                                   specifierLen);
6379   }
6380 
6381   // %P can only be used with os_log.
6382   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6383     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6384                                                   specifierLen);
6385   }
6386 
6387   // %n is not allowed with os_log.
6388   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6389     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6390                          getLocationOfByte(CS.getStart()),
6391                          /*IsStringLocation*/ false,
6392                          getSpecifierRange(startSpecifier, specifierLen));
6393 
6394     return true;
6395   }
6396 
6397   // Only scalars are allowed for os_trace.
6398   if (FSType == Sema::FST_OSTrace &&
6399       (CS.getKind() == ConversionSpecifier::PArg ||
6400        CS.getKind() == ConversionSpecifier::sArg ||
6401        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6402     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6403                                                   specifierLen);
6404   }
6405 
6406   // Check for use of public/private annotation outside of os_log().
6407   if (FSType != Sema::FST_OSLog) {
6408     if (FS.isPublic().isSet()) {
6409       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6410                                << "public",
6411                            getLocationOfByte(FS.isPublic().getPosition()),
6412                            /*IsStringLocation*/ false,
6413                            getSpecifierRange(startSpecifier, specifierLen));
6414     }
6415     if (FS.isPrivate().isSet()) {
6416       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6417                                << "private",
6418                            getLocationOfByte(FS.isPrivate().getPosition()),
6419                            /*IsStringLocation*/ false,
6420                            getSpecifierRange(startSpecifier, specifierLen));
6421     }
6422   }
6423 
6424   // Check for invalid use of field width
6425   if (!FS.hasValidFieldWidth()) {
6426     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6427         startSpecifier, specifierLen);
6428   }
6429 
6430   // Check for invalid use of precision
6431   if (!FS.hasValidPrecision()) {
6432     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6433         startSpecifier, specifierLen);
6434   }
6435 
6436   // Precision is mandatory for %P specifier.
6437   if (CS.getKind() == ConversionSpecifier::PArg &&
6438       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6439     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6440                          getLocationOfByte(startSpecifier),
6441                          /*IsStringLocation*/ false,
6442                          getSpecifierRange(startSpecifier, specifierLen));
6443   }
6444 
6445   // Check each flag does not conflict with any other component.
6446   if (!FS.hasValidThousandsGroupingPrefix())
6447     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6448   if (!FS.hasValidLeadingZeros())
6449     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6450   if (!FS.hasValidPlusPrefix())
6451     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6452   if (!FS.hasValidSpacePrefix())
6453     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6454   if (!FS.hasValidAlternativeForm())
6455     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6456   if (!FS.hasValidLeftJustified())
6457     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6458 
6459   // Check that flags are not ignored by another flag
6460   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6461     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6462         startSpecifier, specifierLen);
6463   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6464     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6465             startSpecifier, specifierLen);
6466 
6467   // Check the length modifier is valid with the given conversion specifier.
6468   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6469     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6470                                 diag::warn_format_nonsensical_length);
6471   else if (!FS.hasStandardLengthModifier())
6472     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6473   else if (!FS.hasStandardLengthConversionCombination())
6474     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6475                                 diag::warn_format_non_standard_conversion_spec);
6476 
6477   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6478     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6479 
6480   // The remaining checks depend on the data arguments.
6481   if (HasVAListArg)
6482     return true;
6483 
6484   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6485     return false;
6486 
6487   const Expr *Arg = getDataArg(argIndex);
6488   if (!Arg)
6489     return true;
6490 
6491   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6492 }
6493 
6494 static bool requiresParensToAddCast(const Expr *E) {
6495   // FIXME: We should have a general way to reason about operator
6496   // precedence and whether parens are actually needed here.
6497   // Take care of a few common cases where they aren't.
6498   const Expr *Inside = E->IgnoreImpCasts();
6499   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6500     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6501 
6502   switch (Inside->getStmtClass()) {
6503   case Stmt::ArraySubscriptExprClass:
6504   case Stmt::CallExprClass:
6505   case Stmt::CharacterLiteralClass:
6506   case Stmt::CXXBoolLiteralExprClass:
6507   case Stmt::DeclRefExprClass:
6508   case Stmt::FloatingLiteralClass:
6509   case Stmt::IntegerLiteralClass:
6510   case Stmt::MemberExprClass:
6511   case Stmt::ObjCArrayLiteralClass:
6512   case Stmt::ObjCBoolLiteralExprClass:
6513   case Stmt::ObjCBoxedExprClass:
6514   case Stmt::ObjCDictionaryLiteralClass:
6515   case Stmt::ObjCEncodeExprClass:
6516   case Stmt::ObjCIvarRefExprClass:
6517   case Stmt::ObjCMessageExprClass:
6518   case Stmt::ObjCPropertyRefExprClass:
6519   case Stmt::ObjCStringLiteralClass:
6520   case Stmt::ObjCSubscriptRefExprClass:
6521   case Stmt::ParenExprClass:
6522   case Stmt::StringLiteralClass:
6523   case Stmt::UnaryOperatorClass:
6524     return false;
6525   default:
6526     return true;
6527   }
6528 }
6529 
6530 static std::pair<QualType, StringRef>
6531 shouldNotPrintDirectly(const ASTContext &Context,
6532                        QualType IntendedTy,
6533                        const Expr *E) {
6534   // Use a 'while' to peel off layers of typedefs.
6535   QualType TyTy = IntendedTy;
6536   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6537     StringRef Name = UserTy->getDecl()->getName();
6538     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6539       .Case("CFIndex", Context.getNSIntegerType())
6540       .Case("NSInteger", Context.getNSIntegerType())
6541       .Case("NSUInteger", Context.getNSUIntegerType())
6542       .Case("SInt32", Context.IntTy)
6543       .Case("UInt32", Context.UnsignedIntTy)
6544       .Default(QualType());
6545 
6546     if (!CastTy.isNull())
6547       return std::make_pair(CastTy, Name);
6548 
6549     TyTy = UserTy->desugar();
6550   }
6551 
6552   // Strip parens if necessary.
6553   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6554     return shouldNotPrintDirectly(Context,
6555                                   PE->getSubExpr()->getType(),
6556                                   PE->getSubExpr());
6557 
6558   // If this is a conditional expression, then its result type is constructed
6559   // via usual arithmetic conversions and thus there might be no necessary
6560   // typedef sugar there.  Recurse to operands to check for NSInteger &
6561   // Co. usage condition.
6562   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6563     QualType TrueTy, FalseTy;
6564     StringRef TrueName, FalseName;
6565 
6566     std::tie(TrueTy, TrueName) =
6567       shouldNotPrintDirectly(Context,
6568                              CO->getTrueExpr()->getType(),
6569                              CO->getTrueExpr());
6570     std::tie(FalseTy, FalseName) =
6571       shouldNotPrintDirectly(Context,
6572                              CO->getFalseExpr()->getType(),
6573                              CO->getFalseExpr());
6574 
6575     if (TrueTy == FalseTy)
6576       return std::make_pair(TrueTy, TrueName);
6577     else if (TrueTy.isNull())
6578       return std::make_pair(FalseTy, FalseName);
6579     else if (FalseTy.isNull())
6580       return std::make_pair(TrueTy, TrueName);
6581   }
6582 
6583   return std::make_pair(QualType(), StringRef());
6584 }
6585 
6586 bool
6587 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6588                                     const char *StartSpecifier,
6589                                     unsigned SpecifierLen,
6590                                     const Expr *E) {
6591   using namespace analyze_format_string;
6592   using namespace analyze_printf;
6593 
6594   // Now type check the data expression that matches the
6595   // format specifier.
6596   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6597   if (!AT.isValid())
6598     return true;
6599 
6600   QualType ExprTy = E->getType();
6601   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6602     ExprTy = TET->getUnderlyingExpr()->getType();
6603   }
6604 
6605   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6606 
6607   if (match == analyze_printf::ArgType::Match) {
6608     return true;
6609   }
6610 
6611   // Look through argument promotions for our error message's reported type.
6612   // This includes the integral and floating promotions, but excludes array
6613   // and function pointer decay; seeing that an argument intended to be a
6614   // string has type 'char [6]' is probably more confusing than 'char *'.
6615   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6616     if (ICE->getCastKind() == CK_IntegralCast ||
6617         ICE->getCastKind() == CK_FloatingCast) {
6618       E = ICE->getSubExpr();
6619       ExprTy = E->getType();
6620 
6621       // Check if we didn't match because of an implicit cast from a 'char'
6622       // or 'short' to an 'int'.  This is done because printf is a varargs
6623       // function.
6624       if (ICE->getType() == S.Context.IntTy ||
6625           ICE->getType() == S.Context.UnsignedIntTy) {
6626         // All further checking is done on the subexpression.
6627         if (AT.matchesType(S.Context, ExprTy))
6628           return true;
6629       }
6630     }
6631   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6632     // Special case for 'a', which has type 'int' in C.
6633     // Note, however, that we do /not/ want to treat multibyte constants like
6634     // 'MooV' as characters! This form is deprecated but still exists.
6635     if (ExprTy == S.Context.IntTy)
6636       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6637         ExprTy = S.Context.CharTy;
6638   }
6639 
6640   // Look through enums to their underlying type.
6641   bool IsEnum = false;
6642   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6643     ExprTy = EnumTy->getDecl()->getIntegerType();
6644     IsEnum = true;
6645   }
6646 
6647   // %C in an Objective-C context prints a unichar, not a wchar_t.
6648   // If the argument is an integer of some kind, believe the %C and suggest
6649   // a cast instead of changing the conversion specifier.
6650   QualType IntendedTy = ExprTy;
6651   if (isObjCContext() &&
6652       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6653     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6654         !ExprTy->isCharType()) {
6655       // 'unichar' is defined as a typedef of unsigned short, but we should
6656       // prefer using the typedef if it is visible.
6657       IntendedTy = S.Context.UnsignedShortTy;
6658 
6659       // While we are here, check if the value is an IntegerLiteral that happens
6660       // to be within the valid range.
6661       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6662         const llvm::APInt &V = IL->getValue();
6663         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6664           return true;
6665       }
6666 
6667       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6668                           Sema::LookupOrdinaryName);
6669       if (S.LookupName(Result, S.getCurScope())) {
6670         NamedDecl *ND = Result.getFoundDecl();
6671         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6672           if (TD->getUnderlyingType() == IntendedTy)
6673             IntendedTy = S.Context.getTypedefType(TD);
6674       }
6675     }
6676   }
6677 
6678   // Special-case some of Darwin's platform-independence types by suggesting
6679   // casts to primitive types that are known to be large enough.
6680   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6681   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6682     QualType CastTy;
6683     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6684     if (!CastTy.isNull()) {
6685       IntendedTy = CastTy;
6686       ShouldNotPrintDirectly = true;
6687     }
6688   }
6689 
6690   // We may be able to offer a FixItHint if it is a supported type.
6691   PrintfSpecifier fixedFS = FS;
6692   bool success =
6693       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6694 
6695   if (success) {
6696     // Get the fix string from the fixed format specifier
6697     SmallString<16> buf;
6698     llvm::raw_svector_ostream os(buf);
6699     fixedFS.toString(os);
6700 
6701     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6702 
6703     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6704       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6705       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6706         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6707       }
6708       // In this case, the specifier is wrong and should be changed to match
6709       // the argument.
6710       EmitFormatDiagnostic(S.PDiag(diag)
6711                                << AT.getRepresentativeTypeName(S.Context)
6712                                << IntendedTy << IsEnum << E->getSourceRange(),
6713                            E->getLocStart(),
6714                            /*IsStringLocation*/ false, SpecRange,
6715                            FixItHint::CreateReplacement(SpecRange, os.str()));
6716     } else {
6717       // The canonical type for formatting this value is different from the
6718       // actual type of the expression. (This occurs, for example, with Darwin's
6719       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6720       // should be printed as 'long' for 64-bit compatibility.)
6721       // Rather than emitting a normal format/argument mismatch, we want to
6722       // add a cast to the recommended type (and correct the format string
6723       // if necessary).
6724       SmallString<16> CastBuf;
6725       llvm::raw_svector_ostream CastFix(CastBuf);
6726       CastFix << "(";
6727       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6728       CastFix << ")";
6729 
6730       SmallVector<FixItHint,4> Hints;
6731       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6732         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6733 
6734       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6735         // If there's already a cast present, just replace it.
6736         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6737         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6738 
6739       } else if (!requiresParensToAddCast(E)) {
6740         // If the expression has high enough precedence,
6741         // just write the C-style cast.
6742         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6743                                                    CastFix.str()));
6744       } else {
6745         // Otherwise, add parens around the expression as well as the cast.
6746         CastFix << "(";
6747         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6748                                                    CastFix.str()));
6749 
6750         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6751         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6752       }
6753 
6754       if (ShouldNotPrintDirectly) {
6755         // The expression has a type that should not be printed directly.
6756         // We extract the name from the typedef because we don't want to show
6757         // the underlying type in the diagnostic.
6758         StringRef Name;
6759         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6760           Name = TypedefTy->getDecl()->getName();
6761         else
6762           Name = CastTyName;
6763         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6764                                << Name << IntendedTy << IsEnum
6765                                << E->getSourceRange(),
6766                              E->getLocStart(), /*IsStringLocation=*/false,
6767                              SpecRange, Hints);
6768       } else {
6769         // In this case, the expression could be printed using a different
6770         // specifier, but we've decided that the specifier is probably correct
6771         // and we should cast instead. Just use the normal warning message.
6772         EmitFormatDiagnostic(
6773           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6774             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6775             << E->getSourceRange(),
6776           E->getLocStart(), /*IsStringLocation*/false,
6777           SpecRange, Hints);
6778       }
6779     }
6780   } else {
6781     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6782                                                    SpecifierLen);
6783     // Since the warning for passing non-POD types to variadic functions
6784     // was deferred until now, we emit a warning for non-POD
6785     // arguments here.
6786     switch (S.isValidVarArgType(ExprTy)) {
6787     case Sema::VAK_Valid:
6788     case Sema::VAK_ValidInCXX11: {
6789       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6790       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6791         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6792       }
6793 
6794       EmitFormatDiagnostic(
6795           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6796                         << IsEnum << CSR << E->getSourceRange(),
6797           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6798       break;
6799     }
6800     case Sema::VAK_Undefined:
6801     case Sema::VAK_MSVCUndefined:
6802       EmitFormatDiagnostic(
6803         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6804           << S.getLangOpts().CPlusPlus11
6805           << ExprTy
6806           << CallType
6807           << AT.getRepresentativeTypeName(S.Context)
6808           << CSR
6809           << E->getSourceRange(),
6810         E->getLocStart(), /*IsStringLocation*/false, CSR);
6811       checkForCStrMembers(AT, E);
6812       break;
6813 
6814     case Sema::VAK_Invalid:
6815       if (ExprTy->isObjCObjectType())
6816         EmitFormatDiagnostic(
6817           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6818             << S.getLangOpts().CPlusPlus11
6819             << ExprTy
6820             << CallType
6821             << AT.getRepresentativeTypeName(S.Context)
6822             << CSR
6823             << E->getSourceRange(),
6824           E->getLocStart(), /*IsStringLocation*/false, CSR);
6825       else
6826         // FIXME: If this is an initializer list, suggest removing the braces
6827         // or inserting a cast to the target type.
6828         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6829           << isa<InitListExpr>(E) << ExprTy << CallType
6830           << AT.getRepresentativeTypeName(S.Context)
6831           << E->getSourceRange();
6832       break;
6833     }
6834 
6835     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6836            "format string specifier index out of range");
6837     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6838   }
6839 
6840   return true;
6841 }
6842 
6843 //===--- CHECK: Scanf format string checking ------------------------------===//
6844 
6845 namespace {
6846 
6847 class CheckScanfHandler : public CheckFormatHandler {
6848 public:
6849   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6850                     const Expr *origFormatExpr, Sema::FormatStringType type,
6851                     unsigned firstDataArg, unsigned numDataArgs,
6852                     const char *beg, bool hasVAListArg,
6853                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6854                     bool inFunctionCall, Sema::VariadicCallType CallType,
6855                     llvm::SmallBitVector &CheckedVarArgs,
6856                     UncoveredArgHandler &UncoveredArg)
6857       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6858                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6859                            inFunctionCall, CallType, CheckedVarArgs,
6860                            UncoveredArg) {}
6861 
6862   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6863                             const char *startSpecifier,
6864                             unsigned specifierLen) override;
6865 
6866   bool HandleInvalidScanfConversionSpecifier(
6867           const analyze_scanf::ScanfSpecifier &FS,
6868           const char *startSpecifier,
6869           unsigned specifierLen) override;
6870 
6871   void HandleIncompleteScanList(const char *start, const char *end) override;
6872 };
6873 
6874 } // namespace
6875 
6876 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6877                                                  const char *end) {
6878   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6879                        getLocationOfByte(end), /*IsStringLocation*/true,
6880                        getSpecifierRange(start, end - start));
6881 }
6882 
6883 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6884                                         const analyze_scanf::ScanfSpecifier &FS,
6885                                         const char *startSpecifier,
6886                                         unsigned specifierLen) {
6887   const analyze_scanf::ScanfConversionSpecifier &CS =
6888     FS.getConversionSpecifier();
6889 
6890   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6891                                           getLocationOfByte(CS.getStart()),
6892                                           startSpecifier, specifierLen,
6893                                           CS.getStart(), CS.getLength());
6894 }
6895 
6896 bool CheckScanfHandler::HandleScanfSpecifier(
6897                                        const analyze_scanf::ScanfSpecifier &FS,
6898                                        const char *startSpecifier,
6899                                        unsigned specifierLen) {
6900   using namespace analyze_scanf;
6901   using namespace analyze_format_string;
6902 
6903   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6904 
6905   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6906   // be used to decide if we are using positional arguments consistently.
6907   if (FS.consumesDataArgument()) {
6908     if (atFirstArg) {
6909       atFirstArg = false;
6910       usesPositionalArgs = FS.usesPositionalArg();
6911     }
6912     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6913       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6914                                         startSpecifier, specifierLen);
6915       return false;
6916     }
6917   }
6918 
6919   // Check if the field with is non-zero.
6920   const OptionalAmount &Amt = FS.getFieldWidth();
6921   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6922     if (Amt.getConstantAmount() == 0) {
6923       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6924                                                    Amt.getConstantLength());
6925       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6926                            getLocationOfByte(Amt.getStart()),
6927                            /*IsStringLocation*/true, R,
6928                            FixItHint::CreateRemoval(R));
6929     }
6930   }
6931 
6932   if (!FS.consumesDataArgument()) {
6933     // FIXME: Technically specifying a precision or field width here
6934     // makes no sense.  Worth issuing a warning at some point.
6935     return true;
6936   }
6937 
6938   // Consume the argument.
6939   unsigned argIndex = FS.getArgIndex();
6940   if (argIndex < NumDataArgs) {
6941       // The check to see if the argIndex is valid will come later.
6942       // We set the bit here because we may exit early from this
6943       // function if we encounter some other error.
6944     CoveredArgs.set(argIndex);
6945   }
6946 
6947   // Check the length modifier is valid with the given conversion specifier.
6948   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6949     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6950                                 diag::warn_format_nonsensical_length);
6951   else if (!FS.hasStandardLengthModifier())
6952     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6953   else if (!FS.hasStandardLengthConversionCombination())
6954     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6955                                 diag::warn_format_non_standard_conversion_spec);
6956 
6957   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6958     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6959 
6960   // The remaining checks depend on the data arguments.
6961   if (HasVAListArg)
6962     return true;
6963 
6964   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6965     return false;
6966 
6967   // Check that the argument type matches the format specifier.
6968   const Expr *Ex = getDataArg(argIndex);
6969   if (!Ex)
6970     return true;
6971 
6972   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6973 
6974   if (!AT.isValid()) {
6975     return true;
6976   }
6977 
6978   analyze_format_string::ArgType::MatchKind match =
6979       AT.matchesType(S.Context, Ex->getType());
6980   if (match == analyze_format_string::ArgType::Match) {
6981     return true;
6982   }
6983 
6984   ScanfSpecifier fixedFS = FS;
6985   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6986                                  S.getLangOpts(), S.Context);
6987 
6988   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6989   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6990     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6991   }
6992 
6993   if (success) {
6994     // Get the fix string from the fixed format specifier.
6995     SmallString<128> buf;
6996     llvm::raw_svector_ostream os(buf);
6997     fixedFS.toString(os);
6998 
6999     EmitFormatDiagnostic(
7000         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7001                       << Ex->getType() << false << Ex->getSourceRange(),
7002         Ex->getLocStart(),
7003         /*IsStringLocation*/ false,
7004         getSpecifierRange(startSpecifier, specifierLen),
7005         FixItHint::CreateReplacement(
7006             getSpecifierRange(startSpecifier, specifierLen), os.str()));
7007   } else {
7008     EmitFormatDiagnostic(S.PDiag(diag)
7009                              << AT.getRepresentativeTypeName(S.Context)
7010                              << Ex->getType() << false << Ex->getSourceRange(),
7011                          Ex->getLocStart(),
7012                          /*IsStringLocation*/ false,
7013                          getSpecifierRange(startSpecifier, specifierLen));
7014   }
7015 
7016   return true;
7017 }
7018 
7019 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7020                               const Expr *OrigFormatExpr,
7021                               ArrayRef<const Expr *> Args,
7022                               bool HasVAListArg, unsigned format_idx,
7023                               unsigned firstDataArg,
7024                               Sema::FormatStringType Type,
7025                               bool inFunctionCall,
7026                               Sema::VariadicCallType CallType,
7027                               llvm::SmallBitVector &CheckedVarArgs,
7028                               UncoveredArgHandler &UncoveredArg) {
7029   // CHECK: is the format string a wide literal?
7030   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
7031     CheckFormatHandler::EmitFormatDiagnostic(
7032       S, inFunctionCall, Args[format_idx],
7033       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
7034       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
7035     return;
7036   }
7037 
7038   // Str - The format string.  NOTE: this is NOT null-terminated!
7039   StringRef StrRef = FExpr->getString();
7040   const char *Str = StrRef.data();
7041   // Account for cases where the string literal is truncated in a declaration.
7042   const ConstantArrayType *T =
7043     S.Context.getAsConstantArrayType(FExpr->getType());
7044   assert(T && "String literal not of constant array type!");
7045   size_t TypeSize = T->getSize().getZExtValue();
7046   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7047   const unsigned numDataArgs = Args.size() - firstDataArg;
7048 
7049   // Emit a warning if the string literal is truncated and does not contain an
7050   // embedded null character.
7051   if (TypeSize <= StrRef.size() &&
7052       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7053     CheckFormatHandler::EmitFormatDiagnostic(
7054         S, inFunctionCall, Args[format_idx],
7055         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
7056         FExpr->getLocStart(),
7057         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7058     return;
7059   }
7060 
7061   // CHECK: empty format string?
7062   if (StrLen == 0 && numDataArgs > 0) {
7063     CheckFormatHandler::EmitFormatDiagnostic(
7064       S, inFunctionCall, Args[format_idx],
7065       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
7066       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
7067     return;
7068   }
7069 
7070   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
7071       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7072       Type == Sema::FST_OSTrace) {
7073     CheckPrintfHandler H(
7074         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7075         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7076         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7077         CheckedVarArgs, UncoveredArg);
7078 
7079     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
7080                                                   S.getLangOpts(),
7081                                                   S.Context.getTargetInfo(),
7082                                             Type == Sema::FST_FreeBSDKPrintf))
7083       H.DoneProcessing();
7084   } else if (Type == Sema::FST_Scanf) {
7085     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7086                         numDataArgs, Str, HasVAListArg, Args, format_idx,
7087                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
7088 
7089     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
7090                                                  S.getLangOpts(),
7091                                                  S.Context.getTargetInfo()))
7092       H.DoneProcessing();
7093   } // TODO: handle other formats
7094 }
7095 
7096 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7097   // Str - The format string.  NOTE: this is NOT null-terminated!
7098   StringRef StrRef = FExpr->getString();
7099   const char *Str = StrRef.data();
7100   // Account for cases where the string literal is truncated in a declaration.
7101   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7102   assert(T && "String literal not of constant array type!");
7103   size_t TypeSize = T->getSize().getZExtValue();
7104   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7105   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7106                                                          getLangOpts(),
7107                                                          Context.getTargetInfo());
7108 }
7109 
7110 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7111 
7112 // Returns the related absolute value function that is larger, of 0 if one
7113 // does not exist.
7114 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7115   switch (AbsFunction) {
7116   default:
7117     return 0;
7118 
7119   case Builtin::BI__builtin_abs:
7120     return Builtin::BI__builtin_labs;
7121   case Builtin::BI__builtin_labs:
7122     return Builtin::BI__builtin_llabs;
7123   case Builtin::BI__builtin_llabs:
7124     return 0;
7125 
7126   case Builtin::BI__builtin_fabsf:
7127     return Builtin::BI__builtin_fabs;
7128   case Builtin::BI__builtin_fabs:
7129     return Builtin::BI__builtin_fabsl;
7130   case Builtin::BI__builtin_fabsl:
7131     return 0;
7132 
7133   case Builtin::BI__builtin_cabsf:
7134     return Builtin::BI__builtin_cabs;
7135   case Builtin::BI__builtin_cabs:
7136     return Builtin::BI__builtin_cabsl;
7137   case Builtin::BI__builtin_cabsl:
7138     return 0;
7139 
7140   case Builtin::BIabs:
7141     return Builtin::BIlabs;
7142   case Builtin::BIlabs:
7143     return Builtin::BIllabs;
7144   case Builtin::BIllabs:
7145     return 0;
7146 
7147   case Builtin::BIfabsf:
7148     return Builtin::BIfabs;
7149   case Builtin::BIfabs:
7150     return Builtin::BIfabsl;
7151   case Builtin::BIfabsl:
7152     return 0;
7153 
7154   case Builtin::BIcabsf:
7155    return Builtin::BIcabs;
7156   case Builtin::BIcabs:
7157     return Builtin::BIcabsl;
7158   case Builtin::BIcabsl:
7159     return 0;
7160   }
7161 }
7162 
7163 // Returns the argument type of the absolute value function.
7164 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7165                                              unsigned AbsType) {
7166   if (AbsType == 0)
7167     return QualType();
7168 
7169   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7170   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7171   if (Error != ASTContext::GE_None)
7172     return QualType();
7173 
7174   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7175   if (!FT)
7176     return QualType();
7177 
7178   if (FT->getNumParams() != 1)
7179     return QualType();
7180 
7181   return FT->getParamType(0);
7182 }
7183 
7184 // Returns the best absolute value function, or zero, based on type and
7185 // current absolute value function.
7186 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7187                                    unsigned AbsFunctionKind) {
7188   unsigned BestKind = 0;
7189   uint64_t ArgSize = Context.getTypeSize(ArgType);
7190   for (unsigned Kind = AbsFunctionKind; Kind != 0;
7191        Kind = getLargerAbsoluteValueFunction(Kind)) {
7192     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7193     if (Context.getTypeSize(ParamType) >= ArgSize) {
7194       if (BestKind == 0)
7195         BestKind = Kind;
7196       else if (Context.hasSameType(ParamType, ArgType)) {
7197         BestKind = Kind;
7198         break;
7199       }
7200     }
7201   }
7202   return BestKind;
7203 }
7204 
7205 enum AbsoluteValueKind {
7206   AVK_Integer,
7207   AVK_Floating,
7208   AVK_Complex
7209 };
7210 
7211 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7212   if (T->isIntegralOrEnumerationType())
7213     return AVK_Integer;
7214   if (T->isRealFloatingType())
7215     return AVK_Floating;
7216   if (T->isAnyComplexType())
7217     return AVK_Complex;
7218 
7219   llvm_unreachable("Type not integer, floating, or complex");
7220 }
7221 
7222 // Changes the absolute value function to a different type.  Preserves whether
7223 // the function is a builtin.
7224 static unsigned changeAbsFunction(unsigned AbsKind,
7225                                   AbsoluteValueKind ValueKind) {
7226   switch (ValueKind) {
7227   case AVK_Integer:
7228     switch (AbsKind) {
7229     default:
7230       return 0;
7231     case Builtin::BI__builtin_fabsf:
7232     case Builtin::BI__builtin_fabs:
7233     case Builtin::BI__builtin_fabsl:
7234     case Builtin::BI__builtin_cabsf:
7235     case Builtin::BI__builtin_cabs:
7236     case Builtin::BI__builtin_cabsl:
7237       return Builtin::BI__builtin_abs;
7238     case Builtin::BIfabsf:
7239     case Builtin::BIfabs:
7240     case Builtin::BIfabsl:
7241     case Builtin::BIcabsf:
7242     case Builtin::BIcabs:
7243     case Builtin::BIcabsl:
7244       return Builtin::BIabs;
7245     }
7246   case AVK_Floating:
7247     switch (AbsKind) {
7248     default:
7249       return 0;
7250     case Builtin::BI__builtin_abs:
7251     case Builtin::BI__builtin_labs:
7252     case Builtin::BI__builtin_llabs:
7253     case Builtin::BI__builtin_cabsf:
7254     case Builtin::BI__builtin_cabs:
7255     case Builtin::BI__builtin_cabsl:
7256       return Builtin::BI__builtin_fabsf;
7257     case Builtin::BIabs:
7258     case Builtin::BIlabs:
7259     case Builtin::BIllabs:
7260     case Builtin::BIcabsf:
7261     case Builtin::BIcabs:
7262     case Builtin::BIcabsl:
7263       return Builtin::BIfabsf;
7264     }
7265   case AVK_Complex:
7266     switch (AbsKind) {
7267     default:
7268       return 0;
7269     case Builtin::BI__builtin_abs:
7270     case Builtin::BI__builtin_labs:
7271     case Builtin::BI__builtin_llabs:
7272     case Builtin::BI__builtin_fabsf:
7273     case Builtin::BI__builtin_fabs:
7274     case Builtin::BI__builtin_fabsl:
7275       return Builtin::BI__builtin_cabsf;
7276     case Builtin::BIabs:
7277     case Builtin::BIlabs:
7278     case Builtin::BIllabs:
7279     case Builtin::BIfabsf:
7280     case Builtin::BIfabs:
7281     case Builtin::BIfabsl:
7282       return Builtin::BIcabsf;
7283     }
7284   }
7285   llvm_unreachable("Unable to convert function");
7286 }
7287 
7288 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
7289   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7290   if (!FnInfo)
7291     return 0;
7292 
7293   switch (FDecl->getBuiltinID()) {
7294   default:
7295     return 0;
7296   case Builtin::BI__builtin_abs:
7297   case Builtin::BI__builtin_fabs:
7298   case Builtin::BI__builtin_fabsf:
7299   case Builtin::BI__builtin_fabsl:
7300   case Builtin::BI__builtin_labs:
7301   case Builtin::BI__builtin_llabs:
7302   case Builtin::BI__builtin_cabs:
7303   case Builtin::BI__builtin_cabsf:
7304   case Builtin::BI__builtin_cabsl:
7305   case Builtin::BIabs:
7306   case Builtin::BIlabs:
7307   case Builtin::BIllabs:
7308   case Builtin::BIfabs:
7309   case Builtin::BIfabsf:
7310   case Builtin::BIfabsl:
7311   case Builtin::BIcabs:
7312   case Builtin::BIcabsf:
7313   case Builtin::BIcabsl:
7314     return FDecl->getBuiltinID();
7315   }
7316   llvm_unreachable("Unknown Builtin type");
7317 }
7318 
7319 // If the replacement is valid, emit a note with replacement function.
7320 // Additionally, suggest including the proper header if not already included.
7321 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7322                             unsigned AbsKind, QualType ArgType) {
7323   bool EmitHeaderHint = true;
7324   const char *HeaderName = nullptr;
7325   const char *FunctionName = nullptr;
7326   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7327     FunctionName = "std::abs";
7328     if (ArgType->isIntegralOrEnumerationType()) {
7329       HeaderName = "cstdlib";
7330     } else if (ArgType->isRealFloatingType()) {
7331       HeaderName = "cmath";
7332     } else {
7333       llvm_unreachable("Invalid Type");
7334     }
7335 
7336     // Lookup all std::abs
7337     if (NamespaceDecl *Std = S.getStdNamespace()) {
7338       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7339       R.suppressDiagnostics();
7340       S.LookupQualifiedName(R, Std);
7341 
7342       for (const auto *I : R) {
7343         const FunctionDecl *FDecl = nullptr;
7344         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7345           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7346         } else {
7347           FDecl = dyn_cast<FunctionDecl>(I);
7348         }
7349         if (!FDecl)
7350           continue;
7351 
7352         // Found std::abs(), check that they are the right ones.
7353         if (FDecl->getNumParams() != 1)
7354           continue;
7355 
7356         // Check that the parameter type can handle the argument.
7357         QualType ParamType = FDecl->getParamDecl(0)->getType();
7358         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7359             S.Context.getTypeSize(ArgType) <=
7360                 S.Context.getTypeSize(ParamType)) {
7361           // Found a function, don't need the header hint.
7362           EmitHeaderHint = false;
7363           break;
7364         }
7365       }
7366     }
7367   } else {
7368     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7369     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7370 
7371     if (HeaderName) {
7372       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7373       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7374       R.suppressDiagnostics();
7375       S.LookupName(R, S.getCurScope());
7376 
7377       if (R.isSingleResult()) {
7378         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7379         if (FD && FD->getBuiltinID() == AbsKind) {
7380           EmitHeaderHint = false;
7381         } else {
7382           return;
7383         }
7384       } else if (!R.empty()) {
7385         return;
7386       }
7387     }
7388   }
7389 
7390   S.Diag(Loc, diag::note_replace_abs_function)
7391       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7392 
7393   if (!HeaderName)
7394     return;
7395 
7396   if (!EmitHeaderHint)
7397     return;
7398 
7399   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7400                                                     << FunctionName;
7401 }
7402 
7403 template <std::size_t StrLen>
7404 static bool IsStdFunction(const FunctionDecl *FDecl,
7405                           const char (&Str)[StrLen]) {
7406   if (!FDecl)
7407     return false;
7408   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7409     return false;
7410   if (!FDecl->isInStdNamespace())
7411     return false;
7412 
7413   return true;
7414 }
7415 
7416 // Warn when using the wrong abs() function.
7417 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7418                                       const FunctionDecl *FDecl) {
7419   if (Call->getNumArgs() != 1)
7420     return;
7421 
7422   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7423   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7424   if (AbsKind == 0 && !IsStdAbs)
7425     return;
7426 
7427   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7428   QualType ParamType = Call->getArg(0)->getType();
7429 
7430   // Unsigned types cannot be negative.  Suggest removing the absolute value
7431   // function call.
7432   if (ArgType->isUnsignedIntegerType()) {
7433     const char *FunctionName =
7434         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7435     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7436     Diag(Call->getExprLoc(), diag::note_remove_abs)
7437         << FunctionName
7438         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7439     return;
7440   }
7441 
7442   // Taking the absolute value of a pointer is very suspicious, they probably
7443   // wanted to index into an array, dereference a pointer, call a function, etc.
7444   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7445     unsigned DiagType = 0;
7446     if (ArgType->isFunctionType())
7447       DiagType = 1;
7448     else if (ArgType->isArrayType())
7449       DiagType = 2;
7450 
7451     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7452     return;
7453   }
7454 
7455   // std::abs has overloads which prevent most of the absolute value problems
7456   // from occurring.
7457   if (IsStdAbs)
7458     return;
7459 
7460   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7461   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7462 
7463   // The argument and parameter are the same kind.  Check if they are the right
7464   // size.
7465   if (ArgValueKind == ParamValueKind) {
7466     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7467       return;
7468 
7469     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7470     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7471         << FDecl << ArgType << ParamType;
7472 
7473     if (NewAbsKind == 0)
7474       return;
7475 
7476     emitReplacement(*this, Call->getExprLoc(),
7477                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7478     return;
7479   }
7480 
7481   // ArgValueKind != ParamValueKind
7482   // The wrong type of absolute value function was used.  Attempt to find the
7483   // proper one.
7484   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7485   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7486   if (NewAbsKind == 0)
7487     return;
7488 
7489   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7490       << FDecl << ParamValueKind << ArgValueKind;
7491 
7492   emitReplacement(*this, Call->getExprLoc(),
7493                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7494 }
7495 
7496 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7497 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7498                                 const FunctionDecl *FDecl) {
7499   if (!Call || !FDecl) return;
7500 
7501   // Ignore template specializations and macros.
7502   if (inTemplateInstantiation()) return;
7503   if (Call->getExprLoc().isMacroID()) return;
7504 
7505   // Only care about the one template argument, two function parameter std::max
7506   if (Call->getNumArgs() != 2) return;
7507   if (!IsStdFunction(FDecl, "max")) return;
7508   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7509   if (!ArgList) return;
7510   if (ArgList->size() != 1) return;
7511 
7512   // Check that template type argument is unsigned integer.
7513   const auto& TA = ArgList->get(0);
7514   if (TA.getKind() != TemplateArgument::Type) return;
7515   QualType ArgType = TA.getAsType();
7516   if (!ArgType->isUnsignedIntegerType()) return;
7517 
7518   // See if either argument is a literal zero.
7519   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7520     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7521     if (!MTE) return false;
7522     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7523     if (!Num) return false;
7524     if (Num->getValue() != 0) return false;
7525     return true;
7526   };
7527 
7528   const Expr *FirstArg = Call->getArg(0);
7529   const Expr *SecondArg = Call->getArg(1);
7530   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7531   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7532 
7533   // Only warn when exactly one argument is zero.
7534   if (IsFirstArgZero == IsSecondArgZero) return;
7535 
7536   SourceRange FirstRange = FirstArg->getSourceRange();
7537   SourceRange SecondRange = SecondArg->getSourceRange();
7538 
7539   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7540 
7541   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7542       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7543 
7544   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7545   SourceRange RemovalRange;
7546   if (IsFirstArgZero) {
7547     RemovalRange = SourceRange(FirstRange.getBegin(),
7548                                SecondRange.getBegin().getLocWithOffset(-1));
7549   } else {
7550     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7551                                SecondRange.getEnd());
7552   }
7553 
7554   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7555         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7556         << FixItHint::CreateRemoval(RemovalRange);
7557 }
7558 
7559 //===--- CHECK: Standard memory functions ---------------------------------===//
7560 
7561 /// Takes the expression passed to the size_t parameter of functions
7562 /// such as memcmp, strncat, etc and warns if it's a comparison.
7563 ///
7564 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7565 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7566                                            IdentifierInfo *FnName,
7567                                            SourceLocation FnLoc,
7568                                            SourceLocation RParenLoc) {
7569   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7570   if (!Size)
7571     return false;
7572 
7573   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7574   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7575     return false;
7576 
7577   SourceRange SizeRange = Size->getSourceRange();
7578   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7579       << SizeRange << FnName;
7580   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7581       << FnName << FixItHint::CreateInsertion(
7582                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7583       << FixItHint::CreateRemoval(RParenLoc);
7584   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7585       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7586       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7587                                     ")");
7588 
7589   return true;
7590 }
7591 
7592 /// Determine whether the given type is or contains a dynamic class type
7593 /// (e.g., whether it has a vtable).
7594 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7595                                                      bool &IsContained) {
7596   // Look through array types while ignoring qualifiers.
7597   const Type *Ty = T->getBaseElementTypeUnsafe();
7598   IsContained = false;
7599 
7600   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7601   RD = RD ? RD->getDefinition() : nullptr;
7602   if (!RD || RD->isInvalidDecl())
7603     return nullptr;
7604 
7605   if (RD->isDynamicClass())
7606     return RD;
7607 
7608   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7609   // It's impossible for a class to transitively contain itself by value, so
7610   // infinite recursion is impossible.
7611   for (auto *FD : RD->fields()) {
7612     bool SubContained;
7613     if (const CXXRecordDecl *ContainedRD =
7614             getContainedDynamicClass(FD->getType(), SubContained)) {
7615       IsContained = true;
7616       return ContainedRD;
7617     }
7618   }
7619 
7620   return nullptr;
7621 }
7622 
7623 /// If E is a sizeof expression, returns its argument expression,
7624 /// otherwise returns NULL.
7625 static const Expr *getSizeOfExprArg(const Expr *E) {
7626   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7627       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7628     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7629       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7630 
7631   return nullptr;
7632 }
7633 
7634 /// If E is a sizeof expression, returns its argument type.
7635 static QualType getSizeOfArgType(const Expr *E) {
7636   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7637       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7638     if (SizeOf->getKind() == UETT_SizeOf)
7639       return SizeOf->getTypeOfArgument();
7640 
7641   return QualType();
7642 }
7643 
7644 namespace {
7645 
7646 struct SearchNonTrivialToInitializeField
7647     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7648   using Super =
7649       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7650 
7651   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7652 
7653   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7654                      SourceLocation SL) {
7655     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7656       asDerived().visitArray(PDIK, AT, SL);
7657       return;
7658     }
7659 
7660     Super::visitWithKind(PDIK, FT, SL);
7661   }
7662 
7663   void visitARCStrong(QualType FT, SourceLocation SL) {
7664     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7665   }
7666   void visitARCWeak(QualType FT, SourceLocation SL) {
7667     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7668   }
7669   void visitStruct(QualType FT, SourceLocation SL) {
7670     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7671       visit(FD->getType(), FD->getLocation());
7672   }
7673   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7674                   const ArrayType *AT, SourceLocation SL) {
7675     visit(getContext().getBaseElementType(AT), SL);
7676   }
7677   void visitTrivial(QualType FT, SourceLocation SL) {}
7678 
7679   static void diag(QualType RT, const Expr *E, Sema &S) {
7680     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7681   }
7682 
7683   ASTContext &getContext() { return S.getASTContext(); }
7684 
7685   const Expr *E;
7686   Sema &S;
7687 };
7688 
7689 struct SearchNonTrivialToCopyField
7690     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7691   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7692 
7693   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7694 
7695   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7696                      SourceLocation SL) {
7697     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7698       asDerived().visitArray(PCK, AT, SL);
7699       return;
7700     }
7701 
7702     Super::visitWithKind(PCK, FT, SL);
7703   }
7704 
7705   void visitARCStrong(QualType FT, SourceLocation SL) {
7706     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7707   }
7708   void visitARCWeak(QualType FT, SourceLocation SL) {
7709     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7710   }
7711   void visitStruct(QualType FT, SourceLocation SL) {
7712     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7713       visit(FD->getType(), FD->getLocation());
7714   }
7715   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7716                   SourceLocation SL) {
7717     visit(getContext().getBaseElementType(AT), SL);
7718   }
7719   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7720                 SourceLocation SL) {}
7721   void visitTrivial(QualType FT, SourceLocation SL) {}
7722   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7723 
7724   static void diag(QualType RT, const Expr *E, Sema &S) {
7725     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7726   }
7727 
7728   ASTContext &getContext() { return S.getASTContext(); }
7729 
7730   const Expr *E;
7731   Sema &S;
7732 };
7733 
7734 }
7735 
7736 /// Check for dangerous or invalid arguments to memset().
7737 ///
7738 /// This issues warnings on known problematic, dangerous or unspecified
7739 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7740 /// function calls.
7741 ///
7742 /// \param Call The call expression to diagnose.
7743 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7744                                    unsigned BId,
7745                                    IdentifierInfo *FnName) {
7746   assert(BId != 0);
7747 
7748   // It is possible to have a non-standard definition of memset.  Validate
7749   // we have enough arguments, and if not, abort further checking.
7750   unsigned ExpectedNumArgs =
7751       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7752   if (Call->getNumArgs() < ExpectedNumArgs)
7753     return;
7754 
7755   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7756                       BId == Builtin::BIstrndup ? 1 : 2);
7757   unsigned LenArg =
7758       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7759   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7760 
7761   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7762                                      Call->getLocStart(), Call->getRParenLoc()))
7763     return;
7764 
7765   // We have special checking when the length is a sizeof expression.
7766   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7767   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7768   llvm::FoldingSetNodeID SizeOfArgID;
7769 
7770   // Although widely used, 'bzero' is not a standard function. Be more strict
7771   // with the argument types before allowing diagnostics and only allow the
7772   // form bzero(ptr, sizeof(...)).
7773   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7774   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7775     return;
7776 
7777   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7778     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7779     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7780 
7781     QualType DestTy = Dest->getType();
7782     QualType PointeeTy;
7783     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7784       PointeeTy = DestPtrTy->getPointeeType();
7785 
7786       // Never warn about void type pointers. This can be used to suppress
7787       // false positives.
7788       if (PointeeTy->isVoidType())
7789         continue;
7790 
7791       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7792       // actually comparing the expressions for equality. Because computing the
7793       // expression IDs can be expensive, we only do this if the diagnostic is
7794       // enabled.
7795       if (SizeOfArg &&
7796           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7797                            SizeOfArg->getExprLoc())) {
7798         // We only compute IDs for expressions if the warning is enabled, and
7799         // cache the sizeof arg's ID.
7800         if (SizeOfArgID == llvm::FoldingSetNodeID())
7801           SizeOfArg->Profile(SizeOfArgID, Context, true);
7802         llvm::FoldingSetNodeID DestID;
7803         Dest->Profile(DestID, Context, true);
7804         if (DestID == SizeOfArgID) {
7805           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7806           //       over sizeof(src) as well.
7807           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7808           StringRef ReadableName = FnName->getName();
7809 
7810           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7811             if (UnaryOp->getOpcode() == UO_AddrOf)
7812               ActionIdx = 1; // If its an address-of operator, just remove it.
7813           if (!PointeeTy->isIncompleteType() &&
7814               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7815             ActionIdx = 2; // If the pointee's size is sizeof(char),
7816                            // suggest an explicit length.
7817 
7818           // If the function is defined as a builtin macro, do not show macro
7819           // expansion.
7820           SourceLocation SL = SizeOfArg->getExprLoc();
7821           SourceRange DSR = Dest->getSourceRange();
7822           SourceRange SSR = SizeOfArg->getSourceRange();
7823           SourceManager &SM = getSourceManager();
7824 
7825           if (SM.isMacroArgExpansion(SL)) {
7826             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7827             SL = SM.getSpellingLoc(SL);
7828             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7829                              SM.getSpellingLoc(DSR.getEnd()));
7830             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7831                              SM.getSpellingLoc(SSR.getEnd()));
7832           }
7833 
7834           DiagRuntimeBehavior(SL, SizeOfArg,
7835                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7836                                 << ReadableName
7837                                 << PointeeTy
7838                                 << DestTy
7839                                 << DSR
7840                                 << SSR);
7841           DiagRuntimeBehavior(SL, SizeOfArg,
7842                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7843                                 << ActionIdx
7844                                 << SSR);
7845 
7846           break;
7847         }
7848       }
7849 
7850       // Also check for cases where the sizeof argument is the exact same
7851       // type as the memory argument, and where it points to a user-defined
7852       // record type.
7853       if (SizeOfArgTy != QualType()) {
7854         if (PointeeTy->isRecordType() &&
7855             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7856           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7857                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7858                                 << FnName << SizeOfArgTy << ArgIdx
7859                                 << PointeeTy << Dest->getSourceRange()
7860                                 << LenExpr->getSourceRange());
7861           break;
7862         }
7863       }
7864     } else if (DestTy->isArrayType()) {
7865       PointeeTy = DestTy;
7866     }
7867 
7868     if (PointeeTy == QualType())
7869       continue;
7870 
7871     // Always complain about dynamic classes.
7872     bool IsContained;
7873     if (const CXXRecordDecl *ContainedRD =
7874             getContainedDynamicClass(PointeeTy, IsContained)) {
7875 
7876       unsigned OperationType = 0;
7877       // "overwritten" if we're warning about the destination for any call
7878       // but memcmp; otherwise a verb appropriate to the call.
7879       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7880         if (BId == Builtin::BImemcpy)
7881           OperationType = 1;
7882         else if(BId == Builtin::BImemmove)
7883           OperationType = 2;
7884         else if (BId == Builtin::BImemcmp)
7885           OperationType = 3;
7886       }
7887 
7888       DiagRuntimeBehavior(
7889         Dest->getExprLoc(), Dest,
7890         PDiag(diag::warn_dyn_class_memaccess)
7891           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7892           << FnName << IsContained << ContainedRD << OperationType
7893           << Call->getCallee()->getSourceRange());
7894     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7895              BId != Builtin::BImemset)
7896       DiagRuntimeBehavior(
7897         Dest->getExprLoc(), Dest,
7898         PDiag(diag::warn_arc_object_memaccess)
7899           << ArgIdx << FnName << PointeeTy
7900           << Call->getCallee()->getSourceRange());
7901     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7902       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7903           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7904         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7905                             PDiag(diag::warn_cstruct_memaccess)
7906                                 << ArgIdx << FnName << PointeeTy << 0);
7907         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
7908       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
7909                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
7910         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7911                             PDiag(diag::warn_cstruct_memaccess)
7912                                 << ArgIdx << FnName << PointeeTy << 1);
7913         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
7914       } else {
7915         continue;
7916       }
7917     } else
7918       continue;
7919 
7920     DiagRuntimeBehavior(
7921       Dest->getExprLoc(), Dest,
7922       PDiag(diag::note_bad_memaccess_silence)
7923         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7924     break;
7925   }
7926 }
7927 
7928 // A little helper routine: ignore addition and subtraction of integer literals.
7929 // This intentionally does not ignore all integer constant expressions because
7930 // we don't want to remove sizeof().
7931 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7932   Ex = Ex->IgnoreParenCasts();
7933 
7934   while (true) {
7935     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7936     if (!BO || !BO->isAdditiveOp())
7937       break;
7938 
7939     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7940     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7941 
7942     if (isa<IntegerLiteral>(RHS))
7943       Ex = LHS;
7944     else if (isa<IntegerLiteral>(LHS))
7945       Ex = RHS;
7946     else
7947       break;
7948   }
7949 
7950   return Ex;
7951 }
7952 
7953 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7954                                                       ASTContext &Context) {
7955   // Only handle constant-sized or VLAs, but not flexible members.
7956   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7957     // Only issue the FIXIT for arrays of size > 1.
7958     if (CAT->getSize().getSExtValue() <= 1)
7959       return false;
7960   } else if (!Ty->isVariableArrayType()) {
7961     return false;
7962   }
7963   return true;
7964 }
7965 
7966 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7967 // be the size of the source, instead of the destination.
7968 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7969                                     IdentifierInfo *FnName) {
7970 
7971   // Don't crash if the user has the wrong number of arguments
7972   unsigned NumArgs = Call->getNumArgs();
7973   if ((NumArgs != 3) && (NumArgs != 4))
7974     return;
7975 
7976   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7977   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7978   const Expr *CompareWithSrc = nullptr;
7979 
7980   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7981                                      Call->getLocStart(), Call->getRParenLoc()))
7982     return;
7983 
7984   // Look for 'strlcpy(dst, x, sizeof(x))'
7985   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7986     CompareWithSrc = Ex;
7987   else {
7988     // Look for 'strlcpy(dst, x, strlen(x))'
7989     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7990       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7991           SizeCall->getNumArgs() == 1)
7992         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7993     }
7994   }
7995 
7996   if (!CompareWithSrc)
7997     return;
7998 
7999   // Determine if the argument to sizeof/strlen is equal to the source
8000   // argument.  In principle there's all kinds of things you could do
8001   // here, for instance creating an == expression and evaluating it with
8002   // EvaluateAsBooleanCondition, but this uses a more direct technique:
8003   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8004   if (!SrcArgDRE)
8005     return;
8006 
8007   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8008   if (!CompareWithSrcDRE ||
8009       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8010     return;
8011 
8012   const Expr *OriginalSizeArg = Call->getArg(2);
8013   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8014     << OriginalSizeArg->getSourceRange() << FnName;
8015 
8016   // Output a FIXIT hint if the destination is an array (rather than a
8017   // pointer to an array).  This could be enhanced to handle some
8018   // pointers if we know the actual size, like if DstArg is 'array+2'
8019   // we could say 'sizeof(array)-2'.
8020   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
8021   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
8022     return;
8023 
8024   SmallString<128> sizeString;
8025   llvm::raw_svector_ostream OS(sizeString);
8026   OS << "sizeof(";
8027   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8028   OS << ")";
8029 
8030   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8031     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8032                                     OS.str());
8033 }
8034 
8035 /// Check if two expressions refer to the same declaration.
8036 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8037   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8038     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8039       return D1->getDecl() == D2->getDecl();
8040   return false;
8041 }
8042 
8043 static const Expr *getStrlenExprArg(const Expr *E) {
8044   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8045     const FunctionDecl *FD = CE->getDirectCallee();
8046     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
8047       return nullptr;
8048     return CE->getArg(0)->IgnoreParenCasts();
8049   }
8050   return nullptr;
8051 }
8052 
8053 // Warn on anti-patterns as the 'size' argument to strncat.
8054 // The correct size argument should look like following:
8055 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8056 void Sema::CheckStrncatArguments(const CallExpr *CE,
8057                                  IdentifierInfo *FnName) {
8058   // Don't crash if the user has the wrong number of arguments.
8059   if (CE->getNumArgs() < 3)
8060     return;
8061   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8062   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8063   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8064 
8065   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8066                                      CE->getRParenLoc()))
8067     return;
8068 
8069   // Identify common expressions, which are wrongly used as the size argument
8070   // to strncat and may lead to buffer overflows.
8071   unsigned PatternType = 0;
8072   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8073     // - sizeof(dst)
8074     if (referToTheSameDecl(SizeOfArg, DstArg))
8075       PatternType = 1;
8076     // - sizeof(src)
8077     else if (referToTheSameDecl(SizeOfArg, SrcArg))
8078       PatternType = 2;
8079   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8080     if (BE->getOpcode() == BO_Sub) {
8081       const Expr *L = BE->getLHS()->IgnoreParenCasts();
8082       const Expr *R = BE->getRHS()->IgnoreParenCasts();
8083       // - sizeof(dst) - strlen(dst)
8084       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8085           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8086         PatternType = 1;
8087       // - sizeof(src) - (anything)
8088       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8089         PatternType = 2;
8090     }
8091   }
8092 
8093   if (PatternType == 0)
8094     return;
8095 
8096   // Generate the diagnostic.
8097   SourceLocation SL = LenArg->getLocStart();
8098   SourceRange SR = LenArg->getSourceRange();
8099   SourceManager &SM = getSourceManager();
8100 
8101   // If the function is defined as a builtin macro, do not show macro expansion.
8102   if (SM.isMacroArgExpansion(SL)) {
8103     SL = SM.getSpellingLoc(SL);
8104     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8105                      SM.getSpellingLoc(SR.getEnd()));
8106   }
8107 
8108   // Check if the destination is an array (rather than a pointer to an array).
8109   QualType DstTy = DstArg->getType();
8110   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8111                                                                     Context);
8112   if (!isKnownSizeArray) {
8113     if (PatternType == 1)
8114       Diag(SL, diag::warn_strncat_wrong_size) << SR;
8115     else
8116       Diag(SL, diag::warn_strncat_src_size) << SR;
8117     return;
8118   }
8119 
8120   if (PatternType == 1)
8121     Diag(SL, diag::warn_strncat_large_size) << SR;
8122   else
8123     Diag(SL, diag::warn_strncat_src_size) << SR;
8124 
8125   SmallString<128> sizeString;
8126   llvm::raw_svector_ostream OS(sizeString);
8127   OS << "sizeof(";
8128   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8129   OS << ") - ";
8130   OS << "strlen(";
8131   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
8132   OS << ") - 1";
8133 
8134   Diag(SL, diag::note_strncat_wrong_size)
8135     << FixItHint::CreateReplacement(SR, OS.str());
8136 }
8137 
8138 //===--- CHECK: Return Address of Stack Variable --------------------------===//
8139 
8140 static const Expr *EvalVal(const Expr *E,
8141                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8142                            const Decl *ParentDecl);
8143 static const Expr *EvalAddr(const Expr *E,
8144                             SmallVectorImpl<const DeclRefExpr *> &refVars,
8145                             const Decl *ParentDecl);
8146 
8147 /// CheckReturnStackAddr - Check if a return statement returns the address
8148 ///   of a stack variable.
8149 static void
8150 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8151                      SourceLocation ReturnLoc) {
8152   const Expr *stackE = nullptr;
8153   SmallVector<const DeclRefExpr *, 8> refVars;
8154 
8155   // Perform checking for returned stack addresses, local blocks,
8156   // label addresses or references to temporaries.
8157   if (lhsType->isPointerType() ||
8158       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
8159     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
8160   } else if (lhsType->isReferenceType()) {
8161     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
8162   }
8163 
8164   if (!stackE)
8165     return; // Nothing suspicious was found.
8166 
8167   // Parameters are initialized in the calling scope, so taking the address
8168   // of a parameter reference doesn't need a warning.
8169   for (auto *DRE : refVars)
8170     if (isa<ParmVarDecl>(DRE->getDecl()))
8171       return;
8172 
8173   SourceLocation diagLoc;
8174   SourceRange diagRange;
8175   if (refVars.empty()) {
8176     diagLoc = stackE->getLocStart();
8177     diagRange = stackE->getSourceRange();
8178   } else {
8179     // We followed through a reference variable. 'stackE' contains the
8180     // problematic expression but we will warn at the return statement pointing
8181     // at the reference variable. We will later display the "trail" of
8182     // reference variables using notes.
8183     diagLoc = refVars[0]->getLocStart();
8184     diagRange = refVars[0]->getSourceRange();
8185   }
8186 
8187   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8188     // address of local var
8189     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
8190      << DR->getDecl()->getDeclName() << diagRange;
8191   } else if (isa<BlockExpr>(stackE)) { // local block.
8192     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
8193   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
8194     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
8195   } else { // local temporary.
8196     // If there is an LValue->RValue conversion, then the value of the
8197     // reference type is used, not the reference.
8198     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8199       if (ICE->getCastKind() == CK_LValueToRValue) {
8200         return;
8201       }
8202     }
8203     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8204      << lhsType->isReferenceType() << diagRange;
8205   }
8206 
8207   // Display the "trail" of reference variables that we followed until we
8208   // found the problematic expression using notes.
8209   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
8210     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
8211     // If this var binds to another reference var, show the range of the next
8212     // var, otherwise the var binds to the problematic expression, in which case
8213     // show the range of the expression.
8214     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8215                                     : stackE->getSourceRange();
8216     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8217         << VD->getDeclName() << range;
8218   }
8219 }
8220 
8221 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8222 ///  check if the expression in a return statement evaluates to an address
8223 ///  to a location on the stack, a local block, an address of a label, or a
8224 ///  reference to local temporary. The recursion is used to traverse the
8225 ///  AST of the return expression, with recursion backtracking when we
8226 ///  encounter a subexpression that (1) clearly does not lead to one of the
8227 ///  above problematic expressions (2) is something we cannot determine leads to
8228 ///  a problematic expression based on such local checking.
8229 ///
8230 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
8231 ///  the expression that they point to. Such variables are added to the
8232 ///  'refVars' vector so that we know what the reference variable "trail" was.
8233 ///
8234 ///  EvalAddr processes expressions that are pointers that are used as
8235 ///  references (and not L-values).  EvalVal handles all other values.
8236 ///  At the base case of the recursion is a check for the above problematic
8237 ///  expressions.
8238 ///
8239 ///  This implementation handles:
8240 ///
8241 ///   * pointer-to-pointer casts
8242 ///   * implicit conversions from array references to pointers
8243 ///   * taking the address of fields
8244 ///   * arbitrary interplay between "&" and "*" operators
8245 ///   * pointer arithmetic from an address of a stack variable
8246 ///   * taking the address of an array element where the array is on the stack
8247 static const Expr *EvalAddr(const Expr *E,
8248                             SmallVectorImpl<const DeclRefExpr *> &refVars,
8249                             const Decl *ParentDecl) {
8250   if (E->isTypeDependent())
8251     return nullptr;
8252 
8253   // We should only be called for evaluating pointer expressions.
8254   assert((E->getType()->isAnyPointerType() ||
8255           E->getType()->isBlockPointerType() ||
8256           E->getType()->isObjCQualifiedIdType()) &&
8257          "EvalAddr only works on pointers");
8258 
8259   E = E->IgnoreParens();
8260 
8261   // Our "symbolic interpreter" is just a dispatch off the currently
8262   // viewed AST node.  We then recursively traverse the AST by calling
8263   // EvalAddr and EvalVal appropriately.
8264   switch (E->getStmtClass()) {
8265   case Stmt::DeclRefExprClass: {
8266     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8267 
8268     // If we leave the immediate function, the lifetime isn't about to end.
8269     if (DR->refersToEnclosingVariableOrCapture())
8270       return nullptr;
8271 
8272     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
8273       // If this is a reference variable, follow through to the expression that
8274       // it points to.
8275       if (V->hasLocalStorage() &&
8276           V->getType()->isReferenceType() && V->hasInit()) {
8277         // Add the reference variable to the "trail".
8278         refVars.push_back(DR);
8279         return EvalAddr(V->getInit(), refVars, ParentDecl);
8280       }
8281 
8282     return nullptr;
8283   }
8284 
8285   case Stmt::UnaryOperatorClass: {
8286     // The only unary operator that make sense to handle here
8287     // is AddrOf.  All others don't make sense as pointers.
8288     const UnaryOperator *U = cast<UnaryOperator>(E);
8289 
8290     if (U->getOpcode() == UO_AddrOf)
8291       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
8292     return nullptr;
8293   }
8294 
8295   case Stmt::BinaryOperatorClass: {
8296     // Handle pointer arithmetic.  All other binary operators are not valid
8297     // in this context.
8298     const BinaryOperator *B = cast<BinaryOperator>(E);
8299     BinaryOperatorKind op = B->getOpcode();
8300 
8301     if (op != BO_Add && op != BO_Sub)
8302       return nullptr;
8303 
8304     const Expr *Base = B->getLHS();
8305 
8306     // Determine which argument is the real pointer base.  It could be
8307     // the RHS argument instead of the LHS.
8308     if (!Base->getType()->isPointerType())
8309       Base = B->getRHS();
8310 
8311     assert(Base->getType()->isPointerType());
8312     return EvalAddr(Base, refVars, ParentDecl);
8313   }
8314 
8315   // For conditional operators we need to see if either the LHS or RHS are
8316   // valid DeclRefExpr*s.  If one of them is valid, we return it.
8317   case Stmt::ConditionalOperatorClass: {
8318     const ConditionalOperator *C = cast<ConditionalOperator>(E);
8319 
8320     // Handle the GNU extension for missing LHS.
8321     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
8322     if (const Expr *LHSExpr = C->getLHS()) {
8323       // In C++, we can have a throw-expression, which has 'void' type.
8324       if (!LHSExpr->getType()->isVoidType())
8325         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
8326           return LHS;
8327     }
8328 
8329     // In C++, we can have a throw-expression, which has 'void' type.
8330     if (C->getRHS()->getType()->isVoidType())
8331       return nullptr;
8332 
8333     return EvalAddr(C->getRHS(), refVars, ParentDecl);
8334   }
8335 
8336   case Stmt::BlockExprClass:
8337     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
8338       return E; // local block.
8339     return nullptr;
8340 
8341   case Stmt::AddrLabelExprClass:
8342     return E; // address of label.
8343 
8344   case Stmt::ExprWithCleanupsClass:
8345     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8346                     ParentDecl);
8347 
8348   // For casts, we need to handle conversions from arrays to
8349   // pointer values, and pointer-to-pointer conversions.
8350   case Stmt::ImplicitCastExprClass:
8351   case Stmt::CStyleCastExprClass:
8352   case Stmt::CXXFunctionalCastExprClass:
8353   case Stmt::ObjCBridgedCastExprClass:
8354   case Stmt::CXXStaticCastExprClass:
8355   case Stmt::CXXDynamicCastExprClass:
8356   case Stmt::CXXConstCastExprClass:
8357   case Stmt::CXXReinterpretCastExprClass: {
8358     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
8359     switch (cast<CastExpr>(E)->getCastKind()) {
8360     case CK_LValueToRValue:
8361     case CK_NoOp:
8362     case CK_BaseToDerived:
8363     case CK_DerivedToBase:
8364     case CK_UncheckedDerivedToBase:
8365     case CK_Dynamic:
8366     case CK_CPointerToObjCPointerCast:
8367     case CK_BlockPointerToObjCPointerCast:
8368     case CK_AnyPointerToBlockPointerCast:
8369       return EvalAddr(SubExpr, refVars, ParentDecl);
8370 
8371     case CK_ArrayToPointerDecay:
8372       return EvalVal(SubExpr, refVars, ParentDecl);
8373 
8374     case CK_BitCast:
8375       if (SubExpr->getType()->isAnyPointerType() ||
8376           SubExpr->getType()->isBlockPointerType() ||
8377           SubExpr->getType()->isObjCQualifiedIdType())
8378         return EvalAddr(SubExpr, refVars, ParentDecl);
8379       else
8380         return nullptr;
8381 
8382     default:
8383       return nullptr;
8384     }
8385   }
8386 
8387   case Stmt::MaterializeTemporaryExprClass:
8388     if (const Expr *Result =
8389             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8390                      refVars, ParentDecl))
8391       return Result;
8392     return E;
8393 
8394   // Everything else: we simply don't reason about them.
8395   default:
8396     return nullptr;
8397   }
8398 }
8399 
8400 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
8401 ///   See the comments for EvalAddr for more details.
8402 static const Expr *EvalVal(const Expr *E,
8403                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8404                            const Decl *ParentDecl) {
8405   do {
8406     // We should only be called for evaluating non-pointer expressions, or
8407     // expressions with a pointer type that are not used as references but
8408     // instead
8409     // are l-values (e.g., DeclRefExpr with a pointer type).
8410 
8411     // Our "symbolic interpreter" is just a dispatch off the currently
8412     // viewed AST node.  We then recursively traverse the AST by calling
8413     // EvalAddr and EvalVal appropriately.
8414 
8415     E = E->IgnoreParens();
8416     switch (E->getStmtClass()) {
8417     case Stmt::ImplicitCastExprClass: {
8418       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8419       if (IE->getValueKind() == VK_LValue) {
8420         E = IE->getSubExpr();
8421         continue;
8422       }
8423       return nullptr;
8424     }
8425 
8426     case Stmt::ExprWithCleanupsClass:
8427       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8428                      ParentDecl);
8429 
8430     case Stmt::DeclRefExprClass: {
8431       // When we hit a DeclRefExpr we are looking at code that refers to a
8432       // variable's name. If it's not a reference variable we check if it has
8433       // local storage within the function, and if so, return the expression.
8434       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8435 
8436       // If we leave the immediate function, the lifetime isn't about to end.
8437       if (DR->refersToEnclosingVariableOrCapture())
8438         return nullptr;
8439 
8440       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8441         // Check if it refers to itself, e.g. "int& i = i;".
8442         if (V == ParentDecl)
8443           return DR;
8444 
8445         if (V->hasLocalStorage()) {
8446           if (!V->getType()->isReferenceType())
8447             return DR;
8448 
8449           // Reference variable, follow through to the expression that
8450           // it points to.
8451           if (V->hasInit()) {
8452             // Add the reference variable to the "trail".
8453             refVars.push_back(DR);
8454             return EvalVal(V->getInit(), refVars, V);
8455           }
8456         }
8457       }
8458 
8459       return nullptr;
8460     }
8461 
8462     case Stmt::UnaryOperatorClass: {
8463       // The only unary operator that make sense to handle here
8464       // is Deref.  All others don't resolve to a "name."  This includes
8465       // handling all sorts of rvalues passed to a unary operator.
8466       const UnaryOperator *U = cast<UnaryOperator>(E);
8467 
8468       if (U->getOpcode() == UO_Deref)
8469         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8470 
8471       return nullptr;
8472     }
8473 
8474     case Stmt::ArraySubscriptExprClass: {
8475       // Array subscripts are potential references to data on the stack.  We
8476       // retrieve the DeclRefExpr* for the array variable if it indeed
8477       // has local storage.
8478       const auto *ASE = cast<ArraySubscriptExpr>(E);
8479       if (ASE->isTypeDependent())
8480         return nullptr;
8481       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8482     }
8483 
8484     case Stmt::OMPArraySectionExprClass: {
8485       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8486                       ParentDecl);
8487     }
8488 
8489     case Stmt::ConditionalOperatorClass: {
8490       // For conditional operators we need to see if either the LHS or RHS are
8491       // non-NULL Expr's.  If one is non-NULL, we return it.
8492       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8493 
8494       // Handle the GNU extension for missing LHS.
8495       if (const Expr *LHSExpr = C->getLHS()) {
8496         // In C++, we can have a throw-expression, which has 'void' type.
8497         if (!LHSExpr->getType()->isVoidType())
8498           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8499             return LHS;
8500       }
8501 
8502       // In C++, we can have a throw-expression, which has 'void' type.
8503       if (C->getRHS()->getType()->isVoidType())
8504         return nullptr;
8505 
8506       return EvalVal(C->getRHS(), refVars, ParentDecl);
8507     }
8508 
8509     // Accesses to members are potential references to data on the stack.
8510     case Stmt::MemberExprClass: {
8511       const MemberExpr *M = cast<MemberExpr>(E);
8512 
8513       // Check for indirect access.  We only want direct field accesses.
8514       if (M->isArrow())
8515         return nullptr;
8516 
8517       // Check whether the member type is itself a reference, in which case
8518       // we're not going to refer to the member, but to what the member refers
8519       // to.
8520       if (M->getMemberDecl()->getType()->isReferenceType())
8521         return nullptr;
8522 
8523       return EvalVal(M->getBase(), refVars, ParentDecl);
8524     }
8525 
8526     case Stmt::MaterializeTemporaryExprClass:
8527       if (const Expr *Result =
8528               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8529                       refVars, ParentDecl))
8530         return Result;
8531       return E;
8532 
8533     default:
8534       // Check that we don't return or take the address of a reference to a
8535       // temporary. This is only useful in C++.
8536       if (!E->isTypeDependent() && E->isRValue())
8537         return E;
8538 
8539       // Everything else: we simply don't reason about them.
8540       return nullptr;
8541     }
8542   } while (true);
8543 }
8544 
8545 void
8546 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8547                          SourceLocation ReturnLoc,
8548                          bool isObjCMethod,
8549                          const AttrVec *Attrs,
8550                          const FunctionDecl *FD) {
8551   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8552 
8553   // Check if the return value is null but should not be.
8554   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8555        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8556       CheckNonNullExpr(*this, RetValExp))
8557     Diag(ReturnLoc, diag::warn_null_ret)
8558       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8559 
8560   // C++11 [basic.stc.dynamic.allocation]p4:
8561   //   If an allocation function declared with a non-throwing
8562   //   exception-specification fails to allocate storage, it shall return
8563   //   a null pointer. Any other allocation function that fails to allocate
8564   //   storage shall indicate failure only by throwing an exception [...]
8565   if (FD) {
8566     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8567     if (Op == OO_New || Op == OO_Array_New) {
8568       const FunctionProtoType *Proto
8569         = FD->getType()->castAs<FunctionProtoType>();
8570       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
8571           CheckNonNullExpr(*this, RetValExp))
8572         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8573           << FD << getLangOpts().CPlusPlus11;
8574     }
8575   }
8576 }
8577 
8578 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8579 
8580 /// Check for comparisons of floating point operands using != and ==.
8581 /// Issue a warning if these are no self-comparisons, as they are not likely
8582 /// to do what the programmer intended.
8583 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8584   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8585   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8586 
8587   // Special case: check for x == x (which is OK).
8588   // Do not emit warnings for such cases.
8589   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8590     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8591       if (DRL->getDecl() == DRR->getDecl())
8592         return;
8593 
8594   // Special case: check for comparisons against literals that can be exactly
8595   //  represented by APFloat.  In such cases, do not emit a warning.  This
8596   //  is a heuristic: often comparison against such literals are used to
8597   //  detect if a value in a variable has not changed.  This clearly can
8598   //  lead to false negatives.
8599   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8600     if (FLL->isExact())
8601       return;
8602   } else
8603     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8604       if (FLR->isExact())
8605         return;
8606 
8607   // Check for comparisons with builtin types.
8608   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8609     if (CL->getBuiltinCallee())
8610       return;
8611 
8612   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8613     if (CR->getBuiltinCallee())
8614       return;
8615 
8616   // Emit the diagnostic.
8617   Diag(Loc, diag::warn_floatingpoint_eq)
8618     << LHS->getSourceRange() << RHS->getSourceRange();
8619 }
8620 
8621 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8622 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8623 
8624 namespace {
8625 
8626 /// Structure recording the 'active' range of an integer-valued
8627 /// expression.
8628 struct IntRange {
8629   /// The number of bits active in the int.
8630   unsigned Width;
8631 
8632   /// True if the int is known not to have negative values.
8633   bool NonNegative;
8634 
8635   IntRange(unsigned Width, bool NonNegative)
8636       : Width(Width), NonNegative(NonNegative) {}
8637 
8638   /// Returns the range of the bool type.
8639   static IntRange forBoolType() {
8640     return IntRange(1, true);
8641   }
8642 
8643   /// Returns the range of an opaque value of the given integral type.
8644   static IntRange forValueOfType(ASTContext &C, QualType T) {
8645     return forValueOfCanonicalType(C,
8646                           T->getCanonicalTypeInternal().getTypePtr());
8647   }
8648 
8649   /// Returns the range of an opaque value of a canonical integral type.
8650   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8651     assert(T->isCanonicalUnqualified());
8652 
8653     if (const VectorType *VT = dyn_cast<VectorType>(T))
8654       T = VT->getElementType().getTypePtr();
8655     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8656       T = CT->getElementType().getTypePtr();
8657     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8658       T = AT->getValueType().getTypePtr();
8659 
8660     if (!C.getLangOpts().CPlusPlus) {
8661       // For enum types in C code, use the underlying datatype.
8662       if (const EnumType *ET = dyn_cast<EnumType>(T))
8663         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8664     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8665       // For enum types in C++, use the known bit width of the enumerators.
8666       EnumDecl *Enum = ET->getDecl();
8667       // In C++11, enums can have a fixed underlying type. Use this type to
8668       // compute the range.
8669       if (Enum->isFixed()) {
8670         return IntRange(C.getIntWidth(QualType(T, 0)),
8671                         !ET->isSignedIntegerOrEnumerationType());
8672       }
8673 
8674       unsigned NumPositive = Enum->getNumPositiveBits();
8675       unsigned NumNegative = Enum->getNumNegativeBits();
8676 
8677       if (NumNegative == 0)
8678         return IntRange(NumPositive, true/*NonNegative*/);
8679       else
8680         return IntRange(std::max(NumPositive + 1, NumNegative),
8681                         false/*NonNegative*/);
8682     }
8683 
8684     const BuiltinType *BT = cast<BuiltinType>(T);
8685     assert(BT->isInteger());
8686 
8687     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8688   }
8689 
8690   /// Returns the "target" range of a canonical integral type, i.e.
8691   /// the range of values expressible in the type.
8692   ///
8693   /// This matches forValueOfCanonicalType except that enums have the
8694   /// full range of their type, not the range of their enumerators.
8695   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8696     assert(T->isCanonicalUnqualified());
8697 
8698     if (const VectorType *VT = dyn_cast<VectorType>(T))
8699       T = VT->getElementType().getTypePtr();
8700     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8701       T = CT->getElementType().getTypePtr();
8702     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8703       T = AT->getValueType().getTypePtr();
8704     if (const EnumType *ET = dyn_cast<EnumType>(T))
8705       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8706 
8707     const BuiltinType *BT = cast<BuiltinType>(T);
8708     assert(BT->isInteger());
8709 
8710     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8711   }
8712 
8713   /// Returns the supremum of two ranges: i.e. their conservative merge.
8714   static IntRange join(IntRange L, IntRange R) {
8715     return IntRange(std::max(L.Width, R.Width),
8716                     L.NonNegative && R.NonNegative);
8717   }
8718 
8719   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8720   static IntRange meet(IntRange L, IntRange R) {
8721     return IntRange(std::min(L.Width, R.Width),
8722                     L.NonNegative || R.NonNegative);
8723   }
8724 };
8725 
8726 } // namespace
8727 
8728 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8729                               unsigned MaxWidth) {
8730   if (value.isSigned() && value.isNegative())
8731     return IntRange(value.getMinSignedBits(), false);
8732 
8733   if (value.getBitWidth() > MaxWidth)
8734     value = value.trunc(MaxWidth);
8735 
8736   // isNonNegative() just checks the sign bit without considering
8737   // signedness.
8738   return IntRange(value.getActiveBits(), true);
8739 }
8740 
8741 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8742                               unsigned MaxWidth) {
8743   if (result.isInt())
8744     return GetValueRange(C, result.getInt(), MaxWidth);
8745 
8746   if (result.isVector()) {
8747     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8748     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8749       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8750       R = IntRange::join(R, El);
8751     }
8752     return R;
8753   }
8754 
8755   if (result.isComplexInt()) {
8756     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8757     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8758     return IntRange::join(R, I);
8759   }
8760 
8761   // This can happen with lossless casts to intptr_t of "based" lvalues.
8762   // Assume it might use arbitrary bits.
8763   // FIXME: The only reason we need to pass the type in here is to get
8764   // the sign right on this one case.  It would be nice if APValue
8765   // preserved this.
8766   assert(result.isLValue() || result.isAddrLabelDiff());
8767   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8768 }
8769 
8770 static QualType GetExprType(const Expr *E) {
8771   QualType Ty = E->getType();
8772   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8773     Ty = AtomicRHS->getValueType();
8774   return Ty;
8775 }
8776 
8777 /// Pseudo-evaluate the given integer expression, estimating the
8778 /// range of values it might take.
8779 ///
8780 /// \param MaxWidth - the width to which the value will be truncated
8781 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8782   E = E->IgnoreParens();
8783 
8784   // Try a full evaluation first.
8785   Expr::EvalResult result;
8786   if (E->EvaluateAsRValue(result, C))
8787     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8788 
8789   // I think we only want to look through implicit casts here; if the
8790   // user has an explicit widening cast, we should treat the value as
8791   // being of the new, wider type.
8792   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8793     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8794       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8795 
8796     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8797 
8798     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8799                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8800 
8801     // Assume that non-integer casts can span the full range of the type.
8802     if (!isIntegerCast)
8803       return OutputTypeRange;
8804 
8805     IntRange SubRange
8806       = GetExprRange(C, CE->getSubExpr(),
8807                      std::min(MaxWidth, OutputTypeRange.Width));
8808 
8809     // Bail out if the subexpr's range is as wide as the cast type.
8810     if (SubRange.Width >= OutputTypeRange.Width)
8811       return OutputTypeRange;
8812 
8813     // Otherwise, we take the smaller width, and we're non-negative if
8814     // either the output type or the subexpr is.
8815     return IntRange(SubRange.Width,
8816                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8817   }
8818 
8819   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8820     // If we can fold the condition, just take that operand.
8821     bool CondResult;
8822     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8823       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8824                                         : CO->getFalseExpr(),
8825                           MaxWidth);
8826 
8827     // Otherwise, conservatively merge.
8828     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8829     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8830     return IntRange::join(L, R);
8831   }
8832 
8833   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8834     switch (BO->getOpcode()) {
8835     case BO_Cmp:
8836       llvm_unreachable("builtin <=> should have class type");
8837 
8838     // Boolean-valued operations are single-bit and positive.
8839     case BO_LAnd:
8840     case BO_LOr:
8841     case BO_LT:
8842     case BO_GT:
8843     case BO_LE:
8844     case BO_GE:
8845     case BO_EQ:
8846     case BO_NE:
8847       return IntRange::forBoolType();
8848 
8849     // The type of the assignments is the type of the LHS, so the RHS
8850     // is not necessarily the same type.
8851     case BO_MulAssign:
8852     case BO_DivAssign:
8853     case BO_RemAssign:
8854     case BO_AddAssign:
8855     case BO_SubAssign:
8856     case BO_XorAssign:
8857     case BO_OrAssign:
8858       // TODO: bitfields?
8859       return IntRange::forValueOfType(C, GetExprType(E));
8860 
8861     // Simple assignments just pass through the RHS, which will have
8862     // been coerced to the LHS type.
8863     case BO_Assign:
8864       // TODO: bitfields?
8865       return GetExprRange(C, BO->getRHS(), MaxWidth);
8866 
8867     // Operations with opaque sources are black-listed.
8868     case BO_PtrMemD:
8869     case BO_PtrMemI:
8870       return IntRange::forValueOfType(C, GetExprType(E));
8871 
8872     // Bitwise-and uses the *infinum* of the two source ranges.
8873     case BO_And:
8874     case BO_AndAssign:
8875       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8876                             GetExprRange(C, BO->getRHS(), MaxWidth));
8877 
8878     // Left shift gets black-listed based on a judgement call.
8879     case BO_Shl:
8880       // ...except that we want to treat '1 << (blah)' as logically
8881       // positive.  It's an important idiom.
8882       if (IntegerLiteral *I
8883             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8884         if (I->getValue() == 1) {
8885           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8886           return IntRange(R.Width, /*NonNegative*/ true);
8887         }
8888       }
8889       LLVM_FALLTHROUGH;
8890 
8891     case BO_ShlAssign:
8892       return IntRange::forValueOfType(C, GetExprType(E));
8893 
8894     // Right shift by a constant can narrow its left argument.
8895     case BO_Shr:
8896     case BO_ShrAssign: {
8897       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8898 
8899       // If the shift amount is a positive constant, drop the width by
8900       // that much.
8901       llvm::APSInt shift;
8902       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8903           shift.isNonNegative()) {
8904         unsigned zext = shift.getZExtValue();
8905         if (zext >= L.Width)
8906           L.Width = (L.NonNegative ? 0 : 1);
8907         else
8908           L.Width -= zext;
8909       }
8910 
8911       return L;
8912     }
8913 
8914     // Comma acts as its right operand.
8915     case BO_Comma:
8916       return GetExprRange(C, BO->getRHS(), MaxWidth);
8917 
8918     // Black-list pointer subtractions.
8919     case BO_Sub:
8920       if (BO->getLHS()->getType()->isPointerType())
8921         return IntRange::forValueOfType(C, GetExprType(E));
8922       break;
8923 
8924     // The width of a division result is mostly determined by the size
8925     // of the LHS.
8926     case BO_Div: {
8927       // Don't 'pre-truncate' the operands.
8928       unsigned opWidth = C.getIntWidth(GetExprType(E));
8929       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8930 
8931       // If the divisor is constant, use that.
8932       llvm::APSInt divisor;
8933       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8934         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8935         if (log2 >= L.Width)
8936           L.Width = (L.NonNegative ? 0 : 1);
8937         else
8938           L.Width = std::min(L.Width - log2, MaxWidth);
8939         return L;
8940       }
8941 
8942       // Otherwise, just use the LHS's width.
8943       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8944       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8945     }
8946 
8947     // The result of a remainder can't be larger than the result of
8948     // either side.
8949     case BO_Rem: {
8950       // Don't 'pre-truncate' the operands.
8951       unsigned opWidth = C.getIntWidth(GetExprType(E));
8952       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8953       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8954 
8955       IntRange meet = IntRange::meet(L, R);
8956       meet.Width = std::min(meet.Width, MaxWidth);
8957       return meet;
8958     }
8959 
8960     // The default behavior is okay for these.
8961     case BO_Mul:
8962     case BO_Add:
8963     case BO_Xor:
8964     case BO_Or:
8965       break;
8966     }
8967 
8968     // The default case is to treat the operation as if it were closed
8969     // on the narrowest type that encompasses both operands.
8970     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8971     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8972     return IntRange::join(L, R);
8973   }
8974 
8975   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8976     switch (UO->getOpcode()) {
8977     // Boolean-valued operations are white-listed.
8978     case UO_LNot:
8979       return IntRange::forBoolType();
8980 
8981     // Operations with opaque sources are black-listed.
8982     case UO_Deref:
8983     case UO_AddrOf: // should be impossible
8984       return IntRange::forValueOfType(C, GetExprType(E));
8985 
8986     default:
8987       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8988     }
8989   }
8990 
8991   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8992     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8993 
8994   if (const auto *BitField = E->getSourceBitField())
8995     return IntRange(BitField->getBitWidthValue(C),
8996                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8997 
8998   return IntRange::forValueOfType(C, GetExprType(E));
8999 }
9000 
9001 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9002   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9003 }
9004 
9005 /// Checks whether the given value, which currently has the given
9006 /// source semantics, has the same value when coerced through the
9007 /// target semantics.
9008 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9009                                  const llvm::fltSemantics &Src,
9010                                  const llvm::fltSemantics &Tgt) {
9011   llvm::APFloat truncated = value;
9012 
9013   bool ignored;
9014   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9015   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9016 
9017   return truncated.bitwiseIsEqual(value);
9018 }
9019 
9020 /// Checks whether the given value, which currently has the given
9021 /// source semantics, has the same value when coerced through the
9022 /// target semantics.
9023 ///
9024 /// The value might be a vector of floats (or a complex number).
9025 static bool IsSameFloatAfterCast(const APValue &value,
9026                                  const llvm::fltSemantics &Src,
9027                                  const llvm::fltSemantics &Tgt) {
9028   if (value.isFloat())
9029     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9030 
9031   if (value.isVector()) {
9032     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9033       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9034         return false;
9035     return true;
9036   }
9037 
9038   assert(value.isComplexFloat());
9039   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9040           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9041 }
9042 
9043 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9044 
9045 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9046   // Suppress cases where we are comparing against an enum constant.
9047   if (const DeclRefExpr *DR =
9048       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9049     if (isa<EnumConstantDecl>(DR->getDecl()))
9050       return true;
9051 
9052   // Suppress cases where the '0' value is expanded from a macro.
9053   if (E->getLocStart().isMacroID())
9054     return true;
9055 
9056   return false;
9057 }
9058 
9059 static bool isKnownToHaveUnsignedValue(Expr *E) {
9060   return E->getType()->isIntegerType() &&
9061          (!E->getType()->isSignedIntegerType() ||
9062           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9063 }
9064 
9065 namespace {
9066 /// The promoted range of values of a type. In general this has the
9067 /// following structure:
9068 ///
9069 ///     |-----------| . . . |-----------|
9070 ///     ^           ^       ^           ^
9071 ///    Min       HoleMin  HoleMax      Max
9072 ///
9073 /// ... where there is only a hole if a signed type is promoted to unsigned
9074 /// (in which case Min and Max are the smallest and largest representable
9075 /// values).
9076 struct PromotedRange {
9077   // Min, or HoleMax if there is a hole.
9078   llvm::APSInt PromotedMin;
9079   // Max, or HoleMin if there is a hole.
9080   llvm::APSInt PromotedMax;
9081 
9082   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9083     if (R.Width == 0)
9084       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9085     else if (R.Width >= BitWidth && !Unsigned) {
9086       // Promotion made the type *narrower*. This happens when promoting
9087       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9088       // Treat all values of 'signed int' as being in range for now.
9089       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9090       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9091     } else {
9092       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9093                         .extOrTrunc(BitWidth);
9094       PromotedMin.setIsUnsigned(Unsigned);
9095 
9096       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9097                         .extOrTrunc(BitWidth);
9098       PromotedMax.setIsUnsigned(Unsigned);
9099     }
9100   }
9101 
9102   // Determine whether this range is contiguous (has no hole).
9103   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9104 
9105   // Where a constant value is within the range.
9106   enum ComparisonResult {
9107     LT = 0x1,
9108     LE = 0x2,
9109     GT = 0x4,
9110     GE = 0x8,
9111     EQ = 0x10,
9112     NE = 0x20,
9113     InRangeFlag = 0x40,
9114 
9115     Less = LE | LT | NE,
9116     Min = LE | InRangeFlag,
9117     InRange = InRangeFlag,
9118     Max = GE | InRangeFlag,
9119     Greater = GE | GT | NE,
9120 
9121     OnlyValue = LE | GE | EQ | InRangeFlag,
9122     InHole = NE
9123   };
9124 
9125   ComparisonResult compare(const llvm::APSInt &Value) const {
9126     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9127            Value.isUnsigned() == PromotedMin.isUnsigned());
9128     if (!isContiguous()) {
9129       assert(Value.isUnsigned() && "discontiguous range for signed compare");
9130       if (Value.isMinValue()) return Min;
9131       if (Value.isMaxValue()) return Max;
9132       if (Value >= PromotedMin) return InRange;
9133       if (Value <= PromotedMax) return InRange;
9134       return InHole;
9135     }
9136 
9137     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9138     case -1: return Less;
9139     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9140     case 1:
9141       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9142       case -1: return InRange;
9143       case 0: return Max;
9144       case 1: return Greater;
9145       }
9146     }
9147 
9148     llvm_unreachable("impossible compare result");
9149   }
9150 
9151   static llvm::Optional<StringRef>
9152   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9153     if (Op == BO_Cmp) {
9154       ComparisonResult LTFlag = LT, GTFlag = GT;
9155       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9156 
9157       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9158       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9159       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9160       return llvm::None;
9161     }
9162 
9163     ComparisonResult TrueFlag, FalseFlag;
9164     if (Op == BO_EQ) {
9165       TrueFlag = EQ;
9166       FalseFlag = NE;
9167     } else if (Op == BO_NE) {
9168       TrueFlag = NE;
9169       FalseFlag = EQ;
9170     } else {
9171       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9172         TrueFlag = LT;
9173         FalseFlag = GE;
9174       } else {
9175         TrueFlag = GT;
9176         FalseFlag = LE;
9177       }
9178       if (Op == BO_GE || Op == BO_LE)
9179         std::swap(TrueFlag, FalseFlag);
9180     }
9181     if (R & TrueFlag)
9182       return StringRef("true");
9183     if (R & FalseFlag)
9184       return StringRef("false");
9185     return llvm::None;
9186   }
9187 };
9188 }
9189 
9190 static bool HasEnumType(Expr *E) {
9191   // Strip off implicit integral promotions.
9192   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9193     if (ICE->getCastKind() != CK_IntegralCast &&
9194         ICE->getCastKind() != CK_NoOp)
9195       break;
9196     E = ICE->getSubExpr();
9197   }
9198 
9199   return E->getType()->isEnumeralType();
9200 }
9201 
9202 static int classifyConstantValue(Expr *Constant) {
9203   // The values of this enumeration are used in the diagnostics
9204   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9205   enum ConstantValueKind {
9206     Miscellaneous = 0,
9207     LiteralTrue,
9208     LiteralFalse
9209   };
9210   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9211     return BL->getValue() ? ConstantValueKind::LiteralTrue
9212                           : ConstantValueKind::LiteralFalse;
9213   return ConstantValueKind::Miscellaneous;
9214 }
9215 
9216 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9217                                         Expr *Constant, Expr *Other,
9218                                         const llvm::APSInt &Value,
9219                                         bool RhsConstant) {
9220   if (S.inTemplateInstantiation())
9221     return false;
9222 
9223   Expr *OriginalOther = Other;
9224 
9225   Constant = Constant->IgnoreParenImpCasts();
9226   Other = Other->IgnoreParenImpCasts();
9227 
9228   // Suppress warnings on tautological comparisons between values of the same
9229   // enumeration type. There are only two ways we could warn on this:
9230   //  - If the constant is outside the range of representable values of
9231   //    the enumeration. In such a case, we should warn about the cast
9232   //    to enumeration type, not about the comparison.
9233   //  - If the constant is the maximum / minimum in-range value. For an
9234   //    enumeratin type, such comparisons can be meaningful and useful.
9235   if (Constant->getType()->isEnumeralType() &&
9236       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9237     return false;
9238 
9239   // TODO: Investigate using GetExprRange() to get tighter bounds
9240   // on the bit ranges.
9241   QualType OtherT = Other->getType();
9242   if (const auto *AT = OtherT->getAs<AtomicType>())
9243     OtherT = AT->getValueType();
9244   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9245 
9246   // Whether we're treating Other as being a bool because of the form of
9247   // expression despite it having another type (typically 'int' in C).
9248   bool OtherIsBooleanDespiteType =
9249       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9250   if (OtherIsBooleanDespiteType)
9251     OtherRange = IntRange::forBoolType();
9252 
9253   // Determine the promoted range of the other type and see if a comparison of
9254   // the constant against that range is tautological.
9255   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9256                                    Value.isUnsigned());
9257   auto Cmp = OtherPromotedRange.compare(Value);
9258   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9259   if (!Result)
9260     return false;
9261 
9262   // Suppress the diagnostic for an in-range comparison if the constant comes
9263   // from a macro or enumerator. We don't want to diagnose
9264   //
9265   //   some_long_value <= INT_MAX
9266   //
9267   // when sizeof(int) == sizeof(long).
9268   bool InRange = Cmp & PromotedRange::InRangeFlag;
9269   if (InRange && IsEnumConstOrFromMacro(S, Constant))
9270     return false;
9271 
9272   // If this is a comparison to an enum constant, include that
9273   // constant in the diagnostic.
9274   const EnumConstantDecl *ED = nullptr;
9275   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9276     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9277 
9278   // Should be enough for uint128 (39 decimal digits)
9279   SmallString<64> PrettySourceValue;
9280   llvm::raw_svector_ostream OS(PrettySourceValue);
9281   if (ED)
9282     OS << '\'' << *ED << "' (" << Value << ")";
9283   else
9284     OS << Value;
9285 
9286   // FIXME: We use a somewhat different formatting for the in-range cases and
9287   // cases involving boolean values for historical reasons. We should pick a
9288   // consistent way of presenting these diagnostics.
9289   if (!InRange || Other->isKnownToHaveBooleanValue()) {
9290     S.DiagRuntimeBehavior(
9291       E->getOperatorLoc(), E,
9292       S.PDiag(!InRange ? diag::warn_out_of_range_compare
9293                        : diag::warn_tautological_bool_compare)
9294           << OS.str() << classifyConstantValue(Constant)
9295           << OtherT << OtherIsBooleanDespiteType << *Result
9296           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9297   } else {
9298     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9299                         ? (HasEnumType(OriginalOther)
9300                                ? diag::warn_unsigned_enum_always_true_comparison
9301                                : diag::warn_unsigned_always_true_comparison)
9302                         : diag::warn_tautological_constant_compare;
9303 
9304     S.Diag(E->getOperatorLoc(), Diag)
9305         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9306         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9307   }
9308 
9309   return true;
9310 }
9311 
9312 /// Analyze the operands of the given comparison.  Implements the
9313 /// fallback case from AnalyzeComparison.
9314 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
9315   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9316   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9317 }
9318 
9319 /// Implements -Wsign-compare.
9320 ///
9321 /// \param E the binary operator to check for warnings
9322 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
9323   // The type the comparison is being performed in.
9324   QualType T = E->getLHS()->getType();
9325 
9326   // Only analyze comparison operators where both sides have been converted to
9327   // the same type.
9328   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9329     return AnalyzeImpConvsInComparison(S, E);
9330 
9331   // Don't analyze value-dependent comparisons directly.
9332   if (E->isValueDependent())
9333     return AnalyzeImpConvsInComparison(S, E);
9334 
9335   Expr *LHS = E->getLHS();
9336   Expr *RHS = E->getRHS();
9337 
9338   if (T->isIntegralType(S.Context)) {
9339     llvm::APSInt RHSValue;
9340     llvm::APSInt LHSValue;
9341 
9342     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9343     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
9344 
9345     // We don't care about expressions whose result is a constant.
9346     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9347       return AnalyzeImpConvsInComparison(S, E);
9348 
9349     // We only care about expressions where just one side is literal
9350     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9351       // Is the constant on the RHS or LHS?
9352       const bool RhsConstant = IsRHSIntegralLiteral;
9353       Expr *Const = RhsConstant ? RHS : LHS;
9354       Expr *Other = RhsConstant ? LHS : RHS;
9355       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9356 
9357       // Check whether an integer constant comparison results in a value
9358       // of 'true' or 'false'.
9359       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9360         return AnalyzeImpConvsInComparison(S, E);
9361     }
9362   }
9363 
9364   if (!T->hasUnsignedIntegerRepresentation()) {
9365     // We don't do anything special if this isn't an unsigned integral
9366     // comparison:  we're only interested in integral comparisons, and
9367     // signed comparisons only happen in cases we don't care to warn about.
9368     return AnalyzeImpConvsInComparison(S, E);
9369   }
9370 
9371   LHS = LHS->IgnoreParenImpCasts();
9372   RHS = RHS->IgnoreParenImpCasts();
9373 
9374   if (!S.getLangOpts().CPlusPlus) {
9375     // Avoid warning about comparison of integers with different signs when
9376     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9377     // the type of `E`.
9378     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9379       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9380     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9381       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9382   }
9383 
9384   // Check to see if one of the (unmodified) operands is of different
9385   // signedness.
9386   Expr *signedOperand, *unsignedOperand;
9387   if (LHS->getType()->hasSignedIntegerRepresentation()) {
9388     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
9389            "unsigned comparison between two signed integer expressions?");
9390     signedOperand = LHS;
9391     unsignedOperand = RHS;
9392   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9393     signedOperand = RHS;
9394     unsignedOperand = LHS;
9395   } else {
9396     return AnalyzeImpConvsInComparison(S, E);
9397   }
9398 
9399   // Otherwise, calculate the effective range of the signed operand.
9400   IntRange signedRange = GetExprRange(S.Context, signedOperand);
9401 
9402   // Go ahead and analyze implicit conversions in the operands.  Note
9403   // that we skip the implicit conversions on both sides.
9404   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9405   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9406 
9407   // If the signed range is non-negative, -Wsign-compare won't fire.
9408   if (signedRange.NonNegative)
9409     return;
9410 
9411   // For (in)equality comparisons, if the unsigned operand is a
9412   // constant which cannot collide with a overflowed signed operand,
9413   // then reinterpreting the signed operand as unsigned will not
9414   // change the result of the comparison.
9415   if (E->isEqualityOp()) {
9416     unsigned comparisonWidth = S.Context.getIntWidth(T);
9417     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9418 
9419     // We should never be unable to prove that the unsigned operand is
9420     // non-negative.
9421     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9422 
9423     if (unsignedRange.Width < comparisonWidth)
9424       return;
9425   }
9426 
9427   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9428     S.PDiag(diag::warn_mixed_sign_comparison)
9429       << LHS->getType() << RHS->getType()
9430       << LHS->getSourceRange() << RHS->getSourceRange());
9431 }
9432 
9433 /// Analyzes an attempt to assign the given value to a bitfield.
9434 ///
9435 /// Returns true if there was something fishy about the attempt.
9436 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9437                                       SourceLocation InitLoc) {
9438   assert(Bitfield->isBitField());
9439   if (Bitfield->isInvalidDecl())
9440     return false;
9441 
9442   // White-list bool bitfields.
9443   QualType BitfieldType = Bitfield->getType();
9444   if (BitfieldType->isBooleanType())
9445      return false;
9446 
9447   if (BitfieldType->isEnumeralType()) {
9448     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9449     // If the underlying enum type was not explicitly specified as an unsigned
9450     // type and the enum contain only positive values, MSVC++ will cause an
9451     // inconsistency by storing this as a signed type.
9452     if (S.getLangOpts().CPlusPlus11 &&
9453         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9454         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9455         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9456       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9457         << BitfieldEnumDecl->getNameAsString();
9458     }
9459   }
9460 
9461   if (Bitfield->getType()->isBooleanType())
9462     return false;
9463 
9464   // Ignore value- or type-dependent expressions.
9465   if (Bitfield->getBitWidth()->isValueDependent() ||
9466       Bitfield->getBitWidth()->isTypeDependent() ||
9467       Init->isValueDependent() ||
9468       Init->isTypeDependent())
9469     return false;
9470 
9471   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9472   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9473 
9474   llvm::APSInt Value;
9475   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9476                                    Expr::SE_AllowSideEffects)) {
9477     // The RHS is not constant.  If the RHS has an enum type, make sure the
9478     // bitfield is wide enough to hold all the values of the enum without
9479     // truncation.
9480     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9481       EnumDecl *ED = EnumTy->getDecl();
9482       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9483 
9484       // Enum types are implicitly signed on Windows, so check if there are any
9485       // negative enumerators to see if the enum was intended to be signed or
9486       // not.
9487       bool SignedEnum = ED->getNumNegativeBits() > 0;
9488 
9489       // Check for surprising sign changes when assigning enum values to a
9490       // bitfield of different signedness.  If the bitfield is signed and we
9491       // have exactly the right number of bits to store this unsigned enum,
9492       // suggest changing the enum to an unsigned type. This typically happens
9493       // on Windows where unfixed enums always use an underlying type of 'int'.
9494       unsigned DiagID = 0;
9495       if (SignedEnum && !SignedBitfield) {
9496         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9497       } else if (SignedBitfield && !SignedEnum &&
9498                  ED->getNumPositiveBits() == FieldWidth) {
9499         DiagID = diag::warn_signed_bitfield_enum_conversion;
9500       }
9501 
9502       if (DiagID) {
9503         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9504         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9505         SourceRange TypeRange =
9506             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9507         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9508             << SignedEnum << TypeRange;
9509       }
9510 
9511       // Compute the required bitwidth. If the enum has negative values, we need
9512       // one more bit than the normal number of positive bits to represent the
9513       // sign bit.
9514       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9515                                                   ED->getNumNegativeBits())
9516                                        : ED->getNumPositiveBits();
9517 
9518       // Check the bitwidth.
9519       if (BitsNeeded > FieldWidth) {
9520         Expr *WidthExpr = Bitfield->getBitWidth();
9521         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9522             << Bitfield << ED;
9523         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9524             << BitsNeeded << ED << WidthExpr->getSourceRange();
9525       }
9526     }
9527 
9528     return false;
9529   }
9530 
9531   unsigned OriginalWidth = Value.getBitWidth();
9532 
9533   if (!Value.isSigned() || Value.isNegative())
9534     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9535       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9536         OriginalWidth = Value.getMinSignedBits();
9537 
9538   if (OriginalWidth <= FieldWidth)
9539     return false;
9540 
9541   // Compute the value which the bitfield will contain.
9542   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9543   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9544 
9545   // Check whether the stored value is equal to the original value.
9546   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9547   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9548     return false;
9549 
9550   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9551   // therefore don't strictly fit into a signed bitfield of width 1.
9552   if (FieldWidth == 1 && Value == 1)
9553     return false;
9554 
9555   std::string PrettyValue = Value.toString(10);
9556   std::string PrettyTrunc = TruncatedValue.toString(10);
9557 
9558   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9559     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9560     << Init->getSourceRange();
9561 
9562   return true;
9563 }
9564 
9565 /// Analyze the given simple or compound assignment for warning-worthy
9566 /// operations.
9567 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9568   // Just recurse on the LHS.
9569   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9570 
9571   // We want to recurse on the RHS as normal unless we're assigning to
9572   // a bitfield.
9573   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9574     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9575                                   E->getOperatorLoc())) {
9576       // Recurse, ignoring any implicit conversions on the RHS.
9577       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9578                                         E->getOperatorLoc());
9579     }
9580   }
9581 
9582   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9583 }
9584 
9585 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9586 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9587                             SourceLocation CContext, unsigned diag,
9588                             bool pruneControlFlow = false) {
9589   if (pruneControlFlow) {
9590     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9591                           S.PDiag(diag)
9592                             << SourceType << T << E->getSourceRange()
9593                             << SourceRange(CContext));
9594     return;
9595   }
9596   S.Diag(E->getExprLoc(), diag)
9597     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9598 }
9599 
9600 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9601 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9602                             SourceLocation CContext,
9603                             unsigned diag, bool pruneControlFlow = false) {
9604   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9605 }
9606 
9607 /// Analyze the given compound assignment for the possible losing of
9608 /// floating-point precision.
9609 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9610   assert(isa<CompoundAssignOperator>(E) &&
9611          "Must be compound assignment operation");
9612   // Recurse on the LHS and RHS in here
9613   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9614   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9615 
9616   // Now check the outermost expression
9617   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9618   const auto *RBT = cast<CompoundAssignOperator>(E)
9619                         ->getComputationResultType()
9620                         ->getAs<BuiltinType>();
9621 
9622   // If both source and target are floating points.
9623   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9624     // Builtin FP kinds are ordered by increasing FP rank.
9625     if (ResultBT->getKind() < RBT->getKind())
9626       // We don't want to warn for system macro.
9627       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9628         // warn about dropping FP rank.
9629         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9630                         E->getOperatorLoc(),
9631                         diag::warn_impcast_float_result_precision);
9632 }
9633 
9634 /// Diagnose an implicit cast from a floating point value to an integer value.
9635 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9636                                     SourceLocation CContext) {
9637   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9638   const bool PruneWarnings = S.inTemplateInstantiation();
9639 
9640   Expr *InnerE = E->IgnoreParenImpCasts();
9641   // We also want to warn on, e.g., "int i = -1.234"
9642   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9643     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9644       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9645 
9646   const bool IsLiteral =
9647       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9648 
9649   llvm::APFloat Value(0.0);
9650   bool IsConstant =
9651     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9652   if (!IsConstant) {
9653     return DiagnoseImpCast(S, E, T, CContext,
9654                            diag::warn_impcast_float_integer, PruneWarnings);
9655   }
9656 
9657   bool isExact = false;
9658 
9659   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9660                             T->hasUnsignedIntegerRepresentation());
9661   llvm::APFloat::opStatus Result = Value.convertToInteger(
9662       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9663 
9664   if (Result == llvm::APFloat::opOK && isExact) {
9665     if (IsLiteral) return;
9666     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9667                            PruneWarnings);
9668   }
9669 
9670   // Conversion of a floating-point value to a non-bool integer where the
9671   // integral part cannot be represented by the integer type is undefined.
9672   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9673     return DiagnoseImpCast(
9674         S, E, T, CContext,
9675         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
9676                   : diag::warn_impcast_float_to_integer_out_of_range,
9677         PruneWarnings);
9678 
9679   unsigned DiagID = 0;
9680   if (IsLiteral) {
9681     // Warn on floating point literal to integer.
9682     DiagID = diag::warn_impcast_literal_float_to_integer;
9683   } else if (IntegerValue == 0) {
9684     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9685       return DiagnoseImpCast(S, E, T, CContext,
9686                              diag::warn_impcast_float_integer, PruneWarnings);
9687     }
9688     // Warn on non-zero to zero conversion.
9689     DiagID = diag::warn_impcast_float_to_integer_zero;
9690   } else {
9691     if (IntegerValue.isUnsigned()) {
9692       if (!IntegerValue.isMaxValue()) {
9693         return DiagnoseImpCast(S, E, T, CContext,
9694                                diag::warn_impcast_float_integer, PruneWarnings);
9695       }
9696     } else {  // IntegerValue.isSigned()
9697       if (!IntegerValue.isMaxSignedValue() &&
9698           !IntegerValue.isMinSignedValue()) {
9699         return DiagnoseImpCast(S, E, T, CContext,
9700                                diag::warn_impcast_float_integer, PruneWarnings);
9701       }
9702     }
9703     // Warn on evaluatable floating point expression to integer conversion.
9704     DiagID = diag::warn_impcast_float_to_integer;
9705   }
9706 
9707   // FIXME: Force the precision of the source value down so we don't print
9708   // digits which are usually useless (we don't really care here if we
9709   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9710   // would automatically print the shortest representation, but it's a bit
9711   // tricky to implement.
9712   SmallString<16> PrettySourceValue;
9713   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9714   precision = (precision * 59 + 195) / 196;
9715   Value.toString(PrettySourceValue, precision);
9716 
9717   SmallString<16> PrettyTargetValue;
9718   if (IsBool)
9719     PrettyTargetValue = Value.isZero() ? "false" : "true";
9720   else
9721     IntegerValue.toString(PrettyTargetValue);
9722 
9723   if (PruneWarnings) {
9724     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9725                           S.PDiag(DiagID)
9726                               << E->getType() << T.getUnqualifiedType()
9727                               << PrettySourceValue << PrettyTargetValue
9728                               << E->getSourceRange() << SourceRange(CContext));
9729   } else {
9730     S.Diag(E->getExprLoc(), DiagID)
9731         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9732         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9733   }
9734 }
9735 
9736 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9737                                       IntRange Range) {
9738   if (!Range.Width) return "0";
9739 
9740   llvm::APSInt ValueInRange = Value;
9741   ValueInRange.setIsSigned(!Range.NonNegative);
9742   ValueInRange = ValueInRange.trunc(Range.Width);
9743   return ValueInRange.toString(10);
9744 }
9745 
9746 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9747   if (!isa<ImplicitCastExpr>(Ex))
9748     return false;
9749 
9750   Expr *InnerE = Ex->IgnoreParenImpCasts();
9751   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9752   const Type *Source =
9753     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9754   if (Target->isDependentType())
9755     return false;
9756 
9757   const BuiltinType *FloatCandidateBT =
9758     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9759   const Type *BoolCandidateType = ToBool ? Target : Source;
9760 
9761   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9762           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9763 }
9764 
9765 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9766                                              SourceLocation CC) {
9767   unsigned NumArgs = TheCall->getNumArgs();
9768   for (unsigned i = 0; i < NumArgs; ++i) {
9769     Expr *CurrA = TheCall->getArg(i);
9770     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9771       continue;
9772 
9773     bool IsSwapped = ((i > 0) &&
9774         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9775     IsSwapped |= ((i < (NumArgs - 1)) &&
9776         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9777     if (IsSwapped) {
9778       // Warn on this floating-point to bool conversion.
9779       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9780                       CurrA->getType(), CC,
9781                       diag::warn_impcast_floating_point_to_bool);
9782     }
9783   }
9784 }
9785 
9786 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9787                                    SourceLocation CC) {
9788   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9789                         E->getExprLoc()))
9790     return;
9791 
9792   // Don't warn on functions which have return type nullptr_t.
9793   if (isa<CallExpr>(E))
9794     return;
9795 
9796   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9797   const Expr::NullPointerConstantKind NullKind =
9798       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9799   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9800     return;
9801 
9802   // Return if target type is a safe conversion.
9803   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9804       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9805     return;
9806 
9807   SourceLocation Loc = E->getSourceRange().getBegin();
9808 
9809   // Venture through the macro stacks to get to the source of macro arguments.
9810   // The new location is a better location than the complete location that was
9811   // passed in.
9812   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9813   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
9814 
9815   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9816   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9817     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9818         Loc, S.SourceMgr, S.getLangOpts());
9819     if (MacroName == "NULL")
9820       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
9821   }
9822 
9823   // Only warn if the null and context location are in the same macro expansion.
9824   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9825     return;
9826 
9827   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9828       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9829       << FixItHint::CreateReplacement(Loc,
9830                                       S.getFixItZeroLiteralForType(T, Loc));
9831 }
9832 
9833 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9834                                   ObjCArrayLiteral *ArrayLiteral);
9835 
9836 static void
9837 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9838                            ObjCDictionaryLiteral *DictionaryLiteral);
9839 
9840 /// Check a single element within a collection literal against the
9841 /// target element type.
9842 static void checkObjCCollectionLiteralElement(Sema &S,
9843                                               QualType TargetElementType,
9844                                               Expr *Element,
9845                                               unsigned ElementKind) {
9846   // Skip a bitcast to 'id' or qualified 'id'.
9847   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9848     if (ICE->getCastKind() == CK_BitCast &&
9849         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9850       Element = ICE->getSubExpr();
9851   }
9852 
9853   QualType ElementType = Element->getType();
9854   ExprResult ElementResult(Element);
9855   if (ElementType->getAs<ObjCObjectPointerType>() &&
9856       S.CheckSingleAssignmentConstraints(TargetElementType,
9857                                          ElementResult,
9858                                          false, false)
9859         != Sema::Compatible) {
9860     S.Diag(Element->getLocStart(),
9861            diag::warn_objc_collection_literal_element)
9862       << ElementType << ElementKind << TargetElementType
9863       << Element->getSourceRange();
9864   }
9865 
9866   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9867     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9868   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9869     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9870 }
9871 
9872 /// Check an Objective-C array literal being converted to the given
9873 /// target type.
9874 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9875                                   ObjCArrayLiteral *ArrayLiteral) {
9876   if (!S.NSArrayDecl)
9877     return;
9878 
9879   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9880   if (!TargetObjCPtr)
9881     return;
9882 
9883   if (TargetObjCPtr->isUnspecialized() ||
9884       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9885         != S.NSArrayDecl->getCanonicalDecl())
9886     return;
9887 
9888   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9889   if (TypeArgs.size() != 1)
9890     return;
9891 
9892   QualType TargetElementType = TypeArgs[0];
9893   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9894     checkObjCCollectionLiteralElement(S, TargetElementType,
9895                                       ArrayLiteral->getElement(I),
9896                                       0);
9897   }
9898 }
9899 
9900 /// Check an Objective-C dictionary literal being converted to the given
9901 /// target type.
9902 static void
9903 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9904                            ObjCDictionaryLiteral *DictionaryLiteral) {
9905   if (!S.NSDictionaryDecl)
9906     return;
9907 
9908   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9909   if (!TargetObjCPtr)
9910     return;
9911 
9912   if (TargetObjCPtr->isUnspecialized() ||
9913       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9914         != S.NSDictionaryDecl->getCanonicalDecl())
9915     return;
9916 
9917   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9918   if (TypeArgs.size() != 2)
9919     return;
9920 
9921   QualType TargetKeyType = TypeArgs[0];
9922   QualType TargetObjectType = TypeArgs[1];
9923   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9924     auto Element = DictionaryLiteral->getKeyValueElement(I);
9925     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9926     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9927   }
9928 }
9929 
9930 // Helper function to filter out cases for constant width constant conversion.
9931 // Don't warn on char array initialization or for non-decimal values.
9932 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9933                                           SourceLocation CC) {
9934   // If initializing from a constant, and the constant starts with '0',
9935   // then it is a binary, octal, or hexadecimal.  Allow these constants
9936   // to fill all the bits, even if there is a sign change.
9937   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9938     const char FirstLiteralCharacter =
9939         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9940     if (FirstLiteralCharacter == '0')
9941       return false;
9942   }
9943 
9944   // If the CC location points to a '{', and the type is char, then assume
9945   // assume it is an array initialization.
9946   if (CC.isValid() && T->isCharType()) {
9947     const char FirstContextCharacter =
9948         S.getSourceManager().getCharacterData(CC)[0];
9949     if (FirstContextCharacter == '{')
9950       return false;
9951   }
9952 
9953   return true;
9954 }
9955 
9956 static void
9957 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9958                         bool *ICContext = nullptr) {
9959   if (E->isTypeDependent() || E->isValueDependent()) return;
9960 
9961   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9962   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9963   if (Source == Target) return;
9964   if (Target->isDependentType()) return;
9965 
9966   // If the conversion context location is invalid don't complain. We also
9967   // don't want to emit a warning if the issue occurs from the expansion of
9968   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9969   // delay this check as long as possible. Once we detect we are in that
9970   // scenario, we just return.
9971   if (CC.isInvalid())
9972     return;
9973 
9974   // Diagnose implicit casts to bool.
9975   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9976     if (isa<StringLiteral>(E))
9977       // Warn on string literal to bool.  Checks for string literals in logical
9978       // and expressions, for instance, assert(0 && "error here"), are
9979       // prevented by a check in AnalyzeImplicitConversions().
9980       return DiagnoseImpCast(S, E, T, CC,
9981                              diag::warn_impcast_string_literal_to_bool);
9982     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9983         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9984       // This covers the literal expressions that evaluate to Objective-C
9985       // objects.
9986       return DiagnoseImpCast(S, E, T, CC,
9987                              diag::warn_impcast_objective_c_literal_to_bool);
9988     }
9989     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9990       // Warn on pointer to bool conversion that is always true.
9991       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9992                                      SourceRange(CC));
9993     }
9994   }
9995 
9996   // Check implicit casts from Objective-C collection literals to specialized
9997   // collection types, e.g., NSArray<NSString *> *.
9998   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9999     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10000   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10001     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10002 
10003   // Strip vector types.
10004   if (isa<VectorType>(Source)) {
10005     if (!isa<VectorType>(Target)) {
10006       if (S.SourceMgr.isInSystemMacro(CC))
10007         return;
10008       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10009     }
10010 
10011     // If the vector cast is cast between two vectors of the same size, it is
10012     // a bitcast, not a conversion.
10013     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10014       return;
10015 
10016     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10017     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10018   }
10019   if (auto VecTy = dyn_cast<VectorType>(Target))
10020     Target = VecTy->getElementType().getTypePtr();
10021 
10022   // Strip complex types.
10023   if (isa<ComplexType>(Source)) {
10024     if (!isa<ComplexType>(Target)) {
10025       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10026         return;
10027 
10028       return DiagnoseImpCast(S, E, T, CC,
10029                              S.getLangOpts().CPlusPlus
10030                                  ? diag::err_impcast_complex_scalar
10031                                  : diag::warn_impcast_complex_scalar);
10032     }
10033 
10034     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10035     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10036   }
10037 
10038   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10039   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10040 
10041   // If the source is floating point...
10042   if (SourceBT && SourceBT->isFloatingPoint()) {
10043     // ...and the target is floating point...
10044     if (TargetBT && TargetBT->isFloatingPoint()) {
10045       // ...then warn if we're dropping FP rank.
10046 
10047       // Builtin FP kinds are ordered by increasing FP rank.
10048       if (SourceBT->getKind() > TargetBT->getKind()) {
10049         // Don't warn about float constants that are precisely
10050         // representable in the target type.
10051         Expr::EvalResult result;
10052         if (E->EvaluateAsRValue(result, S.Context)) {
10053           // Value might be a float, a float vector, or a float complex.
10054           if (IsSameFloatAfterCast(result.Val,
10055                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10056                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10057             return;
10058         }
10059 
10060         if (S.SourceMgr.isInSystemMacro(CC))
10061           return;
10062 
10063         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10064       }
10065       // ... or possibly if we're increasing rank, too
10066       else if (TargetBT->getKind() > SourceBT->getKind()) {
10067         if (S.SourceMgr.isInSystemMacro(CC))
10068           return;
10069 
10070         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10071       }
10072       return;
10073     }
10074 
10075     // If the target is integral, always warn.
10076     if (TargetBT && TargetBT->isInteger()) {
10077       if (S.SourceMgr.isInSystemMacro(CC))
10078         return;
10079 
10080       DiagnoseFloatingImpCast(S, E, T, CC);
10081     }
10082 
10083     // Detect the case where a call result is converted from floating-point to
10084     // to bool, and the final argument to the call is converted from bool, to
10085     // discover this typo:
10086     //
10087     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10088     //
10089     // FIXME: This is an incredibly special case; is there some more general
10090     // way to detect this class of misplaced-parentheses bug?
10091     if (Target->isBooleanType() && isa<CallExpr>(E)) {
10092       // Check last argument of function call to see if it is an
10093       // implicit cast from a type matching the type the result
10094       // is being cast to.
10095       CallExpr *CEx = cast<CallExpr>(E);
10096       if (unsigned NumArgs = CEx->getNumArgs()) {
10097         Expr *LastA = CEx->getArg(NumArgs - 1);
10098         Expr *InnerE = LastA->IgnoreParenImpCasts();
10099         if (isa<ImplicitCastExpr>(LastA) &&
10100             InnerE->getType()->isBooleanType()) {
10101           // Warn on this floating-point to bool conversion
10102           DiagnoseImpCast(S, E, T, CC,
10103                           diag::warn_impcast_floating_point_to_bool);
10104         }
10105       }
10106     }
10107     return;
10108   }
10109 
10110   DiagnoseNullConversion(S, E, T, CC);
10111 
10112   S.DiscardMisalignedMemberAddress(Target, E);
10113 
10114   if (!Source->isIntegerType() || !Target->isIntegerType())
10115     return;
10116 
10117   // TODO: remove this early return once the false positives for constant->bool
10118   // in templates, macros, etc, are reduced or removed.
10119   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10120     return;
10121 
10122   IntRange SourceRange = GetExprRange(S.Context, E);
10123   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
10124 
10125   if (SourceRange.Width > TargetRange.Width) {
10126     // If the source is a constant, use a default-on diagnostic.
10127     // TODO: this should happen for bitfield stores, too.
10128     llvm::APSInt Value(32);
10129     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
10130       if (S.SourceMgr.isInSystemMacro(CC))
10131         return;
10132 
10133       std::string PrettySourceValue = Value.toString(10);
10134       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10135 
10136       S.DiagRuntimeBehavior(E->getExprLoc(), E,
10137         S.PDiag(diag::warn_impcast_integer_precision_constant)
10138             << PrettySourceValue << PrettyTargetValue
10139             << E->getType() << T << E->getSourceRange()
10140             << clang::SourceRange(CC));
10141       return;
10142     }
10143 
10144     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10145     if (S.SourceMgr.isInSystemMacro(CC))
10146       return;
10147 
10148     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
10149       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10150                              /* pruneControlFlow */ true);
10151     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
10152   }
10153 
10154   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10155       SourceRange.NonNegative && Source->isSignedIntegerType()) {
10156     // Warn when doing a signed to signed conversion, warn if the positive
10157     // source value is exactly the width of the target type, which will
10158     // cause a negative value to be stored.
10159 
10160     llvm::APSInt Value;
10161     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10162         !S.SourceMgr.isInSystemMacro(CC)) {
10163       if (isSameWidthConstantConversion(S, E, T, CC)) {
10164         std::string PrettySourceValue = Value.toString(10);
10165         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10166 
10167         S.DiagRuntimeBehavior(
10168             E->getExprLoc(), E,
10169             S.PDiag(diag::warn_impcast_integer_precision_constant)
10170                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10171                 << E->getSourceRange() << clang::SourceRange(CC));
10172         return;
10173       }
10174     }
10175 
10176     // Fall through for non-constants to give a sign conversion warning.
10177   }
10178 
10179   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10180       (!TargetRange.NonNegative && SourceRange.NonNegative &&
10181        SourceRange.Width == TargetRange.Width)) {
10182     if (S.SourceMgr.isInSystemMacro(CC))
10183       return;
10184 
10185     unsigned DiagID = diag::warn_impcast_integer_sign;
10186 
10187     // Traditionally, gcc has warned about this under -Wsign-compare.
10188     // We also want to warn about it in -Wconversion.
10189     // So if -Wconversion is off, use a completely identical diagnostic
10190     // in the sign-compare group.
10191     // The conditional-checking code will
10192     if (ICContext) {
10193       DiagID = diag::warn_impcast_integer_sign_conditional;
10194       *ICContext = true;
10195     }
10196 
10197     return DiagnoseImpCast(S, E, T, CC, DiagID);
10198   }
10199 
10200   // Diagnose conversions between different enumeration types.
10201   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10202   // type, to give us better diagnostics.
10203   QualType SourceType = E->getType();
10204   if (!S.getLangOpts().CPlusPlus) {
10205     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10206       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10207         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10208         SourceType = S.Context.getTypeDeclType(Enum);
10209         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10210       }
10211   }
10212 
10213   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10214     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
10215       if (SourceEnum->getDecl()->hasNameForLinkage() &&
10216           TargetEnum->getDecl()->hasNameForLinkage() &&
10217           SourceEnum != TargetEnum) {
10218         if (S.SourceMgr.isInSystemMacro(CC))
10219           return;
10220 
10221         return DiagnoseImpCast(S, E, SourceType, T, CC,
10222                                diag::warn_impcast_different_enum_types);
10223       }
10224 }
10225 
10226 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10227                                      SourceLocation CC, QualType T);
10228 
10229 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10230                                     SourceLocation CC, bool &ICContext) {
10231   E = E->IgnoreParenImpCasts();
10232 
10233   if (isa<ConditionalOperator>(E))
10234     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
10235 
10236   AnalyzeImplicitConversions(S, E, CC);
10237   if (E->getType() != T)
10238     return CheckImplicitConversion(S, E, T, CC, &ICContext);
10239 }
10240 
10241 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10242                                      SourceLocation CC, QualType T) {
10243   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
10244 
10245   bool Suspicious = false;
10246   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10247   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
10248 
10249   // If -Wconversion would have warned about either of the candidates
10250   // for a signedness conversion to the context type...
10251   if (!Suspicious) return;
10252 
10253   // ...but it's currently ignored...
10254   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
10255     return;
10256 
10257   // ...then check whether it would have warned about either of the
10258   // candidates for a signedness conversion to the condition type.
10259   if (E->getType() == T) return;
10260 
10261   Suspicious = false;
10262   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10263                           E->getType(), CC, &Suspicious);
10264   if (!Suspicious)
10265     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
10266                             E->getType(), CC, &Suspicious);
10267 }
10268 
10269 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10270 /// Input argument E is a logical expression.
10271 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
10272   if (S.getLangOpts().Bool)
10273     return;
10274   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10275 }
10276 
10277 /// AnalyzeImplicitConversions - Find and report any interesting
10278 /// implicit conversions in the given expression.  There are a couple
10279 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
10280 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10281                                        SourceLocation CC) {
10282   QualType T = OrigE->getType();
10283   Expr *E = OrigE->IgnoreParenImpCasts();
10284 
10285   if (E->isTypeDependent() || E->isValueDependent())
10286     return;
10287 
10288   // For conditional operators, we analyze the arguments as if they
10289   // were being fed directly into the output.
10290   if (isa<ConditionalOperator>(E)) {
10291     ConditionalOperator *CO = cast<ConditionalOperator>(E);
10292     CheckConditionalOperator(S, CO, CC, T);
10293     return;
10294   }
10295 
10296   // Check implicit argument conversions for function calls.
10297   if (CallExpr *Call = dyn_cast<CallExpr>(E))
10298     CheckImplicitArgumentConversions(S, Call, CC);
10299 
10300   // Go ahead and check any implicit conversions we might have skipped.
10301   // The non-canonical typecheck is just an optimization;
10302   // CheckImplicitConversion will filter out dead implicit conversions.
10303   if (E->getType() != T)
10304     CheckImplicitConversion(S, E, T, CC);
10305 
10306   // Now continue drilling into this expression.
10307 
10308   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10309     // The bound subexpressions in a PseudoObjectExpr are not reachable
10310     // as transitive children.
10311     // FIXME: Use a more uniform representation for this.
10312     for (auto *SE : POE->semantics())
10313       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10314         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
10315   }
10316 
10317   // Skip past explicit casts.
10318   if (isa<ExplicitCastExpr>(E)) {
10319     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
10320     return AnalyzeImplicitConversions(S, E, CC);
10321   }
10322 
10323   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10324     // Do a somewhat different check with comparison operators.
10325     if (BO->isComparisonOp())
10326       return AnalyzeComparison(S, BO);
10327 
10328     // And with simple assignments.
10329     if (BO->getOpcode() == BO_Assign)
10330       return AnalyzeAssignment(S, BO);
10331     // And with compound assignments.
10332     if (BO->isAssignmentOp())
10333       return AnalyzeCompoundAssignment(S, BO);
10334   }
10335 
10336   // These break the otherwise-useful invariant below.  Fortunately,
10337   // we don't really need to recurse into them, because any internal
10338   // expressions should have been analyzed already when they were
10339   // built into statements.
10340   if (isa<StmtExpr>(E)) return;
10341 
10342   // Don't descend into unevaluated contexts.
10343   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
10344 
10345   // Now just recurse over the expression's children.
10346   CC = E->getExprLoc();
10347   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
10348   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
10349   for (Stmt *SubStmt : E->children()) {
10350     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
10351     if (!ChildExpr)
10352       continue;
10353 
10354     if (IsLogicalAndOperator &&
10355         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
10356       // Ignore checking string literals that are in logical and operators.
10357       // This is a common pattern for asserts.
10358       continue;
10359     AnalyzeImplicitConversions(S, ChildExpr, CC);
10360   }
10361 
10362   if (BO && BO->isLogicalOp()) {
10363     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10364     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10365       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10366 
10367     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10368     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10369       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10370   }
10371 
10372   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10373     if (U->getOpcode() == UO_LNot)
10374       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
10375 }
10376 
10377 /// Diagnose integer type and any valid implicit conversion to it.
10378 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10379   // Taking into account implicit conversions,
10380   // allow any integer.
10381   if (!E->getType()->isIntegerType()) {
10382     S.Diag(E->getLocStart(),
10383            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10384     return true;
10385   }
10386   // Potentially emit standard warnings for implicit conversions if enabled
10387   // using -Wconversion.
10388   CheckImplicitConversion(S, E, IntT, E->getLocStart());
10389   return false;
10390 }
10391 
10392 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10393 // Returns true when emitting a warning about taking the address of a reference.
10394 static bool CheckForReference(Sema &SemaRef, const Expr *E,
10395                               const PartialDiagnostic &PD) {
10396   E = E->IgnoreParenImpCasts();
10397 
10398   const FunctionDecl *FD = nullptr;
10399 
10400   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10401     if (!DRE->getDecl()->getType()->isReferenceType())
10402       return false;
10403   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10404     if (!M->getMemberDecl()->getType()->isReferenceType())
10405       return false;
10406   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
10407     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
10408       return false;
10409     FD = Call->getDirectCallee();
10410   } else {
10411     return false;
10412   }
10413 
10414   SemaRef.Diag(E->getExprLoc(), PD);
10415 
10416   // If possible, point to location of function.
10417   if (FD) {
10418     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10419   }
10420 
10421   return true;
10422 }
10423 
10424 // Returns true if the SourceLocation is expanded from any macro body.
10425 // Returns false if the SourceLocation is invalid, is from not in a macro
10426 // expansion, or is from expanded from a top-level macro argument.
10427 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10428   if (Loc.isInvalid())
10429     return false;
10430 
10431   while (Loc.isMacroID()) {
10432     if (SM.isMacroBodyExpansion(Loc))
10433       return true;
10434     Loc = SM.getImmediateMacroCallerLoc(Loc);
10435   }
10436 
10437   return false;
10438 }
10439 
10440 /// Diagnose pointers that are always non-null.
10441 /// \param E the expression containing the pointer
10442 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10443 /// compared to a null pointer
10444 /// \param IsEqual True when the comparison is equal to a null pointer
10445 /// \param Range Extra SourceRange to highlight in the diagnostic
10446 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10447                                         Expr::NullPointerConstantKind NullKind,
10448                                         bool IsEqual, SourceRange Range) {
10449   if (!E)
10450     return;
10451 
10452   // Don't warn inside macros.
10453   if (E->getExprLoc().isMacroID()) {
10454     const SourceManager &SM = getSourceManager();
10455     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10456         IsInAnyMacroBody(SM, Range.getBegin()))
10457       return;
10458   }
10459   E = E->IgnoreImpCasts();
10460 
10461   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10462 
10463   if (isa<CXXThisExpr>(E)) {
10464     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10465                                 : diag::warn_this_bool_conversion;
10466     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10467     return;
10468   }
10469 
10470   bool IsAddressOf = false;
10471 
10472   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10473     if (UO->getOpcode() != UO_AddrOf)
10474       return;
10475     IsAddressOf = true;
10476     E = UO->getSubExpr();
10477   }
10478 
10479   if (IsAddressOf) {
10480     unsigned DiagID = IsCompare
10481                           ? diag::warn_address_of_reference_null_compare
10482                           : diag::warn_address_of_reference_bool_conversion;
10483     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10484                                          << IsEqual;
10485     if (CheckForReference(*this, E, PD)) {
10486       return;
10487     }
10488   }
10489 
10490   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10491     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10492     std::string Str;
10493     llvm::raw_string_ostream S(Str);
10494     E->printPretty(S, nullptr, getPrintingPolicy());
10495     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10496                                 : diag::warn_cast_nonnull_to_bool;
10497     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10498       << E->getSourceRange() << Range << IsEqual;
10499     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10500   };
10501 
10502   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10503   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10504     if (auto *Callee = Call->getDirectCallee()) {
10505       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10506         ComplainAboutNonnullParamOrCall(A);
10507         return;
10508       }
10509     }
10510   }
10511 
10512   // Expect to find a single Decl.  Skip anything more complicated.
10513   ValueDecl *D = nullptr;
10514   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10515     D = R->getDecl();
10516   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10517     D = M->getMemberDecl();
10518   }
10519 
10520   // Weak Decls can be null.
10521   if (!D || D->isWeak())
10522     return;
10523 
10524   // Check for parameter decl with nonnull attribute
10525   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10526     if (getCurFunction() &&
10527         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10528       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10529         ComplainAboutNonnullParamOrCall(A);
10530         return;
10531       }
10532 
10533       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10534         auto ParamIter = llvm::find(FD->parameters(), PV);
10535         assert(ParamIter != FD->param_end());
10536         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10537 
10538         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10539           if (!NonNull->args_size()) {
10540               ComplainAboutNonnullParamOrCall(NonNull);
10541               return;
10542           }
10543 
10544           for (const ParamIdx &ArgNo : NonNull->args()) {
10545             if (ArgNo.getASTIndex() == ParamNo) {
10546               ComplainAboutNonnullParamOrCall(NonNull);
10547               return;
10548             }
10549           }
10550         }
10551       }
10552     }
10553   }
10554 
10555   QualType T = D->getType();
10556   const bool IsArray = T->isArrayType();
10557   const bool IsFunction = T->isFunctionType();
10558 
10559   // Address of function is used to silence the function warning.
10560   if (IsAddressOf && IsFunction) {
10561     return;
10562   }
10563 
10564   // Found nothing.
10565   if (!IsAddressOf && !IsFunction && !IsArray)
10566     return;
10567 
10568   // Pretty print the expression for the diagnostic.
10569   std::string Str;
10570   llvm::raw_string_ostream S(Str);
10571   E->printPretty(S, nullptr, getPrintingPolicy());
10572 
10573   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10574                               : diag::warn_impcast_pointer_to_bool;
10575   enum {
10576     AddressOf,
10577     FunctionPointer,
10578     ArrayPointer
10579   } DiagType;
10580   if (IsAddressOf)
10581     DiagType = AddressOf;
10582   else if (IsFunction)
10583     DiagType = FunctionPointer;
10584   else if (IsArray)
10585     DiagType = ArrayPointer;
10586   else
10587     llvm_unreachable("Could not determine diagnostic.");
10588   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10589                                 << Range << IsEqual;
10590 
10591   if (!IsFunction)
10592     return;
10593 
10594   // Suggest '&' to silence the function warning.
10595   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10596       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10597 
10598   // Check to see if '()' fixit should be emitted.
10599   QualType ReturnType;
10600   UnresolvedSet<4> NonTemplateOverloads;
10601   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10602   if (ReturnType.isNull())
10603     return;
10604 
10605   if (IsCompare) {
10606     // There are two cases here.  If there is null constant, the only suggest
10607     // for a pointer return type.  If the null is 0, then suggest if the return
10608     // type is a pointer or an integer type.
10609     if (!ReturnType->isPointerType()) {
10610       if (NullKind == Expr::NPCK_ZeroExpression ||
10611           NullKind == Expr::NPCK_ZeroLiteral) {
10612         if (!ReturnType->isIntegerType())
10613           return;
10614       } else {
10615         return;
10616       }
10617     }
10618   } else { // !IsCompare
10619     // For function to bool, only suggest if the function pointer has bool
10620     // return type.
10621     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10622       return;
10623   }
10624   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10625       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10626 }
10627 
10628 /// Diagnoses "dangerous" implicit conversions within the given
10629 /// expression (which is a full expression).  Implements -Wconversion
10630 /// and -Wsign-compare.
10631 ///
10632 /// \param CC the "context" location of the implicit conversion, i.e.
10633 ///   the most location of the syntactic entity requiring the implicit
10634 ///   conversion
10635 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10636   // Don't diagnose in unevaluated contexts.
10637   if (isUnevaluatedContext())
10638     return;
10639 
10640   // Don't diagnose for value- or type-dependent expressions.
10641   if (E->isTypeDependent() || E->isValueDependent())
10642     return;
10643 
10644   // Check for array bounds violations in cases where the check isn't triggered
10645   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10646   // ArraySubscriptExpr is on the RHS of a variable initialization.
10647   CheckArrayAccess(E);
10648 
10649   // This is not the right CC for (e.g.) a variable initialization.
10650   AnalyzeImplicitConversions(*this, E, CC);
10651 }
10652 
10653 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10654 /// Input argument E is a logical expression.
10655 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10656   ::CheckBoolLikeConversion(*this, E, CC);
10657 }
10658 
10659 /// Diagnose when expression is an integer constant expression and its evaluation
10660 /// results in integer overflow
10661 void Sema::CheckForIntOverflow (Expr *E) {
10662   // Use a work list to deal with nested struct initializers.
10663   SmallVector<Expr *, 2> Exprs(1, E);
10664 
10665   do {
10666     Expr *OriginalE = Exprs.pop_back_val();
10667     Expr *E = OriginalE->IgnoreParenCasts();
10668 
10669     if (isa<BinaryOperator>(E)) {
10670       E->EvaluateForOverflow(Context);
10671       continue;
10672     }
10673 
10674     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
10675       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10676     else if (isa<ObjCBoxedExpr>(OriginalE))
10677       E->EvaluateForOverflow(Context);
10678     else if (auto Call = dyn_cast<CallExpr>(E))
10679       Exprs.append(Call->arg_begin(), Call->arg_end());
10680     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10681       Exprs.append(Message->arg_begin(), Message->arg_end());
10682   } while (!Exprs.empty());
10683 }
10684 
10685 namespace {
10686 
10687 /// Visitor for expressions which looks for unsequenced operations on the
10688 /// same object.
10689 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10690   using Base = EvaluatedExprVisitor<SequenceChecker>;
10691 
10692   /// A tree of sequenced regions within an expression. Two regions are
10693   /// unsequenced if one is an ancestor or a descendent of the other. When we
10694   /// finish processing an expression with sequencing, such as a comma
10695   /// expression, we fold its tree nodes into its parent, since they are
10696   /// unsequenced with respect to nodes we will visit later.
10697   class SequenceTree {
10698     struct Value {
10699       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10700       unsigned Parent : 31;
10701       unsigned Merged : 1;
10702     };
10703     SmallVector<Value, 8> Values;
10704 
10705   public:
10706     /// A region within an expression which may be sequenced with respect
10707     /// to some other region.
10708     class Seq {
10709       friend class SequenceTree;
10710 
10711       unsigned Index = 0;
10712 
10713       explicit Seq(unsigned N) : Index(N) {}
10714 
10715     public:
10716       Seq() = default;
10717     };
10718 
10719     SequenceTree() { Values.push_back(Value(0)); }
10720     Seq root() const { return Seq(0); }
10721 
10722     /// Create a new sequence of operations, which is an unsequenced
10723     /// subset of \p Parent. This sequence of operations is sequenced with
10724     /// respect to other children of \p Parent.
10725     Seq allocate(Seq Parent) {
10726       Values.push_back(Value(Parent.Index));
10727       return Seq(Values.size() - 1);
10728     }
10729 
10730     /// Merge a sequence of operations into its parent.
10731     void merge(Seq S) {
10732       Values[S.Index].Merged = true;
10733     }
10734 
10735     /// Determine whether two operations are unsequenced. This operation
10736     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10737     /// should have been merged into its parent as appropriate.
10738     bool isUnsequenced(Seq Cur, Seq Old) {
10739       unsigned C = representative(Cur.Index);
10740       unsigned Target = representative(Old.Index);
10741       while (C >= Target) {
10742         if (C == Target)
10743           return true;
10744         C = Values[C].Parent;
10745       }
10746       return false;
10747     }
10748 
10749   private:
10750     /// Pick a representative for a sequence.
10751     unsigned representative(unsigned K) {
10752       if (Values[K].Merged)
10753         // Perform path compression as we go.
10754         return Values[K].Parent = representative(Values[K].Parent);
10755       return K;
10756     }
10757   };
10758 
10759   /// An object for which we can track unsequenced uses.
10760   using Object = NamedDecl *;
10761 
10762   /// Different flavors of object usage which we track. We only track the
10763   /// least-sequenced usage of each kind.
10764   enum UsageKind {
10765     /// A read of an object. Multiple unsequenced reads are OK.
10766     UK_Use,
10767 
10768     /// A modification of an object which is sequenced before the value
10769     /// computation of the expression, such as ++n in C++.
10770     UK_ModAsValue,
10771 
10772     /// A modification of an object which is not sequenced before the value
10773     /// computation of the expression, such as n++.
10774     UK_ModAsSideEffect,
10775 
10776     UK_Count = UK_ModAsSideEffect + 1
10777   };
10778 
10779   struct Usage {
10780     Expr *Use = nullptr;
10781     SequenceTree::Seq Seq;
10782 
10783     Usage() = default;
10784   };
10785 
10786   struct UsageInfo {
10787     Usage Uses[UK_Count];
10788 
10789     /// Have we issued a diagnostic for this variable already?
10790     bool Diagnosed = false;
10791 
10792     UsageInfo() = default;
10793   };
10794   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10795 
10796   Sema &SemaRef;
10797 
10798   /// Sequenced regions within the expression.
10799   SequenceTree Tree;
10800 
10801   /// Declaration modifications and references which we have seen.
10802   UsageInfoMap UsageMap;
10803 
10804   /// The region we are currently within.
10805   SequenceTree::Seq Region;
10806 
10807   /// Filled in with declarations which were modified as a side-effect
10808   /// (that is, post-increment operations).
10809   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10810 
10811   /// Expressions to check later. We defer checking these to reduce
10812   /// stack usage.
10813   SmallVectorImpl<Expr *> &WorkList;
10814 
10815   /// RAII object wrapping the visitation of a sequenced subexpression of an
10816   /// expression. At the end of this process, the side-effects of the evaluation
10817   /// become sequenced with respect to the value computation of the result, so
10818   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10819   /// UK_ModAsValue.
10820   struct SequencedSubexpression {
10821     SequencedSubexpression(SequenceChecker &Self)
10822       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10823       Self.ModAsSideEffect = &ModAsSideEffect;
10824     }
10825 
10826     ~SequencedSubexpression() {
10827       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10828         UsageInfo &U = Self.UsageMap[M.first];
10829         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10830         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10831         SideEffectUsage = M.second;
10832       }
10833       Self.ModAsSideEffect = OldModAsSideEffect;
10834     }
10835 
10836     SequenceChecker &Self;
10837     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10838     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10839   };
10840 
10841   /// RAII object wrapping the visitation of a subexpression which we might
10842   /// choose to evaluate as a constant. If any subexpression is evaluated and
10843   /// found to be non-constant, this allows us to suppress the evaluation of
10844   /// the outer expression.
10845   class EvaluationTracker {
10846   public:
10847     EvaluationTracker(SequenceChecker &Self)
10848         : Self(Self), Prev(Self.EvalTracker) {
10849       Self.EvalTracker = this;
10850     }
10851 
10852     ~EvaluationTracker() {
10853       Self.EvalTracker = Prev;
10854       if (Prev)
10855         Prev->EvalOK &= EvalOK;
10856     }
10857 
10858     bool evaluate(const Expr *E, bool &Result) {
10859       if (!EvalOK || E->isValueDependent())
10860         return false;
10861       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10862       return EvalOK;
10863     }
10864 
10865   private:
10866     SequenceChecker &Self;
10867     EvaluationTracker *Prev;
10868     bool EvalOK = true;
10869   } *EvalTracker = nullptr;
10870 
10871   /// Find the object which is produced by the specified expression,
10872   /// if any.
10873   Object getObject(Expr *E, bool Mod) const {
10874     E = E->IgnoreParenCasts();
10875     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10876       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10877         return getObject(UO->getSubExpr(), Mod);
10878     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10879       if (BO->getOpcode() == BO_Comma)
10880         return getObject(BO->getRHS(), Mod);
10881       if (Mod && BO->isAssignmentOp())
10882         return getObject(BO->getLHS(), Mod);
10883     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10884       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10885       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10886         return ME->getMemberDecl();
10887     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10888       // FIXME: If this is a reference, map through to its value.
10889       return DRE->getDecl();
10890     return nullptr;
10891   }
10892 
10893   /// Note that an object was modified or used by an expression.
10894   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10895     Usage &U = UI.Uses[UK];
10896     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10897       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10898         ModAsSideEffect->push_back(std::make_pair(O, U));
10899       U.Use = Ref;
10900       U.Seq = Region;
10901     }
10902   }
10903 
10904   /// Check whether a modification or use conflicts with a prior usage.
10905   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10906                   bool IsModMod) {
10907     if (UI.Diagnosed)
10908       return;
10909 
10910     const Usage &U = UI.Uses[OtherKind];
10911     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10912       return;
10913 
10914     Expr *Mod = U.Use;
10915     Expr *ModOrUse = Ref;
10916     if (OtherKind == UK_Use)
10917       std::swap(Mod, ModOrUse);
10918 
10919     SemaRef.Diag(Mod->getExprLoc(),
10920                  IsModMod ? diag::warn_unsequenced_mod_mod
10921                           : diag::warn_unsequenced_mod_use)
10922       << O << SourceRange(ModOrUse->getExprLoc());
10923     UI.Diagnosed = true;
10924   }
10925 
10926   void notePreUse(Object O, Expr *Use) {
10927     UsageInfo &U = UsageMap[O];
10928     // Uses conflict with other modifications.
10929     checkUsage(O, U, Use, UK_ModAsValue, false);
10930   }
10931 
10932   void notePostUse(Object O, Expr *Use) {
10933     UsageInfo &U = UsageMap[O];
10934     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10935     addUsage(U, O, Use, UK_Use);
10936   }
10937 
10938   void notePreMod(Object O, Expr *Mod) {
10939     UsageInfo &U = UsageMap[O];
10940     // Modifications conflict with other modifications and with uses.
10941     checkUsage(O, U, Mod, UK_ModAsValue, true);
10942     checkUsage(O, U, Mod, UK_Use, false);
10943   }
10944 
10945   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10946     UsageInfo &U = UsageMap[O];
10947     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10948     addUsage(U, O, Use, UK);
10949   }
10950 
10951 public:
10952   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10953       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10954     Visit(E);
10955   }
10956 
10957   void VisitStmt(Stmt *S) {
10958     // Skip all statements which aren't expressions for now.
10959   }
10960 
10961   void VisitExpr(Expr *E) {
10962     // By default, just recurse to evaluated subexpressions.
10963     Base::VisitStmt(E);
10964   }
10965 
10966   void VisitCastExpr(CastExpr *E) {
10967     Object O = Object();
10968     if (E->getCastKind() == CK_LValueToRValue)
10969       O = getObject(E->getSubExpr(), false);
10970 
10971     if (O)
10972       notePreUse(O, E);
10973     VisitExpr(E);
10974     if (O)
10975       notePostUse(O, E);
10976   }
10977 
10978   void VisitBinComma(BinaryOperator *BO) {
10979     // C++11 [expr.comma]p1:
10980     //   Every value computation and side effect associated with the left
10981     //   expression is sequenced before every value computation and side
10982     //   effect associated with the right expression.
10983     SequenceTree::Seq LHS = Tree.allocate(Region);
10984     SequenceTree::Seq RHS = Tree.allocate(Region);
10985     SequenceTree::Seq OldRegion = Region;
10986 
10987     {
10988       SequencedSubexpression SeqLHS(*this);
10989       Region = LHS;
10990       Visit(BO->getLHS());
10991     }
10992 
10993     Region = RHS;
10994     Visit(BO->getRHS());
10995 
10996     Region = OldRegion;
10997 
10998     // Forget that LHS and RHS are sequenced. They are both unsequenced
10999     // with respect to other stuff.
11000     Tree.merge(LHS);
11001     Tree.merge(RHS);
11002   }
11003 
11004   void VisitBinAssign(BinaryOperator *BO) {
11005     // The modification is sequenced after the value computation of the LHS
11006     // and RHS, so check it before inspecting the operands and update the
11007     // map afterwards.
11008     Object O = getObject(BO->getLHS(), true);
11009     if (!O)
11010       return VisitExpr(BO);
11011 
11012     notePreMod(O, BO);
11013 
11014     // C++11 [expr.ass]p7:
11015     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11016     //   only once.
11017     //
11018     // Therefore, for a compound assignment operator, O is considered used
11019     // everywhere except within the evaluation of E1 itself.
11020     if (isa<CompoundAssignOperator>(BO))
11021       notePreUse(O, BO);
11022 
11023     Visit(BO->getLHS());
11024 
11025     if (isa<CompoundAssignOperator>(BO))
11026       notePostUse(O, BO);
11027 
11028     Visit(BO->getRHS());
11029 
11030     // C++11 [expr.ass]p1:
11031     //   the assignment is sequenced [...] before the value computation of the
11032     //   assignment expression.
11033     // C11 6.5.16/3 has no such rule.
11034     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11035                                                        : UK_ModAsSideEffect);
11036   }
11037 
11038   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11039     VisitBinAssign(CAO);
11040   }
11041 
11042   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11043   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11044   void VisitUnaryPreIncDec(UnaryOperator *UO) {
11045     Object O = getObject(UO->getSubExpr(), true);
11046     if (!O)
11047       return VisitExpr(UO);
11048 
11049     notePreMod(O, UO);
11050     Visit(UO->getSubExpr());
11051     // C++11 [expr.pre.incr]p1:
11052     //   the expression ++x is equivalent to x+=1
11053     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11054                                                        : UK_ModAsSideEffect);
11055   }
11056 
11057   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11058   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11059   void VisitUnaryPostIncDec(UnaryOperator *UO) {
11060     Object O = getObject(UO->getSubExpr(), true);
11061     if (!O)
11062       return VisitExpr(UO);
11063 
11064     notePreMod(O, UO);
11065     Visit(UO->getSubExpr());
11066     notePostMod(O, UO, UK_ModAsSideEffect);
11067   }
11068 
11069   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11070   void VisitBinLOr(BinaryOperator *BO) {
11071     // The side-effects of the LHS of an '&&' are sequenced before the
11072     // value computation of the RHS, and hence before the value computation
11073     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11074     // as if they were unconditionally sequenced.
11075     EvaluationTracker Eval(*this);
11076     {
11077       SequencedSubexpression Sequenced(*this);
11078       Visit(BO->getLHS());
11079     }
11080 
11081     bool Result;
11082     if (Eval.evaluate(BO->getLHS(), Result)) {
11083       if (!Result)
11084         Visit(BO->getRHS());
11085     } else {
11086       // Check for unsequenced operations in the RHS, treating it as an
11087       // entirely separate evaluation.
11088       //
11089       // FIXME: If there are operations in the RHS which are unsequenced
11090       // with respect to operations outside the RHS, and those operations
11091       // are unconditionally evaluated, diagnose them.
11092       WorkList.push_back(BO->getRHS());
11093     }
11094   }
11095   void VisitBinLAnd(BinaryOperator *BO) {
11096     EvaluationTracker Eval(*this);
11097     {
11098       SequencedSubexpression Sequenced(*this);
11099       Visit(BO->getLHS());
11100     }
11101 
11102     bool Result;
11103     if (Eval.evaluate(BO->getLHS(), Result)) {
11104       if (Result)
11105         Visit(BO->getRHS());
11106     } else {
11107       WorkList.push_back(BO->getRHS());
11108     }
11109   }
11110 
11111   // Only visit the condition, unless we can be sure which subexpression will
11112   // be chosen.
11113   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
11114     EvaluationTracker Eval(*this);
11115     {
11116       SequencedSubexpression Sequenced(*this);
11117       Visit(CO->getCond());
11118     }
11119 
11120     bool Result;
11121     if (Eval.evaluate(CO->getCond(), Result))
11122       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
11123     else {
11124       WorkList.push_back(CO->getTrueExpr());
11125       WorkList.push_back(CO->getFalseExpr());
11126     }
11127   }
11128 
11129   void VisitCallExpr(CallExpr *CE) {
11130     // C++11 [intro.execution]p15:
11131     //   When calling a function [...], every value computation and side effect
11132     //   associated with any argument expression, or with the postfix expression
11133     //   designating the called function, is sequenced before execution of every
11134     //   expression or statement in the body of the function [and thus before
11135     //   the value computation of its result].
11136     SequencedSubexpression Sequenced(*this);
11137     Base::VisitCallExpr(CE);
11138 
11139     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11140   }
11141 
11142   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
11143     // This is a call, so all subexpressions are sequenced before the result.
11144     SequencedSubexpression Sequenced(*this);
11145 
11146     if (!CCE->isListInitialization())
11147       return VisitExpr(CCE);
11148 
11149     // In C++11, list initializations are sequenced.
11150     SmallVector<SequenceTree::Seq, 32> Elts;
11151     SequenceTree::Seq Parent = Region;
11152     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11153                                         E = CCE->arg_end();
11154          I != E; ++I) {
11155       Region = Tree.allocate(Parent);
11156       Elts.push_back(Region);
11157       Visit(*I);
11158     }
11159 
11160     // Forget that the initializers are sequenced.
11161     Region = Parent;
11162     for (unsigned I = 0; I < Elts.size(); ++I)
11163       Tree.merge(Elts[I]);
11164   }
11165 
11166   void VisitInitListExpr(InitListExpr *ILE) {
11167     if (!SemaRef.getLangOpts().CPlusPlus11)
11168       return VisitExpr(ILE);
11169 
11170     // In C++11, list initializations are sequenced.
11171     SmallVector<SequenceTree::Seq, 32> Elts;
11172     SequenceTree::Seq Parent = Region;
11173     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11174       Expr *E = ILE->getInit(I);
11175       if (!E) continue;
11176       Region = Tree.allocate(Parent);
11177       Elts.push_back(Region);
11178       Visit(E);
11179     }
11180 
11181     // Forget that the initializers are sequenced.
11182     Region = Parent;
11183     for (unsigned I = 0; I < Elts.size(); ++I)
11184       Tree.merge(Elts[I]);
11185   }
11186 };
11187 
11188 } // namespace
11189 
11190 void Sema::CheckUnsequencedOperations(Expr *E) {
11191   SmallVector<Expr *, 8> WorkList;
11192   WorkList.push_back(E);
11193   while (!WorkList.empty()) {
11194     Expr *Item = WorkList.pop_back_val();
11195     SequenceChecker(*this, Item, WorkList);
11196   }
11197 }
11198 
11199 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11200                               bool IsConstexpr) {
11201   CheckImplicitConversions(E, CheckLoc);
11202   if (!E->isInstantiationDependent())
11203     CheckUnsequencedOperations(E);
11204   if (!IsConstexpr && !E->isValueDependent())
11205     CheckForIntOverflow(E);
11206   DiagnoseMisalignedMembers();
11207 }
11208 
11209 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11210                                        FieldDecl *BitField,
11211                                        Expr *Init) {
11212   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11213 }
11214 
11215 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11216                                          SourceLocation Loc) {
11217   if (!PType->isVariablyModifiedType())
11218     return;
11219   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11220     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11221     return;
11222   }
11223   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11224     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11225     return;
11226   }
11227   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11228     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11229     return;
11230   }
11231 
11232   const ArrayType *AT = S.Context.getAsArrayType(PType);
11233   if (!AT)
11234     return;
11235 
11236   if (AT->getSizeModifier() != ArrayType::Star) {
11237     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11238     return;
11239   }
11240 
11241   S.Diag(Loc, diag::err_array_star_in_function_definition);
11242 }
11243 
11244 /// CheckParmsForFunctionDef - Check that the parameters of the given
11245 /// function are appropriate for the definition of a function. This
11246 /// takes care of any checks that cannot be performed on the
11247 /// declaration itself, e.g., that the types of each of the function
11248 /// parameters are complete.
11249 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
11250                                     bool CheckParameterNames) {
11251   bool HasInvalidParm = false;
11252   for (ParmVarDecl *Param : Parameters) {
11253     // C99 6.7.5.3p4: the parameters in a parameter type list in a
11254     // function declarator that is part of a function definition of
11255     // that function shall not have incomplete type.
11256     //
11257     // This is also C++ [dcl.fct]p6.
11258     if (!Param->isInvalidDecl() &&
11259         RequireCompleteType(Param->getLocation(), Param->getType(),
11260                             diag::err_typecheck_decl_incomplete_type)) {
11261       Param->setInvalidDecl();
11262       HasInvalidParm = true;
11263     }
11264 
11265     // C99 6.9.1p5: If the declarator includes a parameter type list, the
11266     // declaration of each parameter shall include an identifier.
11267     if (CheckParameterNames &&
11268         Param->getIdentifier() == nullptr &&
11269         !Param->isImplicit() &&
11270         !getLangOpts().CPlusPlus)
11271       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11272 
11273     // C99 6.7.5.3p12:
11274     //   If the function declarator is not part of a definition of that
11275     //   function, parameters may have incomplete type and may use the [*]
11276     //   notation in their sequences of declarator specifiers to specify
11277     //   variable length array types.
11278     QualType PType = Param->getOriginalType();
11279     // FIXME: This diagnostic should point the '[*]' if source-location
11280     // information is added for it.
11281     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
11282 
11283     // If the parameter is a c++ class type and it has to be destructed in the
11284     // callee function, declare the destructor so that it can be called by the
11285     // callee function. Do not perform any direct access check on the dtor here.
11286     if (!Param->isInvalidDecl()) {
11287       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11288         if (!ClassDecl->isInvalidDecl() &&
11289             !ClassDecl->hasIrrelevantDestructor() &&
11290             !ClassDecl->isDependentContext() &&
11291             ClassDecl->isParamDestroyedInCallee()) {
11292           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11293           MarkFunctionReferenced(Param->getLocation(), Destructor);
11294           DiagnoseUseOfDecl(Destructor, Param->getLocation());
11295         }
11296       }
11297     }
11298 
11299     // Parameters with the pass_object_size attribute only need to be marked
11300     // constant at function definitions. Because we lack information about
11301     // whether we're on a declaration or definition when we're instantiating the
11302     // attribute, we need to check for constness here.
11303     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11304       if (!Param->getType().isConstQualified())
11305         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11306             << Attr->getSpelling() << 1;
11307   }
11308 
11309   return HasInvalidParm;
11310 }
11311 
11312 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11313 /// or MemberExpr.
11314 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11315                               ASTContext &Context) {
11316   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11317     return Context.getDeclAlign(DRE->getDecl());
11318 
11319   if (const auto *ME = dyn_cast<MemberExpr>(E))
11320     return Context.getDeclAlign(ME->getMemberDecl());
11321 
11322   return TypeAlign;
11323 }
11324 
11325 /// CheckCastAlign - Implements -Wcast-align, which warns when a
11326 /// pointer cast increases the alignment requirements.
11327 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11328   // This is actually a lot of work to potentially be doing on every
11329   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
11330   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
11331     return;
11332 
11333   // Ignore dependent types.
11334   if (T->isDependentType() || Op->getType()->isDependentType())
11335     return;
11336 
11337   // Require that the destination be a pointer type.
11338   const PointerType *DestPtr = T->getAs<PointerType>();
11339   if (!DestPtr) return;
11340 
11341   // If the destination has alignment 1, we're done.
11342   QualType DestPointee = DestPtr->getPointeeType();
11343   if (DestPointee->isIncompleteType()) return;
11344   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11345   if (DestAlign.isOne()) return;
11346 
11347   // Require that the source be a pointer type.
11348   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11349   if (!SrcPtr) return;
11350   QualType SrcPointee = SrcPtr->getPointeeType();
11351 
11352   // Whitelist casts from cv void*.  We already implicitly
11353   // whitelisted casts to cv void*, since they have alignment 1.
11354   // Also whitelist casts involving incomplete types, which implicitly
11355   // includes 'void'.
11356   if (SrcPointee->isIncompleteType()) return;
11357 
11358   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
11359 
11360   if (auto *CE = dyn_cast<CastExpr>(Op)) {
11361     if (CE->getCastKind() == CK_ArrayToPointerDecay)
11362       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11363   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11364     if (UO->getOpcode() == UO_AddrOf)
11365       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11366   }
11367 
11368   if (SrcAlign >= DestAlign) return;
11369 
11370   Diag(TRange.getBegin(), diag::warn_cast_align)
11371     << Op->getType() << T
11372     << static_cast<unsigned>(SrcAlign.getQuantity())
11373     << static_cast<unsigned>(DestAlign.getQuantity())
11374     << TRange << Op->getSourceRange();
11375 }
11376 
11377 /// Check whether this array fits the idiom of a size-one tail padded
11378 /// array member of a struct.
11379 ///
11380 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
11381 /// commonly used to emulate flexible arrays in C89 code.
11382 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
11383                                     const NamedDecl *ND) {
11384   if (Size != 1 || !ND) return false;
11385 
11386   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11387   if (!FD) return false;
11388 
11389   // Don't consider sizes resulting from macro expansions or template argument
11390   // substitution to form C89 tail-padded arrays.
11391 
11392   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
11393   while (TInfo) {
11394     TypeLoc TL = TInfo->getTypeLoc();
11395     // Look through typedefs.
11396     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11397       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
11398       TInfo = TDL->getTypeSourceInfo();
11399       continue;
11400     }
11401     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11402       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
11403       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11404         return false;
11405     }
11406     break;
11407   }
11408 
11409   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
11410   if (!RD) return false;
11411   if (RD->isUnion()) return false;
11412   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11413     if (!CRD->isStandardLayout()) return false;
11414   }
11415 
11416   // See if this is the last field decl in the record.
11417   const Decl *D = FD;
11418   while ((D = D->getNextDeclInContext()))
11419     if (isa<FieldDecl>(D))
11420       return false;
11421   return true;
11422 }
11423 
11424 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11425                             const ArraySubscriptExpr *ASE,
11426                             bool AllowOnePastEnd, bool IndexNegated) {
11427   IndexExpr = IndexExpr->IgnoreParenImpCasts();
11428   if (IndexExpr->isValueDependent())
11429     return;
11430 
11431   const Type *EffectiveType =
11432       BaseExpr->getType()->getPointeeOrArrayElementType();
11433   BaseExpr = BaseExpr->IgnoreParenCasts();
11434   const ConstantArrayType *ArrayTy =
11435     Context.getAsConstantArrayType(BaseExpr->getType());
11436   if (!ArrayTy)
11437     return;
11438 
11439   llvm::APSInt index;
11440   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11441     return;
11442   if (IndexNegated)
11443     index = -index;
11444 
11445   const NamedDecl *ND = nullptr;
11446   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11447     ND = DRE->getDecl();
11448   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11449     ND = ME->getMemberDecl();
11450 
11451   if (index.isUnsigned() || !index.isNegative()) {
11452     llvm::APInt size = ArrayTy->getSize();
11453     if (!size.isStrictlyPositive())
11454       return;
11455 
11456     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11457     if (BaseType != EffectiveType) {
11458       // Make sure we're comparing apples to apples when comparing index to size
11459       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11460       uint64_t array_typesize = Context.getTypeSize(BaseType);
11461       // Handle ptrarith_typesize being zero, such as when casting to void*
11462       if (!ptrarith_typesize) ptrarith_typesize = 1;
11463       if (ptrarith_typesize != array_typesize) {
11464         // There's a cast to a different size type involved
11465         uint64_t ratio = array_typesize / ptrarith_typesize;
11466         // TODO: Be smarter about handling cases where array_typesize is not a
11467         // multiple of ptrarith_typesize
11468         if (ptrarith_typesize * ratio == array_typesize)
11469           size *= llvm::APInt(size.getBitWidth(), ratio);
11470       }
11471     }
11472 
11473     if (size.getBitWidth() > index.getBitWidth())
11474       index = index.zext(size.getBitWidth());
11475     else if (size.getBitWidth() < index.getBitWidth())
11476       size = size.zext(index.getBitWidth());
11477 
11478     // For array subscripting the index must be less than size, but for pointer
11479     // arithmetic also allow the index (offset) to be equal to size since
11480     // computing the next address after the end of the array is legal and
11481     // commonly done e.g. in C++ iterators and range-based for loops.
11482     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11483       return;
11484 
11485     // Also don't warn for arrays of size 1 which are members of some
11486     // structure. These are often used to approximate flexible arrays in C89
11487     // code.
11488     if (IsTailPaddedMemberArray(*this, size, ND))
11489       return;
11490 
11491     // Suppress the warning if the subscript expression (as identified by the
11492     // ']' location) and the index expression are both from macro expansions
11493     // within a system header.
11494     if (ASE) {
11495       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11496           ASE->getRBracketLoc());
11497       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11498         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11499             IndexExpr->getLocStart());
11500         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11501           return;
11502       }
11503     }
11504 
11505     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11506     if (ASE)
11507       DiagID = diag::warn_array_index_exceeds_bounds;
11508 
11509     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11510                         PDiag(DiagID) << index.toString(10, true)
11511                           << size.toString(10, true)
11512                           << (unsigned)size.getLimitedValue(~0U)
11513                           << IndexExpr->getSourceRange());
11514   } else {
11515     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11516     if (!ASE) {
11517       DiagID = diag::warn_ptr_arith_precedes_bounds;
11518       if (index.isNegative()) index = -index;
11519     }
11520 
11521     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11522                         PDiag(DiagID) << index.toString(10, true)
11523                           << IndexExpr->getSourceRange());
11524   }
11525 
11526   if (!ND) {
11527     // Try harder to find a NamedDecl to point at in the note.
11528     while (const ArraySubscriptExpr *ASE =
11529            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11530       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11531     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11532       ND = DRE->getDecl();
11533     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11534       ND = ME->getMemberDecl();
11535   }
11536 
11537   if (ND)
11538     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11539                         PDiag(diag::note_array_index_out_of_bounds)
11540                           << ND->getDeclName());
11541 }
11542 
11543 void Sema::CheckArrayAccess(const Expr *expr) {
11544   int AllowOnePastEnd = 0;
11545   while (expr) {
11546     expr = expr->IgnoreParenImpCasts();
11547     switch (expr->getStmtClass()) {
11548       case Stmt::ArraySubscriptExprClass: {
11549         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11550         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11551                          AllowOnePastEnd > 0);
11552         expr = ASE->getBase();
11553         break;
11554       }
11555       case Stmt::MemberExprClass: {
11556         expr = cast<MemberExpr>(expr)->getBase();
11557         break;
11558       }
11559       case Stmt::OMPArraySectionExprClass: {
11560         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11561         if (ASE->getLowerBound())
11562           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11563                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11564         return;
11565       }
11566       case Stmt::UnaryOperatorClass: {
11567         // Only unwrap the * and & unary operators
11568         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11569         expr = UO->getSubExpr();
11570         switch (UO->getOpcode()) {
11571           case UO_AddrOf:
11572             AllowOnePastEnd++;
11573             break;
11574           case UO_Deref:
11575             AllowOnePastEnd--;
11576             break;
11577           default:
11578             return;
11579         }
11580         break;
11581       }
11582       case Stmt::ConditionalOperatorClass: {
11583         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11584         if (const Expr *lhs = cond->getLHS())
11585           CheckArrayAccess(lhs);
11586         if (const Expr *rhs = cond->getRHS())
11587           CheckArrayAccess(rhs);
11588         return;
11589       }
11590       case Stmt::CXXOperatorCallExprClass: {
11591         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11592         for (const auto *Arg : OCE->arguments())
11593           CheckArrayAccess(Arg);
11594         return;
11595       }
11596       default:
11597         return;
11598     }
11599   }
11600 }
11601 
11602 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11603 
11604 namespace {
11605 
11606 struct RetainCycleOwner {
11607   VarDecl *Variable = nullptr;
11608   SourceRange Range;
11609   SourceLocation Loc;
11610   bool Indirect = false;
11611 
11612   RetainCycleOwner() = default;
11613 
11614   void setLocsFrom(Expr *e) {
11615     Loc = e->getExprLoc();
11616     Range = e->getSourceRange();
11617   }
11618 };
11619 
11620 } // namespace
11621 
11622 /// Consider whether capturing the given variable can possibly lead to
11623 /// a retain cycle.
11624 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11625   // In ARC, it's captured strongly iff the variable has __strong
11626   // lifetime.  In MRR, it's captured strongly if the variable is
11627   // __block and has an appropriate type.
11628   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11629     return false;
11630 
11631   owner.Variable = var;
11632   if (ref)
11633     owner.setLocsFrom(ref);
11634   return true;
11635 }
11636 
11637 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11638   while (true) {
11639     e = e->IgnoreParens();
11640     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11641       switch (cast->getCastKind()) {
11642       case CK_BitCast:
11643       case CK_LValueBitCast:
11644       case CK_LValueToRValue:
11645       case CK_ARCReclaimReturnedObject:
11646         e = cast->getSubExpr();
11647         continue;
11648 
11649       default:
11650         return false;
11651       }
11652     }
11653 
11654     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11655       ObjCIvarDecl *ivar = ref->getDecl();
11656       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11657         return false;
11658 
11659       // Try to find a retain cycle in the base.
11660       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11661         return false;
11662 
11663       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11664       owner.Indirect = true;
11665       return true;
11666     }
11667 
11668     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11669       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11670       if (!var) return false;
11671       return considerVariable(var, ref, owner);
11672     }
11673 
11674     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11675       if (member->isArrow()) return false;
11676 
11677       // Don't count this as an indirect ownership.
11678       e = member->getBase();
11679       continue;
11680     }
11681 
11682     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11683       // Only pay attention to pseudo-objects on property references.
11684       ObjCPropertyRefExpr *pre
11685         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11686                                               ->IgnoreParens());
11687       if (!pre) return false;
11688       if (pre->isImplicitProperty()) return false;
11689       ObjCPropertyDecl *property = pre->getExplicitProperty();
11690       if (!property->isRetaining() &&
11691           !(property->getPropertyIvarDecl() &&
11692             property->getPropertyIvarDecl()->getType()
11693               .getObjCLifetime() == Qualifiers::OCL_Strong))
11694           return false;
11695 
11696       owner.Indirect = true;
11697       if (pre->isSuperReceiver()) {
11698         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11699         if (!owner.Variable)
11700           return false;
11701         owner.Loc = pre->getLocation();
11702         owner.Range = pre->getSourceRange();
11703         return true;
11704       }
11705       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11706                               ->getSourceExpr());
11707       continue;
11708     }
11709 
11710     // Array ivars?
11711 
11712     return false;
11713   }
11714 }
11715 
11716 namespace {
11717 
11718   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11719     ASTContext &Context;
11720     VarDecl *Variable;
11721     Expr *Capturer = nullptr;
11722     bool VarWillBeReased = false;
11723 
11724     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11725         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11726           Context(Context), Variable(variable) {}
11727 
11728     void VisitDeclRefExpr(DeclRefExpr *ref) {
11729       if (ref->getDecl() == Variable && !Capturer)
11730         Capturer = ref;
11731     }
11732 
11733     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11734       if (Capturer) return;
11735       Visit(ref->getBase());
11736       if (Capturer && ref->isFreeIvar())
11737         Capturer = ref;
11738     }
11739 
11740     void VisitBlockExpr(BlockExpr *block) {
11741       // Look inside nested blocks
11742       if (block->getBlockDecl()->capturesVariable(Variable))
11743         Visit(block->getBlockDecl()->getBody());
11744     }
11745 
11746     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11747       if (Capturer) return;
11748       if (OVE->getSourceExpr())
11749         Visit(OVE->getSourceExpr());
11750     }
11751 
11752     void VisitBinaryOperator(BinaryOperator *BinOp) {
11753       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11754         return;
11755       Expr *LHS = BinOp->getLHS();
11756       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11757         if (DRE->getDecl() != Variable)
11758           return;
11759         if (Expr *RHS = BinOp->getRHS()) {
11760           RHS = RHS->IgnoreParenCasts();
11761           llvm::APSInt Value;
11762           VarWillBeReased =
11763             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11764         }
11765       }
11766     }
11767   };
11768 
11769 } // namespace
11770 
11771 /// Check whether the given argument is a block which captures a
11772 /// variable.
11773 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11774   assert(owner.Variable && owner.Loc.isValid());
11775 
11776   e = e->IgnoreParenCasts();
11777 
11778   // Look through [^{...} copy] and Block_copy(^{...}).
11779   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11780     Selector Cmd = ME->getSelector();
11781     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11782       e = ME->getInstanceReceiver();
11783       if (!e)
11784         return nullptr;
11785       e = e->IgnoreParenCasts();
11786     }
11787   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11788     if (CE->getNumArgs() == 1) {
11789       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11790       if (Fn) {
11791         const IdentifierInfo *FnI = Fn->getIdentifier();
11792         if (FnI && FnI->isStr("_Block_copy")) {
11793           e = CE->getArg(0)->IgnoreParenCasts();
11794         }
11795       }
11796     }
11797   }
11798 
11799   BlockExpr *block = dyn_cast<BlockExpr>(e);
11800   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11801     return nullptr;
11802 
11803   FindCaptureVisitor visitor(S.Context, owner.Variable);
11804   visitor.Visit(block->getBlockDecl()->getBody());
11805   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11806 }
11807 
11808 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11809                                 RetainCycleOwner &owner) {
11810   assert(capturer);
11811   assert(owner.Variable && owner.Loc.isValid());
11812 
11813   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11814     << owner.Variable << capturer->getSourceRange();
11815   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11816     << owner.Indirect << owner.Range;
11817 }
11818 
11819 /// Check for a keyword selector that starts with the word 'add' or
11820 /// 'set'.
11821 static bool isSetterLikeSelector(Selector sel) {
11822   if (sel.isUnarySelector()) return false;
11823 
11824   StringRef str = sel.getNameForSlot(0);
11825   while (!str.empty() && str.front() == '_') str = str.substr(1);
11826   if (str.startswith("set"))
11827     str = str.substr(3);
11828   else if (str.startswith("add")) {
11829     // Specially whitelist 'addOperationWithBlock:'.
11830     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11831       return false;
11832     str = str.substr(3);
11833   }
11834   else
11835     return false;
11836 
11837   if (str.empty()) return true;
11838   return !isLowercase(str.front());
11839 }
11840 
11841 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11842                                                     ObjCMessageExpr *Message) {
11843   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11844                                                 Message->getReceiverInterface(),
11845                                                 NSAPI::ClassId_NSMutableArray);
11846   if (!IsMutableArray) {
11847     return None;
11848   }
11849 
11850   Selector Sel = Message->getSelector();
11851 
11852   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11853     S.NSAPIObj->getNSArrayMethodKind(Sel);
11854   if (!MKOpt) {
11855     return None;
11856   }
11857 
11858   NSAPI::NSArrayMethodKind MK = *MKOpt;
11859 
11860   switch (MK) {
11861     case NSAPI::NSMutableArr_addObject:
11862     case NSAPI::NSMutableArr_insertObjectAtIndex:
11863     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11864       return 0;
11865     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11866       return 1;
11867 
11868     default:
11869       return None;
11870   }
11871 
11872   return None;
11873 }
11874 
11875 static
11876 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11877                                                   ObjCMessageExpr *Message) {
11878   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11879                                             Message->getReceiverInterface(),
11880                                             NSAPI::ClassId_NSMutableDictionary);
11881   if (!IsMutableDictionary) {
11882     return None;
11883   }
11884 
11885   Selector Sel = Message->getSelector();
11886 
11887   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11888     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11889   if (!MKOpt) {
11890     return None;
11891   }
11892 
11893   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11894 
11895   switch (MK) {
11896     case NSAPI::NSMutableDict_setObjectForKey:
11897     case NSAPI::NSMutableDict_setValueForKey:
11898     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11899       return 0;
11900 
11901     default:
11902       return None;
11903   }
11904 
11905   return None;
11906 }
11907 
11908 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11909   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11910                                                 Message->getReceiverInterface(),
11911                                                 NSAPI::ClassId_NSMutableSet);
11912 
11913   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11914                                             Message->getReceiverInterface(),
11915                                             NSAPI::ClassId_NSMutableOrderedSet);
11916   if (!IsMutableSet && !IsMutableOrderedSet) {
11917     return None;
11918   }
11919 
11920   Selector Sel = Message->getSelector();
11921 
11922   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11923   if (!MKOpt) {
11924     return None;
11925   }
11926 
11927   NSAPI::NSSetMethodKind MK = *MKOpt;
11928 
11929   switch (MK) {
11930     case NSAPI::NSMutableSet_addObject:
11931     case NSAPI::NSOrderedSet_setObjectAtIndex:
11932     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11933     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11934       return 0;
11935     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11936       return 1;
11937   }
11938 
11939   return None;
11940 }
11941 
11942 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11943   if (!Message->isInstanceMessage()) {
11944     return;
11945   }
11946 
11947   Optional<int> ArgOpt;
11948 
11949   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11950       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11951       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11952     return;
11953   }
11954 
11955   int ArgIndex = *ArgOpt;
11956 
11957   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11958   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11959     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11960   }
11961 
11962   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11963     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11964       if (ArgRE->isObjCSelfExpr()) {
11965         Diag(Message->getSourceRange().getBegin(),
11966              diag::warn_objc_circular_container)
11967           << ArgRE->getDecl() << StringRef("'super'");
11968       }
11969     }
11970   } else {
11971     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11972 
11973     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11974       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11975     }
11976 
11977     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11978       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11979         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11980           ValueDecl *Decl = ReceiverRE->getDecl();
11981           Diag(Message->getSourceRange().getBegin(),
11982                diag::warn_objc_circular_container)
11983             << Decl << Decl;
11984           if (!ArgRE->isObjCSelfExpr()) {
11985             Diag(Decl->getLocation(),
11986                  diag::note_objc_circular_container_declared_here)
11987               << Decl;
11988           }
11989         }
11990       }
11991     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11992       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11993         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11994           ObjCIvarDecl *Decl = IvarRE->getDecl();
11995           Diag(Message->getSourceRange().getBegin(),
11996                diag::warn_objc_circular_container)
11997             << Decl << Decl;
11998           Diag(Decl->getLocation(),
11999                diag::note_objc_circular_container_declared_here)
12000             << Decl;
12001         }
12002       }
12003     }
12004   }
12005 }
12006 
12007 /// Check a message send to see if it's likely to cause a retain cycle.
12008 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12009   // Only check instance methods whose selector looks like a setter.
12010   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12011     return;
12012 
12013   // Try to find a variable that the receiver is strongly owned by.
12014   RetainCycleOwner owner;
12015   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
12016     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
12017       return;
12018   } else {
12019     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12020     owner.Variable = getCurMethodDecl()->getSelfDecl();
12021     owner.Loc = msg->getSuperLoc();
12022     owner.Range = msg->getSuperLoc();
12023   }
12024 
12025   // Check whether the receiver is captured by any of the arguments.
12026   const ObjCMethodDecl *MD = msg->getMethodDecl();
12027   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12028     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12029       // noescape blocks should not be retained by the method.
12030       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12031         continue;
12032       return diagnoseRetainCycle(*this, capturer, owner);
12033     }
12034   }
12035 }
12036 
12037 /// Check a property assign to see if it's likely to cause a retain cycle.
12038 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12039   RetainCycleOwner owner;
12040   if (!findRetainCycleOwner(*this, receiver, owner))
12041     return;
12042 
12043   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12044     diagnoseRetainCycle(*this, capturer, owner);
12045 }
12046 
12047 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12048   RetainCycleOwner Owner;
12049   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
12050     return;
12051 
12052   // Because we don't have an expression for the variable, we have to set the
12053   // location explicitly here.
12054   Owner.Loc = Var->getLocation();
12055   Owner.Range = Var->getSourceRange();
12056 
12057   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12058     diagnoseRetainCycle(*this, Capturer, Owner);
12059 }
12060 
12061 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12062                                      Expr *RHS, bool isProperty) {
12063   // Check if RHS is an Objective-C object literal, which also can get
12064   // immediately zapped in a weak reference.  Note that we explicitly
12065   // allow ObjCStringLiterals, since those are designed to never really die.
12066   RHS = RHS->IgnoreParenImpCasts();
12067 
12068   // This enum needs to match with the 'select' in
12069   // warn_objc_arc_literal_assign (off-by-1).
12070   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12071   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12072     return false;
12073 
12074   S.Diag(Loc, diag::warn_arc_literal_assign)
12075     << (unsigned) Kind
12076     << (isProperty ? 0 : 1)
12077     << RHS->getSourceRange();
12078 
12079   return true;
12080 }
12081 
12082 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12083                                     Qualifiers::ObjCLifetime LT,
12084                                     Expr *RHS, bool isProperty) {
12085   // Strip off any implicit cast added to get to the one ARC-specific.
12086   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12087     if (cast->getCastKind() == CK_ARCConsumeObject) {
12088       S.Diag(Loc, diag::warn_arc_retained_assign)
12089         << (LT == Qualifiers::OCL_ExplicitNone)
12090         << (isProperty ? 0 : 1)
12091         << RHS->getSourceRange();
12092       return true;
12093     }
12094     RHS = cast->getSubExpr();
12095   }
12096 
12097   if (LT == Qualifiers::OCL_Weak &&
12098       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12099     return true;
12100 
12101   return false;
12102 }
12103 
12104 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12105                               QualType LHS, Expr *RHS) {
12106   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12107 
12108   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12109     return false;
12110 
12111   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12112     return true;
12113 
12114   return false;
12115 }
12116 
12117 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12118                               Expr *LHS, Expr *RHS) {
12119   QualType LHSType;
12120   // PropertyRef on LHS type need be directly obtained from
12121   // its declaration as it has a PseudoType.
12122   ObjCPropertyRefExpr *PRE
12123     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12124   if (PRE && !PRE->isImplicitProperty()) {
12125     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12126     if (PD)
12127       LHSType = PD->getType();
12128   }
12129 
12130   if (LHSType.isNull())
12131     LHSType = LHS->getType();
12132 
12133   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12134 
12135   if (LT == Qualifiers::OCL_Weak) {
12136     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
12137       getCurFunction()->markSafeWeakUse(LHS);
12138   }
12139 
12140   if (checkUnsafeAssigns(Loc, LHSType, RHS))
12141     return;
12142 
12143   // FIXME. Check for other life times.
12144   if (LT != Qualifiers::OCL_None)
12145     return;
12146 
12147   if (PRE) {
12148     if (PRE->isImplicitProperty())
12149       return;
12150     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12151     if (!PD)
12152       return;
12153 
12154     unsigned Attributes = PD->getPropertyAttributes();
12155     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
12156       // when 'assign' attribute was not explicitly specified
12157       // by user, ignore it and rely on property type itself
12158       // for lifetime info.
12159       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12160       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12161           LHSType->isObjCRetainableType())
12162         return;
12163 
12164       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12165         if (cast->getCastKind() == CK_ARCConsumeObject) {
12166           Diag(Loc, diag::warn_arc_retained_property_assign)
12167           << RHS->getSourceRange();
12168           return;
12169         }
12170         RHS = cast->getSubExpr();
12171       }
12172     }
12173     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
12174       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12175         return;
12176     }
12177   }
12178 }
12179 
12180 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12181 
12182 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12183                                         SourceLocation StmtLoc,
12184                                         const NullStmt *Body) {
12185   // Do not warn if the body is a macro that expands to nothing, e.g:
12186   //
12187   // #define CALL(x)
12188   // if (condition)
12189   //   CALL(0);
12190   if (Body->hasLeadingEmptyMacro())
12191     return false;
12192 
12193   // Get line numbers of statement and body.
12194   bool StmtLineInvalid;
12195   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
12196                                                       &StmtLineInvalid);
12197   if (StmtLineInvalid)
12198     return false;
12199 
12200   bool BodyLineInvalid;
12201   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12202                                                       &BodyLineInvalid);
12203   if (BodyLineInvalid)
12204     return false;
12205 
12206   // Warn if null statement and body are on the same line.
12207   if (StmtLine != BodyLine)
12208     return false;
12209 
12210   return true;
12211 }
12212 
12213 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12214                                  const Stmt *Body,
12215                                  unsigned DiagID) {
12216   // Since this is a syntactic check, don't emit diagnostic for template
12217   // instantiations, this just adds noise.
12218   if (CurrentInstantiationScope)
12219     return;
12220 
12221   // The body should be a null statement.
12222   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12223   if (!NBody)
12224     return;
12225 
12226   // Do the usual checks.
12227   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12228     return;
12229 
12230   Diag(NBody->getSemiLoc(), DiagID);
12231   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12232 }
12233 
12234 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12235                                  const Stmt *PossibleBody) {
12236   assert(!CurrentInstantiationScope); // Ensured by caller
12237 
12238   SourceLocation StmtLoc;
12239   const Stmt *Body;
12240   unsigned DiagID;
12241   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12242     StmtLoc = FS->getRParenLoc();
12243     Body = FS->getBody();
12244     DiagID = diag::warn_empty_for_body;
12245   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12246     StmtLoc = WS->getCond()->getSourceRange().getEnd();
12247     Body = WS->getBody();
12248     DiagID = diag::warn_empty_while_body;
12249   } else
12250     return; // Neither `for' nor `while'.
12251 
12252   // The body should be a null statement.
12253   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12254   if (!NBody)
12255     return;
12256 
12257   // Skip expensive checks if diagnostic is disabled.
12258   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
12259     return;
12260 
12261   // Do the usual checks.
12262   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12263     return;
12264 
12265   // `for(...);' and `while(...);' are popular idioms, so in order to keep
12266   // noise level low, emit diagnostics only if for/while is followed by a
12267   // CompoundStmt, e.g.:
12268   //    for (int i = 0; i < n; i++);
12269   //    {
12270   //      a(i);
12271   //    }
12272   // or if for/while is followed by a statement with more indentation
12273   // than for/while itself:
12274   //    for (int i = 0; i < n; i++);
12275   //      a(i);
12276   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12277   if (!ProbableTypo) {
12278     bool BodyColInvalid;
12279     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12280                              PossibleBody->getLocStart(),
12281                              &BodyColInvalid);
12282     if (BodyColInvalid)
12283       return;
12284 
12285     bool StmtColInvalid;
12286     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12287                              S->getLocStart(),
12288                              &StmtColInvalid);
12289     if (StmtColInvalid)
12290       return;
12291 
12292     if (BodyCol > StmtCol)
12293       ProbableTypo = true;
12294   }
12295 
12296   if (ProbableTypo) {
12297     Diag(NBody->getSemiLoc(), DiagID);
12298     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12299   }
12300 }
12301 
12302 //===--- CHECK: Warn on self move with std::move. -------------------------===//
12303 
12304 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12305 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12306                              SourceLocation OpLoc) {
12307   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12308     return;
12309 
12310   if (inTemplateInstantiation())
12311     return;
12312 
12313   // Strip parens and casts away.
12314   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12315   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12316 
12317   // Check for a call expression
12318   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12319   if (!CE || CE->getNumArgs() != 1)
12320     return;
12321 
12322   // Check for a call to std::move
12323   if (!CE->isCallToStdMove())
12324     return;
12325 
12326   // Get argument from std::move
12327   RHSExpr = CE->getArg(0);
12328 
12329   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12330   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12331 
12332   // Two DeclRefExpr's, check that the decls are the same.
12333   if (LHSDeclRef && RHSDeclRef) {
12334     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12335       return;
12336     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12337         RHSDeclRef->getDecl()->getCanonicalDecl())
12338       return;
12339 
12340     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12341                                         << LHSExpr->getSourceRange()
12342                                         << RHSExpr->getSourceRange();
12343     return;
12344   }
12345 
12346   // Member variables require a different approach to check for self moves.
12347   // MemberExpr's are the same if every nested MemberExpr refers to the same
12348   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12349   // the base Expr's are CXXThisExpr's.
12350   const Expr *LHSBase = LHSExpr;
12351   const Expr *RHSBase = RHSExpr;
12352   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12353   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12354   if (!LHSME || !RHSME)
12355     return;
12356 
12357   while (LHSME && RHSME) {
12358     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12359         RHSME->getMemberDecl()->getCanonicalDecl())
12360       return;
12361 
12362     LHSBase = LHSME->getBase();
12363     RHSBase = RHSME->getBase();
12364     LHSME = dyn_cast<MemberExpr>(LHSBase);
12365     RHSME = dyn_cast<MemberExpr>(RHSBase);
12366   }
12367 
12368   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12369   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12370   if (LHSDeclRef && RHSDeclRef) {
12371     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12372       return;
12373     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12374         RHSDeclRef->getDecl()->getCanonicalDecl())
12375       return;
12376 
12377     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12378                                         << LHSExpr->getSourceRange()
12379                                         << RHSExpr->getSourceRange();
12380     return;
12381   }
12382 
12383   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12384     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12385                                         << LHSExpr->getSourceRange()
12386                                         << RHSExpr->getSourceRange();
12387 }
12388 
12389 //===--- Layout compatibility ----------------------------------------------//
12390 
12391 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
12392 
12393 /// Check if two enumeration types are layout-compatible.
12394 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
12395   // C++11 [dcl.enum] p8:
12396   // Two enumeration types are layout-compatible if they have the same
12397   // underlying type.
12398   return ED1->isComplete() && ED2->isComplete() &&
12399          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12400 }
12401 
12402 /// Check if two fields are layout-compatible.
12403 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12404                                FieldDecl *Field2) {
12405   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12406     return false;
12407 
12408   if (Field1->isBitField() != Field2->isBitField())
12409     return false;
12410 
12411   if (Field1->isBitField()) {
12412     // Make sure that the bit-fields are the same length.
12413     unsigned Bits1 = Field1->getBitWidthValue(C);
12414     unsigned Bits2 = Field2->getBitWidthValue(C);
12415 
12416     if (Bits1 != Bits2)
12417       return false;
12418   }
12419 
12420   return true;
12421 }
12422 
12423 /// Check if two standard-layout structs are layout-compatible.
12424 /// (C++11 [class.mem] p17)
12425 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12426                                      RecordDecl *RD2) {
12427   // If both records are C++ classes, check that base classes match.
12428   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12429     // If one of records is a CXXRecordDecl we are in C++ mode,
12430     // thus the other one is a CXXRecordDecl, too.
12431     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12432     // Check number of base classes.
12433     if (D1CXX->getNumBases() != D2CXX->getNumBases())
12434       return false;
12435 
12436     // Check the base classes.
12437     for (CXXRecordDecl::base_class_const_iterator
12438                Base1 = D1CXX->bases_begin(),
12439            BaseEnd1 = D1CXX->bases_end(),
12440               Base2 = D2CXX->bases_begin();
12441          Base1 != BaseEnd1;
12442          ++Base1, ++Base2) {
12443       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12444         return false;
12445     }
12446   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12447     // If only RD2 is a C++ class, it should have zero base classes.
12448     if (D2CXX->getNumBases() > 0)
12449       return false;
12450   }
12451 
12452   // Check the fields.
12453   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12454                              Field2End = RD2->field_end(),
12455                              Field1 = RD1->field_begin(),
12456                              Field1End = RD1->field_end();
12457   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12458     if (!isLayoutCompatible(C, *Field1, *Field2))
12459       return false;
12460   }
12461   if (Field1 != Field1End || Field2 != Field2End)
12462     return false;
12463 
12464   return true;
12465 }
12466 
12467 /// Check if two standard-layout unions are layout-compatible.
12468 /// (C++11 [class.mem] p18)
12469 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12470                                     RecordDecl *RD2) {
12471   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12472   for (auto *Field2 : RD2->fields())
12473     UnmatchedFields.insert(Field2);
12474 
12475   for (auto *Field1 : RD1->fields()) {
12476     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12477         I = UnmatchedFields.begin(),
12478         E = UnmatchedFields.end();
12479 
12480     for ( ; I != E; ++I) {
12481       if (isLayoutCompatible(C, Field1, *I)) {
12482         bool Result = UnmatchedFields.erase(*I);
12483         (void) Result;
12484         assert(Result);
12485         break;
12486       }
12487     }
12488     if (I == E)
12489       return false;
12490   }
12491 
12492   return UnmatchedFields.empty();
12493 }
12494 
12495 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12496                                RecordDecl *RD2) {
12497   if (RD1->isUnion() != RD2->isUnion())
12498     return false;
12499 
12500   if (RD1->isUnion())
12501     return isLayoutCompatibleUnion(C, RD1, RD2);
12502   else
12503     return isLayoutCompatibleStruct(C, RD1, RD2);
12504 }
12505 
12506 /// Check if two types are layout-compatible in C++11 sense.
12507 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12508   if (T1.isNull() || T2.isNull())
12509     return false;
12510 
12511   // C++11 [basic.types] p11:
12512   // If two types T1 and T2 are the same type, then T1 and T2 are
12513   // layout-compatible types.
12514   if (C.hasSameType(T1, T2))
12515     return true;
12516 
12517   T1 = T1.getCanonicalType().getUnqualifiedType();
12518   T2 = T2.getCanonicalType().getUnqualifiedType();
12519 
12520   const Type::TypeClass TC1 = T1->getTypeClass();
12521   const Type::TypeClass TC2 = T2->getTypeClass();
12522 
12523   if (TC1 != TC2)
12524     return false;
12525 
12526   if (TC1 == Type::Enum) {
12527     return isLayoutCompatible(C,
12528                               cast<EnumType>(T1)->getDecl(),
12529                               cast<EnumType>(T2)->getDecl());
12530   } else if (TC1 == Type::Record) {
12531     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12532       return false;
12533 
12534     return isLayoutCompatible(C,
12535                               cast<RecordType>(T1)->getDecl(),
12536                               cast<RecordType>(T2)->getDecl());
12537   }
12538 
12539   return false;
12540 }
12541 
12542 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12543 
12544 /// Given a type tag expression find the type tag itself.
12545 ///
12546 /// \param TypeExpr Type tag expression, as it appears in user's code.
12547 ///
12548 /// \param VD Declaration of an identifier that appears in a type tag.
12549 ///
12550 /// \param MagicValue Type tag magic value.
12551 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12552                             const ValueDecl **VD, uint64_t *MagicValue) {
12553   while(true) {
12554     if (!TypeExpr)
12555       return false;
12556 
12557     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12558 
12559     switch (TypeExpr->getStmtClass()) {
12560     case Stmt::UnaryOperatorClass: {
12561       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12562       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12563         TypeExpr = UO->getSubExpr();
12564         continue;
12565       }
12566       return false;
12567     }
12568 
12569     case Stmt::DeclRefExprClass: {
12570       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12571       *VD = DRE->getDecl();
12572       return true;
12573     }
12574 
12575     case Stmt::IntegerLiteralClass: {
12576       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12577       llvm::APInt MagicValueAPInt = IL->getValue();
12578       if (MagicValueAPInt.getActiveBits() <= 64) {
12579         *MagicValue = MagicValueAPInt.getZExtValue();
12580         return true;
12581       } else
12582         return false;
12583     }
12584 
12585     case Stmt::BinaryConditionalOperatorClass:
12586     case Stmt::ConditionalOperatorClass: {
12587       const AbstractConditionalOperator *ACO =
12588           cast<AbstractConditionalOperator>(TypeExpr);
12589       bool Result;
12590       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12591         if (Result)
12592           TypeExpr = ACO->getTrueExpr();
12593         else
12594           TypeExpr = ACO->getFalseExpr();
12595         continue;
12596       }
12597       return false;
12598     }
12599 
12600     case Stmt::BinaryOperatorClass: {
12601       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12602       if (BO->getOpcode() == BO_Comma) {
12603         TypeExpr = BO->getRHS();
12604         continue;
12605       }
12606       return false;
12607     }
12608 
12609     default:
12610       return false;
12611     }
12612   }
12613 }
12614 
12615 /// Retrieve the C type corresponding to type tag TypeExpr.
12616 ///
12617 /// \param TypeExpr Expression that specifies a type tag.
12618 ///
12619 /// \param MagicValues Registered magic values.
12620 ///
12621 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12622 ///        kind.
12623 ///
12624 /// \param TypeInfo Information about the corresponding C type.
12625 ///
12626 /// \returns true if the corresponding C type was found.
12627 static bool GetMatchingCType(
12628         const IdentifierInfo *ArgumentKind,
12629         const Expr *TypeExpr, const ASTContext &Ctx,
12630         const llvm::DenseMap<Sema::TypeTagMagicValue,
12631                              Sema::TypeTagData> *MagicValues,
12632         bool &FoundWrongKind,
12633         Sema::TypeTagData &TypeInfo) {
12634   FoundWrongKind = false;
12635 
12636   // Variable declaration that has type_tag_for_datatype attribute.
12637   const ValueDecl *VD = nullptr;
12638 
12639   uint64_t MagicValue;
12640 
12641   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12642     return false;
12643 
12644   if (VD) {
12645     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12646       if (I->getArgumentKind() != ArgumentKind) {
12647         FoundWrongKind = true;
12648         return false;
12649       }
12650       TypeInfo.Type = I->getMatchingCType();
12651       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12652       TypeInfo.MustBeNull = I->getMustBeNull();
12653       return true;
12654     }
12655     return false;
12656   }
12657 
12658   if (!MagicValues)
12659     return false;
12660 
12661   llvm::DenseMap<Sema::TypeTagMagicValue,
12662                  Sema::TypeTagData>::const_iterator I =
12663       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12664   if (I == MagicValues->end())
12665     return false;
12666 
12667   TypeInfo = I->second;
12668   return true;
12669 }
12670 
12671 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12672                                       uint64_t MagicValue, QualType Type,
12673                                       bool LayoutCompatible,
12674                                       bool MustBeNull) {
12675   if (!TypeTagForDatatypeMagicValues)
12676     TypeTagForDatatypeMagicValues.reset(
12677         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12678 
12679   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12680   (*TypeTagForDatatypeMagicValues)[Magic] =
12681       TypeTagData(Type, LayoutCompatible, MustBeNull);
12682 }
12683 
12684 static bool IsSameCharType(QualType T1, QualType T2) {
12685   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12686   if (!BT1)
12687     return false;
12688 
12689   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12690   if (!BT2)
12691     return false;
12692 
12693   BuiltinType::Kind T1Kind = BT1->getKind();
12694   BuiltinType::Kind T2Kind = BT2->getKind();
12695 
12696   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12697          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12698          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12699          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12700 }
12701 
12702 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12703                                     const ArrayRef<const Expr *> ExprArgs,
12704                                     SourceLocation CallSiteLoc) {
12705   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12706   bool IsPointerAttr = Attr->getIsPointer();
12707 
12708   // Retrieve the argument representing the 'type_tag'.
12709   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12710   if (TypeTagIdxAST >= ExprArgs.size()) {
12711     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12712         << 0 << Attr->getTypeTagIdx().getSourceIndex();
12713     return;
12714   }
12715   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12716   bool FoundWrongKind;
12717   TypeTagData TypeInfo;
12718   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12719                         TypeTagForDatatypeMagicValues.get(),
12720                         FoundWrongKind, TypeInfo)) {
12721     if (FoundWrongKind)
12722       Diag(TypeTagExpr->getExprLoc(),
12723            diag::warn_type_tag_for_datatype_wrong_kind)
12724         << TypeTagExpr->getSourceRange();
12725     return;
12726   }
12727 
12728   // Retrieve the argument representing the 'arg_idx'.
12729   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12730   if (ArgumentIdxAST >= ExprArgs.size()) {
12731     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12732         << 1 << Attr->getArgumentIdx().getSourceIndex();
12733     return;
12734   }
12735   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12736   if (IsPointerAttr) {
12737     // Skip implicit cast of pointer to `void *' (as a function argument).
12738     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12739       if (ICE->getType()->isVoidPointerType() &&
12740           ICE->getCastKind() == CK_BitCast)
12741         ArgumentExpr = ICE->getSubExpr();
12742   }
12743   QualType ArgumentType = ArgumentExpr->getType();
12744 
12745   // Passing a `void*' pointer shouldn't trigger a warning.
12746   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12747     return;
12748 
12749   if (TypeInfo.MustBeNull) {
12750     // Type tag with matching void type requires a null pointer.
12751     if (!ArgumentExpr->isNullPointerConstant(Context,
12752                                              Expr::NPC_ValueDependentIsNotNull)) {
12753       Diag(ArgumentExpr->getExprLoc(),
12754            diag::warn_type_safety_null_pointer_required)
12755           << ArgumentKind->getName()
12756           << ArgumentExpr->getSourceRange()
12757           << TypeTagExpr->getSourceRange();
12758     }
12759     return;
12760   }
12761 
12762   QualType RequiredType = TypeInfo.Type;
12763   if (IsPointerAttr)
12764     RequiredType = Context.getPointerType(RequiredType);
12765 
12766   bool mismatch = false;
12767   if (!TypeInfo.LayoutCompatible) {
12768     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12769 
12770     // C++11 [basic.fundamental] p1:
12771     // Plain char, signed char, and unsigned char are three distinct types.
12772     //
12773     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12774     // char' depending on the current char signedness mode.
12775     if (mismatch)
12776       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12777                                            RequiredType->getPointeeType())) ||
12778           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12779         mismatch = false;
12780   } else
12781     if (IsPointerAttr)
12782       mismatch = !isLayoutCompatible(Context,
12783                                      ArgumentType->getPointeeType(),
12784                                      RequiredType->getPointeeType());
12785     else
12786       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12787 
12788   if (mismatch)
12789     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12790         << ArgumentType << ArgumentKind
12791         << TypeInfo.LayoutCompatible << RequiredType
12792         << ArgumentExpr->getSourceRange()
12793         << TypeTagExpr->getSourceRange();
12794 }
12795 
12796 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12797                                          CharUnits Alignment) {
12798   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12799 }
12800 
12801 void Sema::DiagnoseMisalignedMembers() {
12802   for (MisalignedMember &m : MisalignedMembers) {
12803     const NamedDecl *ND = m.RD;
12804     if (ND->getName().empty()) {
12805       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12806         ND = TD;
12807     }
12808     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12809         << m.MD << ND << m.E->getSourceRange();
12810   }
12811   MisalignedMembers.clear();
12812 }
12813 
12814 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12815   E = E->IgnoreParens();
12816   if (!T->isPointerType() && !T->isIntegerType())
12817     return;
12818   if (isa<UnaryOperator>(E) &&
12819       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12820     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12821     if (isa<MemberExpr>(Op)) {
12822       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12823                           MisalignedMember(Op));
12824       if (MA != MisalignedMembers.end() &&
12825           (T->isIntegerType() ||
12826            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12827                                    Context.getTypeAlignInChars(
12828                                        T->getPointeeType()) <= MA->Alignment))))
12829         MisalignedMembers.erase(MA);
12830     }
12831   }
12832 }
12833 
12834 void Sema::RefersToMemberWithReducedAlignment(
12835     Expr *E,
12836     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12837         Action) {
12838   const auto *ME = dyn_cast<MemberExpr>(E);
12839   if (!ME)
12840     return;
12841 
12842   // No need to check expressions with an __unaligned-qualified type.
12843   if (E->getType().getQualifiers().hasUnaligned())
12844     return;
12845 
12846   // For a chain of MemberExpr like "a.b.c.d" this list
12847   // will keep FieldDecl's like [d, c, b].
12848   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12849   const MemberExpr *TopME = nullptr;
12850   bool AnyIsPacked = false;
12851   do {
12852     QualType BaseType = ME->getBase()->getType();
12853     if (ME->isArrow())
12854       BaseType = BaseType->getPointeeType();
12855     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12856     if (RD->isInvalidDecl())
12857       return;
12858 
12859     ValueDecl *MD = ME->getMemberDecl();
12860     auto *FD = dyn_cast<FieldDecl>(MD);
12861     // We do not care about non-data members.
12862     if (!FD || FD->isInvalidDecl())
12863       return;
12864 
12865     AnyIsPacked =
12866         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12867     ReverseMemberChain.push_back(FD);
12868 
12869     TopME = ME;
12870     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12871   } while (ME);
12872   assert(TopME && "We did not compute a topmost MemberExpr!");
12873 
12874   // Not the scope of this diagnostic.
12875   if (!AnyIsPacked)
12876     return;
12877 
12878   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12879   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12880   // TODO: The innermost base of the member expression may be too complicated.
12881   // For now, just disregard these cases. This is left for future
12882   // improvement.
12883   if (!DRE && !isa<CXXThisExpr>(TopBase))
12884       return;
12885 
12886   // Alignment expected by the whole expression.
12887   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12888 
12889   // No need to do anything else with this case.
12890   if (ExpectedAlignment.isOne())
12891     return;
12892 
12893   // Synthesize offset of the whole access.
12894   CharUnits Offset;
12895   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12896        I++) {
12897     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12898   }
12899 
12900   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12901   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12902       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12903 
12904   // The base expression of the innermost MemberExpr may give
12905   // stronger guarantees than the class containing the member.
12906   if (DRE && !TopME->isArrow()) {
12907     const ValueDecl *VD = DRE->getDecl();
12908     if (!VD->getType()->isReferenceType())
12909       CompleteObjectAlignment =
12910           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12911   }
12912 
12913   // Check if the synthesized offset fulfills the alignment.
12914   if (Offset % ExpectedAlignment != 0 ||
12915       // It may fulfill the offset it but the effective alignment may still be
12916       // lower than the expected expression alignment.
12917       CompleteObjectAlignment < ExpectedAlignment) {
12918     // If this happens, we want to determine a sensible culprit of this.
12919     // Intuitively, watching the chain of member expressions from right to
12920     // left, we start with the required alignment (as required by the field
12921     // type) but some packed attribute in that chain has reduced the alignment.
12922     // It may happen that another packed structure increases it again. But if
12923     // we are here such increase has not been enough. So pointing the first
12924     // FieldDecl that either is packed or else its RecordDecl is,
12925     // seems reasonable.
12926     FieldDecl *FD = nullptr;
12927     CharUnits Alignment;
12928     for (FieldDecl *FDI : ReverseMemberChain) {
12929       if (FDI->hasAttr<PackedAttr>() ||
12930           FDI->getParent()->hasAttr<PackedAttr>()) {
12931         FD = FDI;
12932         Alignment = std::min(
12933             Context.getTypeAlignInChars(FD->getType()),
12934             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12935         break;
12936       }
12937     }
12938     assert(FD && "We did not find a packed FieldDecl!");
12939     Action(E, FD->getParent(), FD, Alignment);
12940   }
12941 }
12942 
12943 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12944   using namespace std::placeholders;
12945 
12946   RefersToMemberWithReducedAlignment(
12947       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12948                      _2, _3, _4));
12949 }
12950